_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q182300
IsLeader
test
func (c *Candidate) IsLeader() bool { c.lock.Lock() defer c.lock.Unlock() return c.leader }
go
{ "resource": "" }
q182301
NewResponse
test
func NewResponse(clientID, redirectURI, userID, exp, code string) Response { return Response{ClientID: clientID, RedirectURI: redirectURI, UserID: userID, Exp: exp, Code: code} }
go
{ "resource": "" }
q182302
GetRequestID
test
func GetRequestID(ctx context.Context) (string, error) { if ctx == nil { return "", errors.New("nil context") } reqID, ok := ctx.Value(contextRequestID).(string) if !ok { return "", errors.New("unexpected type") } if len(reqID) == 0 { return "", errors.New("empty value in context") } return reqID, nil }
go
{ "resource": "" }
q182303
Log
test
func (m *monitorableWriter) Log() { duration := time.Now().Sub(m.t0) if m.Code == 0 { m.Code = 200 } if m.opts.Filter != nil && !m.opts.Filter(m.r, m.Code, duration, m.Size) { return //skip } cc := m.colorCode() size := "" if m.Size > 0 { size = sizestr.ToString(m.Size) } buff := bytes.Buffer{} m.opts.formatTmpl.Execute(&buff, &struct { *Colors Timestamp, Method, Path, CodeColor string Code int Duration, Size, IP string }{ m.opts.Colors, m.t0.Format(m.opts.TimeFormat), m.method, m.path, cc, m.Code, fmtDuration(duration), size, m.ip, }) //fmt is threadsafe :) fmt.Fprint(m.opts.Writer, buff.String()) }
go
{ "resource": "" }
q182304
SendMailSSL
test
func SendMailSSL(addr string, a smtp.Auth, from string, to []string, msg []byte) error { conn, err := tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true}) //TODO: Not secure if err != nil { log.Println("Error Dialing", err) return err } h, _, _ := net.SplitHostPort(addr) c, err := smtp.NewClient(conn, h) if err != nil { log.Println("Error SMTP connection", err) return err } defer c.Close() if a != nil { if ok, _ := c.Extension("AUTH"); ok { if err = c.Auth(a); err != nil { log.Printf("Authentication error: %v", err) return err } } } if err = c.Mail(from); err != nil { log.Printf("From error: %v", err) return err } for _, addr := range to { if err = c.Rcpt(addr); err != nil { log.Printf("Recipient error: %v", err) return err } } w, err := c.Data() if err != nil { return err } w.Write(msg) w.Close() return c.Quit() }
go
{ "resource": "" }
q182305
Send
test
func (m *MailService) Send(message string, subject string, from string, to string) (err error) { t := []string{to} msg := []byte("From: " + from + "\r\n" + "To: " + to + "\r\n" + "Subject: " + subject + "\r\n" + "\r\n" + message + "\r\n") err = m.SMTP.SendMail(from, t, msg) return }
go
{ "resource": "" }
q182306
WaitForIt
test
func WaitForIt(fullConn, host string, port, timeout int) error { // fullConn := flag.String("full-connection", "", "full connection") // host := flag.String("host", "", "host to connect") // port := flag.Int("port", 80, "port to connect") // timeout := flag.Int("timeout", 10, "time to wait until port become available") // printVersion := flag.Bool("v", false, "show the current version") // debug = flag.Bool("debug", false, "enable debug") // flag.Parse() // if *printVersion { // fmt.Println("waitforit version " + VERSION) // return // } conn := buildConn(host, port, fullConn) if conn == nil { return errors.New("Invalid connection") } log.Debug("Waiting " + strconv.Itoa(timeout) + " seconds") if err := pingTCP(conn, timeout); err != nil { return err } if conn.Scheme != "http" && conn.Scheme != "https" { return nil } if err := pingHTTP(conn, timeout); err != nil { return err } return nil }
go
{ "resource": "" }
q182307
Get
test
func Get(source interface{}, environment string, configEnv Environment) (conf interface{}, err error) { if filename, ok := source.(string); ok { source, err = ioutil.ReadFile(filename) if err != nil { log.Printf("Fatal: %v", err) return } } err = yaml.Unmarshal(source.([]byte), configEnv) if err != nil { log.Printf("Fatal: bad config : %v", err) return } conf = configEnv.GetEnvironment(environment) if conf == nil { err = errors.New("No configuration") return } return }
go
{ "resource": "" }
q182308
initConfig
test
func initConfig() { if cfgFile != "" { // enable ability to specify config file via flag Viper.SetConfigFile(cfgFile) } Viper.SetConfigName("config") // name of config file (without extension) Viper.AddConfigPath("$HOME") // adding home directory as first search path Viper.AddConfigPath("./") // adding local directory as second search path Viper.AutomaticEnv() // read in environment variables that match // If a config file is found, read it in. if err := Viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", Viper.ConfigFileUsed()) } }
go
{ "resource": "" }
q182309
WritePluginResultsToDatabase
test
func WritePluginResultsToDatabase(results map[string]interface{}) { // connect to RethinkDB session, err := r.Connect(r.ConnectOpts{ Address: fmt.Sprintf("%s:28015", utils.Getopt("MALICE_RETHINKDB", "rethink")), Timeout: 5 * time.Second, Database: "malice", }) if err != nil { log.Debug(err) return } defer session.Close() res, err := r.Table("samples").Get(results["ID"]).Run(session) utils.Assert(err) defer res.Close() if res.IsNil() { // upsert into RethinkDB resp, err := r.Table("samples").Insert(results, r.InsertOpts{Conflict: "replace"}).RunWrite(session) utils.Assert(err) log.Debug(resp) } else { resp, err := r.Table("samples").Get(results["ID"]).Update(map[string]interface{}{ "plugins": map[string]interface{}{ category: map[string]interface{}{ name: results["Data"], }, }, }).RunWrite(session) utils.Assert(err) log.Debug(resp) } }
go
{ "resource": "" }
q182310
NewAuthController
test
func NewAuthController(um UserManager, cnf web.Config) *AuthController { authController := AuthController{UserManager: um, cnf: cnf} return &authController }
go
{ "resource": "" }
q182311
Authenticate
test
func (c *AuthController) Authenticate(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) var user User var data map[string]string err := decoder.Decode(&user) if err != nil { http.Error(w, fmt.Sprintf("%v", err), 400) return } user, _ = c.UserManager.Get(user.Username, user.Password) if user.Username != "" { token := jwt.New(jwt.GetSigningMethod("HS256")) claims := token.Claims.(jwt.MapClaims) claims["username"] = user.Username claims["email"] = user.Email claims["exp"] = time.Now().Add(time.Minute * 10).Unix() tokenString, _ := token.SignedString([]byte(c.cnf.Jwt.Key)) data = map[string]string{ "id_token": tokenString, } } js, _ := json.Marshal(data) w.Write(js) }
go
{ "resource": "" }
q182312
NewOAuth2Controller
test
func NewOAuth2Controller(am ApplicationManager, cnf web.Config) *OAuth2Controller { oAuth2Controller := OAuth2Controller{cnf: cnf, ApplicationManager: am} return &oAuth2Controller }
go
{ "resource": "" }
q182313
Refresh
test
func (c *OAuth2Controller) Refresh(w http.ResponseWriter, r *http.Request) { grantType := r.URL.Query().Get("grant_type") refreshToken := r.URL.Query().Get("refresh_token") if strings.Compare(grantType, "refresh_token") != 0 { http.Error(w, errors.New("Parameter grant_type is required").Error(), http.StatusBadRequest) return } if strings.Compare(refreshToken, "") == 0 { http.Error(w, errors.New("Parameter refreshToken is required").Error(), http.StatusBadRequest) return } token, err := jwt.Parse(refreshToken, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } return []byte(c.cnf.Jwt.Key), nil }) if err == nil && token.Valid { token := jwt.New(jwt.GetSigningMethod("HS256")) claims := token.Claims.(jwt.MapClaims) claims["exp"] = time.Now().Add(time.Hour * 1).Unix() tokenString, _ := token.SignedString([]byte(c.cnf.Jwt.Key)) data := map[string]string{ "access_token": tokenString, "token_type": "bearer", "expires_in": "3600", } js, _ := json.Marshal(data) w.Write(js) } }
go
{ "resource": "" }
q182314
Token
test
func (c *OAuth2Controller) Token(w http.ResponseWriter, r *http.Request) { grantType := r.URL.Query().Get("grant_type") code := r.URL.Query().Get("code") if strings.Compare(grantType, "authorization_code") != 0 { http.Error(w, errors.New("Parameter grant_type is required").Error(), http.StatusBadRequest) return } if strings.Compare(code, "") == 0 { http.Error(w, errors.New("Parameter code is required").Error(), http.StatusBadRequest) return } response, err := DecodeOAuth2Code(code, c.cnf.Jwt.Key) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } i, err := strconv.ParseInt(response.Exp, 10, 64) exp := time.Unix(i, 0) if exp.After(time.Now()) { log.Printf("Code is expired") } else { token := jwt.New(jwt.GetSigningMethod("HS256")) claims := token.Claims.(jwt.MapClaims) claims["exp"] = time.Now().Add(time.Hour * 1).Unix() tokenString, _ := token.SignedString([]byte(c.cnf.Jwt.Key)) refreshToken := jwt.New(jwt.GetSigningMethod("HS256")) refreshClaims := refreshToken.Claims.(jwt.MapClaims) refreshClaims["exp"] = 0 refreshTokenString, _ := refreshToken.SignedString([]byte(c.cnf.Jwt.Key)) data := map[string]string{ "access_token": tokenString, "token_type": "bearer", "refresh_token": refreshTokenString, "expires_in": "3600", } js, _ := json.Marshal(data) w.Write(js) } }
go
{ "resource": "" }
q182315
Logging
test
func Logging(next http.Handler, log *logrus.Logger) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srw := StatusResponseWriter{w, 0, 0} start := time.Now() next.ServeHTTP(&srw, r) end := time.Now() latency := end.Sub(start) log.WithField("client", r.RemoteAddr).WithField("latency", latency).WithField("length", srw.Length()).WithField("code", srw.Status()).Printf("%s %s %s", r.Method, r.URL, r.Proto) }) }
go
{ "resource": "" }
q182316
SingleFile
test
func SingleFile(filename string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, filename) }) }
go
{ "resource": "" }
q182317
Write
test
func (w *StatusResponseWriter) Write(data []byte) (int, error) { w.length = len(data) return w.ResponseWriter.Write(data) }
go
{ "resource": "" }
q182318
Hijack
test
func (w *StatusResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if hj, ok := w.ResponseWriter.(http.Hijacker); ok { return hj.Hijack() } return nil, nil, errors.New("Not a Hijacker") }
go
{ "resource": "" }
q182319
NewMongo
test
func NewMongo(filename string, environment string) (*Mongo, error) { ctx := context.Background() cnf, err := GetMongo(filename, environment) if err != nil { return nil, err } var uri string if len(cnf.Username) > 0 && len(cnf.Password) > 0 { uri = fmt.Sprintf(`mongodb://%s:%s@%s:%d/%s`, cnf.Username, cnf.Password, cnf.Host, cnf.Port, cnf.Database, ) } else { uri = fmt.Sprintf(`mongodb://%s:%d/%s`, cnf.Host, cnf.Port, cnf.Database, ) } client, err := mongo.NewClient(uri) if err != nil { log.Printf("L'URI du serveur MongoDB est incorrect: %s", uri) return nil, err } err = client.Connect(ctx) if err != nil { log.Print("Impossible d'utiliser ce context") return nil, err } db := client.Database(cnf.Database) err = client.Ping(ctx, nil) if err != nil { log.Printf("Impossible de contacter %v sur le port %d", cnf.Host, cnf.Port) return nil, err } return &Mongo{Client: client, Database: db, context: ctx}, nil }
go
{ "resource": "" }
q182320
Disconnect
test
func (m *Mongo) Disconnect() error { err := m.Client.Disconnect(m.context) if err != nil { log.Printf("Impossible de fermer la connexion") return err } return nil }
go
{ "resource": "" }
q182321
New
test
func New(fields []string) *Table { return &Table{ Fields: fields, Rows: make([]map[string]string, 0), fieldSizes: make(map[string]int), } }
go
{ "resource": "" }
q182322
PrintTable
test
func PrintTable(fields []string, rows []map[string]interface{}) { table := New(fields) for _, r := range rows { table.AddRow(r) } table.Print() }
go
{ "resource": "" }
q182323
PrintHorizontal
test
func PrintHorizontal(m map[string]interface{}) { table := New([]string{"Key", "Value"}) rows := mapToRows(m) for _, row := range rows { table.AddRow(row) } table.HideHead = true table.Print() }
go
{ "resource": "" }
q182324
PrintRow
test
func PrintRow(fields []string, row map[string]interface{}) { table := New(fields) table.AddRow(row) table.Print() }
go
{ "resource": "" }
q182325
AddRow
test
func (t *Table) AddRow(row map[string]interface{}) { newRow := make(map[string]string) for _, k := range t.Fields { v := row[k] // If is not nil format // else value is empty string var val string if v == nil { val = "" } else { val = fmt.Sprintf("%v", v) } newRow[k] = val } t.calculateSizes(newRow) if len(newRow) > 0 { t.Rows = append(t.Rows, newRow) } }
go
{ "resource": "" }
q182326
Print
test
func (t *Table) Print() { if len(t.Rows) == 0 && t.Footer == nil { return } t.calculateSizes(t.Footer) if !t.Markdown { t.printDash() } if !t.HideHead { fmt.Println(t.getHead()) t.printTableDash() } for _, r := range t.Rows { fmt.Println(t.rowString(r)) if !t.Markdown { t.printDash() } } if t.Footer != nil { t.printTableDash() fmt.Println(t.rowString(t.Footer)) if !t.Markdown { t.printTableDash() } } }
go
{ "resource": "" }
q182327
String
test
func (t *Table) String(title string) string { tableString := []string{} if len(t.Rows) == 0 && t.Footer == nil { return "" } tableString = append(tableString, "### "+title) t.calculateSizes(t.Footer) if !t.Markdown { // t.printDash() tableString = append(tableString, t.stringDash()) } if !t.HideHead { tableString = append(tableString, t.getHead()) tableString = append(tableString, t.stringTableDash()) // fmt.Println(t.getHead()) // t.printTableDash() } for _, r := range t.Rows { // fmt.Println(t.rowString(r)) tableString = append(tableString, t.rowString(r)) if !t.Markdown { tableString = append(tableString, t.stringDash()) } } if t.Footer != nil { tableString = append(tableString, t.stringTableDash()) tableString = append(tableString, t.rowString(t.Footer)) if !t.Markdown { tableString = append(tableString, t.stringDash()) } } return strings.Join(tableString[:], "\n") }
go
{ "resource": "" }
q182328
getHead
test
func (t *Table) getHead() string { s := "|" for _, name := range t.Fields { s += t.fieldString(name, strings.Title(name)) + "|" } return s }
go
{ "resource": "" }
q182329
rowString
test
func (t *Table) rowString(row map[string]string) string { s := "|" for _, name := range t.Fields { value := row[name] s += t.fieldString(name, value) + "|" } return s }
go
{ "resource": "" }
q182330
fieldString
test
func (t *Table) fieldString(name, value string) string { value = fmt.Sprintf(" %s ", value) spacesLeft := t.fieldSizes[name] - runewidth.StringWidth(value) if spacesLeft > 0 { for i := 0; i < spacesLeft; i++ { value += " " } } return value }
go
{ "resource": "" }
q182331
stringTableDash
test
func (t *Table) stringTableDash() string { if t.Markdown { return t.stringMarkdownDash() } return t.stringDash() }
go
{ "resource": "" }
q182332
printMarkdownDash
test
func (t *Table) printMarkdownDash() { r := make(map[string]string) for _, name := range t.Fields { r[name] = strings.Repeat("-", t.fieldSizes[name]-2) } fmt.Println(t.rowString(r)) }
go
{ "resource": "" }
q182333
stringMarkdownDash
test
func (t *Table) stringMarkdownDash() string { r := make(map[string]string) for _, name := range t.Fields { r[name] = strings.Repeat("-", t.fieldSizes[name]-2) } return t.rowString(r) }
go
{ "resource": "" }
q182334
HashPassword
test
func HashPassword(password []byte, salt []byte) (hash []byte, err error) { hash, err = scrypt.Key(password, salt, N, R, P, KEYLENGTH) if err != nil { return nil, err } return }
go
{ "resource": "" }
q182335
EncodeOAuth2Code
test
func EncodeOAuth2Code(clientID, redirectURI, userID, sharedKey string) (code string, err error) { rand := RandStringBytesMaskImprSrc(20) exp := time.Now().Add(time.Minute * 10).String() response := NewResponse(clientID, redirectURI, userID, exp, rand) jresponse, err := json.Marshal(response) if err != nil { log.Printf("Error: %v", err) } j64response := base64.StdEncoding.EncodeToString(jresponse) signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS512, Key: []byte(sharedKey)}, nil) if err != nil { log.Printf("Error: %v", err) } object, err := signer.Sign([]byte(j64response)) if err != nil { log.Printf("Error: %v", err) } code, err = object.CompactSerialize() return }
go
{ "resource": "" }
q182336
DecodeOAuth2Code
test
func DecodeOAuth2Code(code, sharedKey string) (response Response, err error) { object, err := jose.ParseSigned(code) if err != nil { return } output, err := object.Verify([]byte(sharedKey)) if err != nil { return } base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(output))) l, err := base64.StdEncoding.Decode(base64Text, output) if err != nil { return } response = Response{} err = json.Unmarshal(base64Text[:l], &response) return }
go
{ "resource": "" }
q182337
NewServer
test
func NewServer(filename string, environment string) (server *Server, err error) { conf, err := GetConfig(filename, environment) logFile, err := os.OpenFile(conf.Log.File+logFilename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.SetOutput(os.Stderr) log.Warningf("Can't open logfile: %v", err) } else { log.SetOutput(logFile) } level := log.ErrorLevel if strings.Compare(conf.Log.Level, "") != 0 { level, _ = log.ParseLevel(conf.Log.Level) } else { log.Infof("Log Level: %v", level) } log.SetLevel(level) server = &Server{Config: conf, Done: make(chan bool, 1), Error: make(chan error, 1), Server: http.Server{Handler: NewLoggingServeMux(conf)}, quit: make(chan bool), isStarted: false} return }
go
{ "resource": "" }
q182338
Start
test
func (s *Server) Start() (err error) { log.Infof("Lunarc is starting on port :%d", s.Config.Port) var l net.Listener go func() { l, err = net.Listen("tcp", fmt.Sprintf(":%d", s.Config.Port)) if err != nil { log.Errorf("Error: %v", err) s.Error <- err return } s.isStarted = true if len(s.Config.SSL.Certificate) > 0 && len(s.Config.SSL.Key) > 0 { err = s.ServeTLS(l, s.Config.SSL.Certificate, s.Config.SSL.Key) if err != nil && err != http.ErrServerClosed { log.Errorf("%v", err) l.Close() s.Error <- err s.quit <- true } close(s.quit) } else { err = s.Serve(l) if err != nil && err != http.ErrServerClosed { log.Errorf("%v", err) s.Error <- err s.quit <- true } close(s.quit) } }() <-s.quit if err = s.Shutdown(context.Background()); err != nil { log.Errorf("%v", err) s.Error <- err } <-s.quit l = nil log.Info("Lunarc terminated.") s.isStarted = false s.Done <- true return }
go
{ "resource": "" }
q182339
Stop
test
func (s *Server) Stop() { if s.isStarted && s.quit != nil { log.Info("Lunarc is stopping...") s.quit <- true } else { log.Info("Lunarc is not running") s.Error <- errors.New("Lunarc is not running") s.Done <- false } }
go
{ "resource": "" }
q182340
NewLoggingServeMux
test
func NewLoggingServeMux(conf Config) *LoggingServeMux { serveMux := http.NewServeMux() return &LoggingServeMux{serveMux, conf} }
go
{ "resource": "" }
q182341
Handler
test
func (mux *LoggingServeMux) Handler(r *http.Request) (h http.Handler, pattern string) { return mux.serveMux.Handler(r) }
go
{ "resource": "" }
q182342
Handle
test
func (mux *LoggingServeMux) Handle(pattern string, handler http.Handler) { var log = logrus.New() logFile, err := os.OpenFile(mux.conf.Log.File+aFilename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Out = os.Stderr log.Warningf("Can't open logfile: %v", err) } else { log.Out = logFile } mux.serveMux.Handle(pattern, Logging(handler, log)) }
go
{ "resource": "" }
q182343
HandleFunc
test
func (mux *LoggingServeMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) { mux.serveMux.Handle(pattern, http.HandlerFunc(handler)) }
go
{ "resource": "" }
q182344
Init
test
func (db *Database) Init() error { // Create URL from host/port db.getURL() // Test connection to ElasticSearch err := db.TestConnection() if err != nil { return errors.Wrap(err, "failed to connect to database") } client, err := elastic.NewSimpleClient( elastic.SetURL(db.URL), elastic.SetBasicAuth( utils.Getopts(db.Username, "MALICE_ELASTICSEARCH_USERNAME", ""), utils.Getopts(db.Password, "MALICE_ELASTICSEARCH_PASSWORD", ""), ), ) if err != nil { return errors.Wrap(err, "failed to create elasticsearch simple client") } exists, err := client.IndexExists(db.Index).Do(context.Background()) if err != nil { return errors.Wrap(err, "failed to check if index exists") } if !exists { // Index does not exist yet. createIndex, err := client.CreateIndex(db.Index).BodyString(mapping).Do(context.Background()) if err != nil { return errors.Wrapf(err, "failed to create index: %s", db.Index) } if !createIndex.Acknowledged { log.Error("index creation not acknowledged") } else { log.Debugf("created index %s", db.Index) } } else { log.Debugf("index %s already exists", db.Index) } return nil }
go
{ "resource": "" }
q182345
WaitForConnection
test
func (db *Database) WaitForConnection(ctx context.Context, timeout int) error { var err error secondsWaited := 0 connCtx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second) defer cancel() log.Debug("===> trying to connect to elasticsearch") for { // Try to connect to Elasticsearch select { case <-connCtx.Done(): return errors.Wrapf(err, "connecting to elasticsearch timed out after %d seconds", secondsWaited) default: err = db.TestConnection() if err == nil { log.Debugf("elasticsearch came online after %d seconds", secondsWaited) return nil } // not ready yet secondsWaited++ log.Debug(" * could not connect to elasticsearch (sleeping for 1 second)") time.Sleep(1 * time.Second) } } }
go
{ "resource": "" }
q182346
StoreFileInfo
test
func (db *Database) StoreFileInfo(sample map[string]interface{}) (elastic.IndexResponse, error) { if len(db.Plugins) == 0 { return elastic.IndexResponse{}, errors.New("Database.Plugins is empty (you must set this field to use this function)") } // Test connection to ElasticSearch err := db.TestConnection() if err != nil { return elastic.IndexResponse{}, errors.Wrap(err, "failed to connect to database") } client, err := elastic.NewSimpleClient( elastic.SetURL(db.URL), elastic.SetBasicAuth( utils.Getopts(db.Username, "MALICE_ELASTICSEARCH_USERNAME", ""), utils.Getopts(db.Password, "MALICE_ELASTICSEARCH_PASSWORD", ""), ), ) if err != nil { return elastic.IndexResponse{}, errors.Wrap(err, "failed to create elasticsearch simple client") } // NOTE: I am not setting ID because I want to be able to re-scan files with updated signatures in the future fInfo := map[string]interface{}{ // "id": sample.SHA256, "file": sample, "plugins": db.Plugins, "scan_date": time.Now().Format(time.RFC3339Nano), } newScan, err := client.Index(). Index(db.Index). Type(db.Type). OpType("index"). // Id("1"). BodyJson(fInfo). Do(context.Background()) if err != nil { return elastic.IndexResponse{}, errors.Wrap(err, "failed to index file info") } log.WithFields(log.Fields{ "id": newScan.Id, "index": newScan.Index, "type": newScan.Type, }).Debug("indexed sample") return *newScan, nil }
go
{ "resource": "" }
q182347
StorePluginResults
test
func (db *Database) StorePluginResults(results database.PluginResults) error { // Test connection to ElasticSearch err := db.TestConnection() if err != nil { return errors.Wrap(err, "failed to connect to database") } client, err := elastic.NewSimpleClient( elastic.SetURL(db.URL), elastic.SetBasicAuth( utils.Getopts(db.Username, "MALICE_ELASTICSEARCH_USERNAME", ""), utils.Getopts(db.Password, "MALICE_ELASTICSEARCH_PASSWORD", ""), ), ) if err != nil { return errors.Wrap(err, "failed to create elasticsearch simple client") } // get sample db record getSample, err := client.Get(). Index(db.Index). Type(db.Type). Id(results.ID). Do(context.Background()) // ignore 404 not found error if err != nil && !elastic.IsNotFound(err) { return errors.Wrapf(err, "failed to get sample with id: %s", results.ID) } if getSample != nil && getSample.Found { log.Debugf("got document %s in version %d from index %s, type %s\n", getSample.Id, getSample.Version, getSample.Index, getSample.Type) updateScan := map[string]interface{}{ "scan_date": time.Now().Format(time.RFC3339Nano), "plugins": map[string]interface{}{ results.Category: map[string]interface{}{ results.Name: results.Data, }, }, } update, err := client.Update().Index(db.Index).Type(db.Type).Id(getSample.Id). Doc(updateScan). Do(context.Background()) if err != nil { return errors.Wrapf(err, "failed to update sample with id: %s", results.ID) } log.Debugf("updated version of sample %q is now %d\n", update.Id, update.Version) } else { // ID not found so create new document with `index` command scan := map[string]interface{}{ "plugins": map[string]interface{}{ results.Category: map[string]interface{}{ results.Name: results.Data, }, }, "scan_date": time.Now().Format(time.RFC3339Nano), } newScan, err := client.Index(). Index(db.Index). Type(db.Type). OpType("index"). // Id("1"). BodyJson(scan). Do(context.Background()) if err != nil { return errors.Wrapf(err, "failed to create new sample plugin doc with id: %s", results.ID) } log.WithFields(log.Fields{ "id": newScan.Id, "index": newScan.Index, "type": newScan.Type, }).Debug("indexed sample") } return nil }
go
{ "resource": "" }
q182348
CamelCase
test
func CamelCase(src string) string { byteSrc := []byte(src) chunks := camelingRegex.FindAll(byteSrc, -1) for idx, val := range chunks { if idx > 0 { chunks[idx] = bytes.Title(val) } } return string(bytes.Join(chunks, nil)) }
go
{ "resource": "" }
q182349
Getopt
test
func Getopt(name, dfault string) string { value := os.Getenv(name) if value == "" { value = dfault } return value }
go
{ "resource": "" }
q182350
Getopts
test
func Getopts(userInput, envVar, dfault string) string { if len(strings.TrimSpace(userInput)) > 0 { return userInput } value := os.Getenv(envVar) if value == "" { value = dfault } return value }
go
{ "resource": "" }
q182351
GetSHA256
test
func GetSHA256(name string) string { dat, err := ioutil.ReadFile(name) Assert(err) h256 := sha256.New() _, err = h256.Write(dat) Assert(err) return fmt.Sprintf("%x", h256.Sum(nil)) }
go
{ "resource": "" }
q182352
RunCommand
test
func RunCommand(ctx context.Context, cmd string, args ...string) (string, error) { var c *exec.Cmd if ctx != nil { c = exec.CommandContext(ctx, cmd, args...) } else { c = exec.Command(cmd, args...) } output, err := c.Output() if err != nil { return string(output), err } // check for exec context timeout if ctx != nil { if ctx.Err() == context.DeadlineExceeded { return "", fmt.Errorf("command %s timed out", cmd) } } return string(output), nil }
go
{ "resource": "" }
q182353
RemoveDuplicates
test
func RemoveDuplicates(elements []string) []string { // Use map to record duplicates as we find them. encountered := map[string]bool{} result := []string{} for v := range elements { if encountered[elements[v]] == true { // Do not add duplicate. } else { // Record this element as an encountered element. encountered[elements[v]] = true // Append to result slice. result = append(result, elements[v]) } } // Return the new slice. return result }
go
{ "resource": "" }
q182354
Unzip
test
func Unzip(archive, target string) error { // fmt.Println("Unzip archive ", target) reader, err := zip.OpenReader(archive) if err != nil { return err } defer reader.Close() for _, file := range reader.File { filePath := filepath.Join(target, file.Name) if file.FileInfo().IsDir() { os.MkdirAll(filePath, file.Mode()) continue } fileReader, err := file.Open() if err != nil { return err } defer fileReader.Close() targetFile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode()) if err != nil { return err } defer targetFile.Close() if _, err := io.Copy(targetFile, fileReader); err != nil { return err } } return nil }
go
{ "resource": "" }
q182355
SliceContainsString
test
func SliceContainsString(a string, list []string) bool { for _, b := range list { if strings.Contains(b, a) { return true } } return false }
go
{ "resource": "" }
q182356
NewSMTP
test
func NewSMTP(filename string, environment string) (s *SMTP, err error) { conf, err := GetSMTP(filename, environment) if err != nil { return } auth := smtp.PlainAuth("", conf.Auth.User, conf.Auth.Password, conf.Host) f := smtp.SendMail if conf.SSL { f = SendMailSSL } s = &SMTP{auth: auth, send: f, addr: fmt.Sprintf("%s:%d", conf.Host, conf.Port)} return }
go
{ "resource": "" }
q182357
SendMail
test
func (s *SMTP) SendMail(from string, to []string, msg []byte) (err error) { err = s.send(s.addr, s.auth, from, to, msg) return }
go
{ "resource": "" }
q182358
GetEnvironment
test
func (se *SMTPEnvironment) GetEnvironment(environment string) interface{} { for env, conf := range se.Env { if strings.Compare(environment, env) == 0 { return conf } } return nil }
go
{ "resource": "" }
q182359
GetSMTP
test
func GetSMTP(source interface{}, environment string) (smtp Config, err error) { var smtpEnvironment SMTPEnvironment i, err := config.Get(source, environment, &smtpEnvironment) smtp = i.(Config) return }
go
{ "resource": "" }
q182360
GetConfig
test
func GetConfig(source interface{}, environment string) (server Config, err error) { var serverEnvironment ServerEnvironment i, err := config.Get(source, environment, &serverEnvironment) server = i.(Config) return }
go
{ "resource": "" }
q182361
GetEnvironment
test
func (m *Environment) GetEnvironment(environment string) interface{} { for env, conf := range m.Env { if strings.Compare(environment, env) == 0 { return conf } } return nil }
go
{ "resource": "" }
q182362
GetMongo
test
func GetMongo(source interface{}, environment string) (mongo Config, err error) { var env Environment i, err := config.Get(source, environment, &env) mongo = i.(Config) return }
go
{ "resource": "" }
q182363
TokenHandler
test
func TokenHandler(next http.Handler, cnf web.Config) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token, err := request.ParseFromRequest(r, request.AuthorizationHeaderExtractor, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { //TODO: On ne passe jamais à l'intérieur return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } return []byte(cnf.Jwt.Key), nil }) if err == nil && token.Valid { next.ServeHTTP(w, r) } else { if r.URL.String() == "/" { next.ServeHTTP(w, r) } else { w.WriteHeader(http.StatusUnauthorized) } } }) }
go
{ "resource": "" }
q182364
Receive
test
func (c *Conn) Receive() (*InMsg, error) { stanza, err := c.xmppConn.Recv() if err != nil { return nil, err } if c.debug { log.Printf("Incoming raw CCS stanza: %+v\n", stanza) } chat, ok := stanza.(xmpp.Chat) if !ok { return nil, nil } if chat.Type == "error" { // todo: once go-xmpp can parse XMPP error messages, return error with XMPP error message (issue: https://github.com/soygul/gcm/issues/14) return nil, errors.New("CCS returned an XMPP error (can be a stanza or JSON error or anything else)") } var m InMsg if err = json.Unmarshal([]byte(chat.Other[0]), &m); err != nil { // todo: handle other fields of chat (remote/type/text/other[1,2,..]) return nil, errors.New("unknow message from CCS") } switch m.MessageType { case "ack": return &m, nil // todo: mark message as sent case "nack": return &m, nil // todo: try and resend the message (after reconnect if problem is about connection draining) case "receipt": return &m, nil // todo: mark message as delivered and remove from the queue case "control": return &m, nil // todo: handle connection draining (and any other control message type?) case "": // acknowledge the incoming ordinary messages as per spec ack := &OutMsg{MessageType: "ack", To: m.From, ID: m.ID} if _, err = c.Send(ack); err != nil { return nil, fmt.Errorf("failed to send ack message to CCS with error: %v", err) } return &m, nil default: // unknown message types can be ignored, as per GCM specs } return &m, nil }
go
{ "resource": "" }
q182365
Send
test
func (c *Conn) Send(m *OutMsg) (n int, err error) { if m.ID == "" { if m.ID, err = getMsgID(); err != nil { return 0, err } } mb, err := json.Marshal(m) if err != nil { return 0, err } ms := string(mb) res := fmt.Sprintf(gcmMessageStanza, ms) return c.xmppConn.SendOrg(res) }
go
{ "resource": "" }
q182366
allBoshReleaseNames
test
func (d pivnetReleaseDiffer) allBoshReleaseNames() []string { boshReleaseNamesMap := make(map[string]string) var addReleaseNames = func(br map[string]*release.BoshRelease) { for brname := range br { boshReleaseNamesMap[brname] = brname } } addReleaseNames(d.release1.BoshRelease) addReleaseNames(d.release2.BoshRelease) var releaseNames []string for brname := range boshReleaseNamesMap { releaseNames = append(releaseNames, brname) } return releaseNames }
go
{ "resource": "" }
q182367
AddedProperty
test
func (dj *DeltaJob) AddedProperty(name string, p *enaml.JobManifestProperty) { dj.AddedProperties[name] = *p }
go
{ "resource": "" }
q182368
RemovedProperty
test
func (dj *DeltaJob) RemovedProperty(name string, p *enaml.JobManifestProperty) { dj.RemovedProperties[name] = *p }
go
{ "resource": "" }
q182369
AddDeltaJob
test
func (r *Result) AddDeltaJob(dj *DeltaJob) { r.DeltaJob = append(r.DeltaJob, *dj) }
go
{ "resource": "" }
q182370
Concat
test
func (r *Result) Concat(other *Result) { for _, dj := range other.DeltaJob { r.DeltaJob = append(r.DeltaJob, dj) } }
go
{ "resource": "" }
q182371
Read
test
func (r *Release) Read(releaseLocation string) (io.ReadCloser, error) { local, err := r.Pull(releaseLocation) if err != nil { return nil, err } rr, err := os.Open(local) if err != nil { return nil, err } return rr, nil }
go
{ "resource": "" }
q182372
Pull
test
func (r *Release) Pull(releaseLocation string) (filename string, err error) { u, uerr := url.Parse(releaseLocation) if uerr != nil || !(u.Scheme == "http" || u.Scheme == "https") { // assume a local file, ensure it exists if _, ferr := os.Stat(releaseLocation); os.IsNotExist(ferr) { err = fmt.Errorf("Could not pull %s. The file doesn't exist or isn't a valid http(s) URL", releaseLocation) return } filename = releaseLocation } else { // remote file, ensure its in the local cache filename = r.CacheDir + "/" + path.Base(releaseLocation) if _, err = os.Stat(filename); os.IsNotExist(err) { fmt.Println("Could not find release in local cache. Downloading now.") err = r.download(releaseLocation, filename) } } return }
go
{ "resource": "" }
q182373
BuildJob
test
func BuildJob(jobMeta BoshJobMeta, dest string) error { b, err := json.Marshal(jobMeta) if err != nil { return err } fmt.Println("building job: ", string(b)) monitFile, specFile, err := createJobFiles(dest, jobMeta.Name) if err != nil { return err } defer monitFile.Close() defer specFile.Close() err = writeMonitFile(monitFile, jobMeta.Name, jobMeta.PIDFile) if err != nil { return err } err = writeSpecFile(specFile, jobMeta.Name, jobMeta.JobProperties, jobMeta.Packages) return err }
go
{ "resource": "" }
q182374
LoadBoshRelease
test
func LoadBoshRelease(releaseRepo pull.Release, path string) (release *BoshRelease, err error) { var rr io.ReadCloser rr, err = releaseRepo.Read(path) if err != nil { return } defer func() { if cerr := rr.Close(); cerr != nil { err = cerr } }() release, err = readBoshRelease(rr) return }
go
{ "resource": "" }
q182375
readBoshRelease
test
func readBoshRelease(rr io.Reader) (*BoshRelease, error) { release := &BoshRelease{ JobManifests: make(map[string]enaml.JobManifest), } err := release.readBoshRelease(rr) return release, err }
go
{ "resource": "" }
q182376
readBoshRelease
test
func (r *BoshRelease) readBoshRelease(rr io.Reader) error { w := pkg.NewTgzWalker(rr) w.OnMatch("release.MF", func(file pkg.FileEntry) error { return decodeYaml(file.Reader, &r.ReleaseManifest) }) w.OnMatch("/jobs/", func(file pkg.FileEntry) error { job, jerr := r.readBoshJob(file.Reader) if jerr == nil { r.JobManifests[job.Name] = job } return jerr }) err := w.Walk() return err }
go
{ "resource": "" }
q182377
readBoshJob
test
func (r *BoshRelease) readBoshJob(jr io.Reader) (enaml.JobManifest, error) { var job enaml.JobManifest jw := pkg.NewTgzWalker(jr) jw.OnMatch("job.MF", func(file pkg.FileEntry) error { return decodeYaml(file.Reader, &job) }) err := jw.Walk() return job, err }
go
{ "resource": "" }
q182378
NewRequest
test
func (s *Client) NewRequest(method, url string, body io.Reader) (*http.Request, error) { req, err := http.NewRequest(method, url, body) if err != nil { return nil, err } setAuth(s, req) return req, nil }
go
{ "resource": "" }
q182379
PushCloudConfig
test
func (s *Client) PushCloudConfig(manifest []byte) error { ccm := enaml.NewCloudConfigManifest(manifest) req, err := s.newCloudConfigRequest(*ccm) if err != nil { return err } res, err := s.http.Do(req) if err != nil { return err } defer res.Body.Close() if res.StatusCode >= 400 { body, err := ioutil.ReadAll(res.Body) if err != nil { return err } return fmt.Errorf("%s error pushing cloud config to BOSH: %s", res.Status, string(body)) } return nil }
go
{ "resource": "" }
q182380
Generate
test
func Generate(packagename string, fileBytes []byte, outputDir string) { b := preprocessJobManifest(fileBytes) objects := make(map[string]map[string]ObjectField) var properties []string for _, v := range b.recs { properties = append(properties, v.Orig) } for i := 0; i < b.max; i++ { for _, v := range b.recs { if v.Length-1 >= i { var structname = v.StructName(i, packagename, properties) var typeName = v.TypeName(i, properties) elementName := v.Slice[i] attributeName := FormatName(elementName) if _, ok := objects[structname]; !ok { objects[structname] = make(map[string]ObjectField) } if previousElement, ok := objects[structname][attributeName]; !ok { lo.G.Debug("Adding", attributeName, "to", structname, "with type", typeName) objects[structname][attributeName] = ObjectField{ ElementName: attributeName, ElementType: typeName, ElementAnnotation: createElementAnnotation(elementName), Meta: v.Yaml, } } else { if previousElement.ElementAnnotation != createElementAnnotation(elementName) { lo.G.Warning("******** Recommended creating custom yaml marshaller on", structname, "for", attributeName, " ********") previousElement.ElementAnnotation = "`yaml:\"-\"`" objects[structname][attributeName] = previousElement } } } } } structs := generateStructs(objects, packagename) writeStructsToDisk(structs, outputDir) }
go
{ "resource": "" }
q182381
CreateNewRecord
test
func CreateNewRecord(property string, yaml enaml.JobManifestProperty) (record Record) { elementArray := strings.Split(property, ".") record = Record{ Length: len(elementArray), Orig: property, Slice: elementArray, Yaml: yaml, } return }
go
{ "resource": "" }
q182382
NewShowCmd
test
func NewShowCmd(releaseRepo pull.Release, release string) *ShowCmd { return &ShowCmd{ releaseRepo: releaseRepo, release: release, } }
go
{ "resource": "" }
q182383
All
test
func (s *ShowCmd) All(w io.Writer) error { if filepath.Ext(s.release) == ".pivotal" { pivnetRelease, err := release.LoadPivnetRelease(s.releaseRepo, s.release) if err != nil { return err } for _, br := range pivnetRelease.BoshRelease { s.printBoshRelease(w, br) } return nil } boshRelease, err := release.LoadBoshRelease(s.releaseRepo, s.release) if err != nil { return err } s.printBoshRelease(w, boshRelease) return nil }
go
{ "resource": "" }
q182384
GetDefaultTaskImageResource
test
func (s *ConcoursePipeline) GetDefaultTaskImageResource() atc.ImageResource { return atc.ImageResource{ Type: s.defaultImageType, Source: atc.Source{ "repository": s.defaultImageRepository, }, } }
go
{ "resource": "" }
q182385
AddRawJob
test
func (s *ConcoursePipeline) AddRawJob(job atc.JobConfig) { s.Jobs = append(s.Jobs, job) }
go
{ "resource": "" }
q182386
AddGroup
test
func (s *ConcoursePipeline) AddGroup(name string, jobs ...string) { s.Groups = append(s.Groups, atc.GroupConfig{ Name: name, Jobs: jobs, }) }
go
{ "resource": "" }
q182387
GetResourceByName
test
func (s *ConcoursePipeline) GetResourceByName(name string) *atc.ResourceConfig { for i, v := range s.Resources { if v.Name == name { return &s.Resources[i] } } return nil }
go
{ "resource": "" }
q182388
AddRawResource
test
func (s *ConcoursePipeline) AddRawResource(rawResource atc.ResourceConfig) { s.Resources = append(s.Resources, rawResource) }
go
{ "resource": "" }
q182389
AddResource
test
func (s *ConcoursePipeline) AddResource(name string, typename string, source map[string]interface{}) { s.Resources = append(s.Resources, atc.ResourceConfig{ Name: name, Type: typename, Source: source, }) }
go
{ "resource": "" }
q182390
AddGithubResource
test
func (s *ConcoursePipeline) AddGithubResource(name string, source map[string]interface{}) { s.AddResource(name, GithubResourceName, source) }
go
{ "resource": "" }
q182391
AddBoshIOResource
test
func (s *ConcoursePipeline) AddBoshIOResource(name string, source map[string]interface{}) { s.AddResource(name, BoshIOResourceName, source) }
go
{ "resource": "" }
q182392
AddBoshDeploymentResource
test
func (s *ConcoursePipeline) AddBoshDeploymentResource(name string, source map[string]interface{}) { s.AddResource(name, BoshDeploymentResourceName, source) }
go
{ "resource": "" }
q182393
AddGitResource
test
func (s *ConcoursePipeline) AddGitResource(name string, source map[string]interface{}) { s.AddResource(name, GitResourceName, source) }
go
{ "resource": "" }
q182394
allJobNames
test
func (d boshReleaseDiffer) allJobNames() []string { jobNamesMap := make(map[string]string) var addJobNames = func(br *release.BoshRelease) { if br != nil { for jbname := range br.JobManifests { jobNamesMap[jbname] = jbname } } } addJobNames(d.release1) addJobNames(d.release2) var jobNames []string for jname := range jobNamesMap { jobNames = append(jobNames, jname) } return jobNames }
go
{ "resource": "" }
q182395
NewDeploymentManifestFromFile
test
func NewDeploymentManifestFromFile(f *os.File) *DeploymentManifest { var b []byte fi, _ := f.Stat() if fi.Size() > 0 { b, _ = ioutil.ReadAll(f) } return NewDeploymentManifest(b) }
go
{ "resource": "" }
q182396
NewDeploymentManifest
test
func NewDeploymentManifest(b []byte) *DeploymentManifest { dm := new(DeploymentManifest) yaml.Unmarshal(b, dm) return dm }
go
{ "resource": "" }
q182397
AddRemoteRelease
test
func (s *DeploymentManifest) AddRemoteRelease(releaseName, ver, url, sha1 string) (err error) { s.Releases = append(s.Releases, Release{ Name: releaseName, URL: url, SHA1: sha1, Version: ver, }) return }
go
{ "resource": "" }
q182398
AddRemoteStemcell
test
func (s *DeploymentManifest) AddRemoteStemcell(os, alias, ver, url, sha1 string) { s.Stemcells = append(s.Stemcells, Stemcell{ OS: os, Alias: alias, Version: ver, URL: url, SHA1: sha1, }) }
go
{ "resource": "" }
q182399
Tag
test
func (s *DeploymentManifest) Tag(key string) string { if s.Tags == nil { return "" } return s.Tags[key] }
go
{ "resource": "" }