Best Selenoid code snippet using main.fileUpload
userinput.go
Source:userinput.go  
1// Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC (NTESS).2// Under the terms of Contract DE-NA0003525 with NTESS,3// the U.S. Government retains certain rights in this software.4package userinput5import (6	"context"7	"io"8	"os"9	"os/exec"10	"path"11	"path/filepath"12	"strings"13	"text/template"14	"time"15	"github.com/master-of-servers/mose/pkg/moseutils"16	"github.com/master-of-servers/mose/pkg/netutils"17	"github.com/master-of-servers/mose/pkg/system"18	"github.com/rs/zerolog/log"19	"github.com/markbates/pkger"20)21// UserInput holds all values from command line arguments and the settings.json22// This is a necessity resulting from templates needing to take values23// from a single struct, and MOSE taking user input from multiple sources24type UserInput struct {25	// CLI26	OSArch               string `mapstructure:"osarch,omitempty"`27	Cmd                  string `mapstructure:"cmd,omitempty"`28	Debug                bool   `mapstructure:"debug,omitempty"`29	ExfilPort            int    `mapstructure:"exfilport,omitempty"`30	FilePath             string `mapstructure:"filepath,omitempty"`31	FileUpload           string `mapstructure:"fileupload,omitempty"`32	LocalIP              string `mapstructure:"localip,omitempty"`33	PayloadName          string `mapstructure:"payloadname,omitempty"`34	NoServe              bool   `mapstructure:"noserve,omitempty"`35	OSTarget             string `mapstructure:"ostarget,omitempty"`36	WebSrvPort           int    `mapstructure:"websrvport,omitempty"`37	RemoteUploadFilePath string `mapstructure:"remoteuploadpath,omitempty"`38	Rhost                string `mapstructure:"rhost,omitempty"`39	ServeSSL             bool   `mapstructure:"ssl,omitempty"`40	TimeToServe          int    `mapstructure:"tts,omitempty"`41	// Settings42	AnsibleBackupLoc    string `mapstructure:"AnsibleBackupLoc,omitempty"`43	ChefClientKey       string `mapstructure:"ChefClientKey,omitempty"`44	ChefNodeName        string `mapstructure:"ChefNodeName,omitempty"`45	ChefValidationKey   string `mapstructure:"ChefValidationKey,omitempty"`46	CleanupFile         string `mapstructure:"CleanupFile,omitempty"`47	ContainerName       string `mapstructure:"ContainerName,omitempty"`48	ImageName           string `mapstructure:"ImageName,omitempty"`49	PuppetBackupLoc     string `mapstructure:"PuppetBackupLoc,omitempty"`50	RemoteHost          string `mapstructure:"RemoteHost,omitempty"`51	SaltBackupLoc       string `mapstructure:"SaltBackupLoc,omitempty"`52	SSLCertPath         string `mapstructure:"SSLCertPath,omitempty"`53	SSLKeyPath          string `mapstructure:"SSLKeyPath,omitempty"`54	TargetChefServer    string `mapstructure:"TargetChefServer,omitempty"`55	TargetOrgName       string `mapstructure:"TargetOrgName,omitempty"`56	TargetValidatorName string `mapstructure:"TargetValidatorName,omitempty"`57	UploadFilePath      string `mapstructure:"UploadFilePath,omitempty"`58	PayloadDirectory    string `mapstructure:"payloads,omitempty"`59	CMTarget string `mapstructure:"cmtarget,omitempty"`60	BaseDir  string `mapstructure:"basedir,omitempty"`61	NoColor  bool   `mapstructure:"nocolor,omitempty"`62}63// StartTakeover kicks everything off for payload generation64func (i *UserInput) StartTakeover() {65	// Output to the payloads directory if -f is specified66	if i.FileUpload != "" {67		targetBin := filepath.Join(i.PayloadDirectory, i.CMTarget+"-"+strings.ToLower(i.OSTarget))68		files := []string{filepath.Join(i.PayloadDirectory, filepath.Base(i.FileUpload)), targetBin}69		archiveLoc := filepath.Join(i.PayloadDirectory, "/files.tar")70		if i.FilePath != "" {71			archiveLoc = i.FilePath72		}73		// Specify tar for the archive type if no extension is defined74		if filepath.Ext(archiveLoc) == "" {75			archiveLoc = archiveLoc + ".tar"76		}77		log.Info().Msgf("Compressing files %v into %s", files, archiveLoc)78		loc, err := system.ArchiveFiles(files, archiveLoc)79		if err != nil {80			log.Error().Err(err).Msg("Error generating archive file")81		}82		log.Debug().Msgf("Archive file created at %s", loc)83	}84	// If the user hasn't specified to output the payload to a file, then serve it85	if i.FilePath == "" {86		i.ServePayload()87	}88}89// GenerateParams adds the specified input parameters into the payload90func (i *UserInput) GenerateParams() {91	var origFileUpload string92	paramLoc := filepath.Join(i.BaseDir, "cmd/", i.CMTarget, "main/tmpl")93	// Generate the params for a given target94	s, err := pkger.Open(filepath.Join("/", paramLoc, "params.tmpl"))95	if err != nil {96		log.Fatal().Err(err).Msg("")97	}98	defer s.Close()99	dat := new(strings.Builder)100	_, err = io.Copy(dat, s)101	if err != nil {102		log.Fatal().Err(err).Msg("")103	}104	t, err := template.New("params").Parse(dat.String())105	if err != nil {106		log.Fatal().Err(err).Msg("")107	}108	f, err := os.Create(filepath.Join(i.BaseDir, "/cmd/", i.CMTarget, "main/params.go"))109	if err != nil {110		log.Fatal().Err(err).Msg("")111	}112	// Temporarily set UserInput.FileUpload to the name of the file uploaded to avoid pathing issues in the payload113	if i.FileUpload != "" {114		origFileUpload = i.FileUpload115		i.FileUpload = filepath.Base(i.FileUpload)116	}117	err = t.Execute(f, i)118	f.Close()119	if i.FileUpload != "" {120		i.FileUpload = origFileUpload121	}122	if err != nil {123		log.Fatal().Err(err).Msg("")124	}125	dir, _ := path.Split(i.FilePath)126	// Check if dir exists and filePath isn't empty127	if _, err := os.Stat(dir); os.IsNotExist(err) && dir != "" && i.FilePath != "" {128		log.Fatal().Msgf("Location %s does not exist", i.FilePath)129	}130	if dir == "" && i.FilePath != "" {131		dir, err := os.Getwd()132		if err != nil {133			log.Fatal().Msg("Couldn't get current working directory")134		}135		i.FilePath = filepath.Join(dir, i.FilePath)136	}137	// Set port option138	if !i.ServeSSL && i.WebSrvPort == 443 {139		i.WebSrvPort = 8090140	}141	// Put it back142	if i.FileUpload != "" {143		i.FileUpload = origFileUpload144	}145}146// GeneratePayload creates the payload to run on the target system147func (i *UserInput) GeneratePayload() {148	if i.Cmd != "" {149		log.Info().Msgf("Generating %s payload to run %s on a %s system, please wait...", i.CMTarget, i.Cmd, strings.ToLower(i.OSTarget))150	} else {151		log.Info().Msgf("Generating %s payload to run %s on a %s system, please wait...", i.CMTarget, filepath.Base(i.FileUpload), strings.ToLower(i.OSTarget))152	}153	_ = os.Mkdir(i.PayloadDirectory, 0755)154	payload := filepath.Join(i.PayloadDirectory, i.CMTarget+"-"+strings.ToLower(i.OSTarget))155	log.Debug().Msgf("Payload output name = %s", filepath.Base(payload))156	log.Debug().Msgf("CM Target = %s", i.CMTarget)157	log.Debug().Msgf("OS Target = %s", i.OSTarget)158	if i.FileUpload != "" {159		log.Debug().Msgf("File to upload and run = %s", i.FileUpload)160	}161	// If FileUpload is specified, we need to copy it into place162	if i.FileUpload != "" {163		err := system.CpFile(i.FileUpload, filepath.Join(i.PayloadDirectory, filepath.Base(i.FileUpload)))164		if err != nil {165			log.Fatal().Err(err).Msgf("Failed to copy input file upload (%v) exiting", i.FileUpload)166		}167	}168	// FilePath specified with command to run169	if i.FilePath != "" && i.FileUpload == "" {170		log.Info().Msgf("Creating binary at: " + i.FilePath)171		payload = i.FilePath172		if !filepath.IsAbs(i.FilePath) {173			payload = filepath.Join(i.BaseDir, i.FilePath)174		}175	}176	// FilePath used as tar output location in conjunction with FileUpload177	if i.FilePath != "" && i.FileUpload != "" {178		log.Info().Msgf("FilePath supplied - the tar file will be created in %s.", i.FilePath)179		log.Info().Msg("File Upload specified - copying payload into the payloads directory.")180		system.CpFile(i.FileUpload, filepath.Join(i.PayloadDirectory, filepath.Base(i.FileUpload)))181	}182	cmd := exec.Command("pkger")183	cmd.Dir = filepath.Join(i.BaseDir, "cmd", i.CMTarget, "main")184	err := cmd.Run()185	if err != nil {186		log.Fatal().Err(err).Msg("Error running the command to generate the target payload")187	}188	cmd = exec.Command("env", "GOOS="+strings.ToLower(i.OSTarget), "GOARCH=amd64", "go", "build", "-o", payload)189	log.Debug().Msgf("env GOOS=%s GOARCH=amd64 go build -o %s", strings.ToLower(i.OSTarget), payload)190	cmd.Dir = filepath.Join(i.BaseDir, "cmd", i.CMTarget, "main")191	err = cmd.Run()192	if err != nil {193		log.Fatal().Err(err).Msg("Error running the command to generate the target payload")194	}195}196// SetLocalIP sets the local IP address if specified as an input parameter (-l IPAddress)197func (i *UserInput) SetLocalIP() {198	if i.LocalIP == "" {199		ip, err := netutils.GetLocalIP()200		i.LocalIP = ip201		if err != nil {202			log.Fatal().Err(err).Msg("")203		}204	}205}206// ServePayload will serve the payload with a web server207func (i *UserInput) ServePayload() {208	proto := "http"209	if i.ServeSSL {210		proto = "https"211	}212	if i.FileUpload != "" {213		moseutils.ColorMsgf("File upload command specified, payload being served at %s://%s:%d/files.tar for %d seconds", proto, i.LocalIP, i.WebSrvPort, i.TimeToServe)214	} else {215		moseutils.ColorMsgf("Payload being served at %s://%s:%d/%s-%s for %d seconds", proto, i.LocalIP, i.WebSrvPort, i.CMTarget, strings.ToLower(i.OSTarget), i.TimeToServe)216	}217	srv := netutils.StartServer(i.WebSrvPort, i.PayloadDirectory, i.ServeSSL, i.SSLCertPath, i.SSLKeyPath, time.Duration(i.TimeToServe)*time.Second, true)218	log.Info().Msg("Web server shutting down...")219	if err := srv.Shutdown(context.Background()); err != nil {220		log.Fatal().Err(err).Msg("")221	}222}...test.go
Source:test.go  
...50	db.SetMaxIdleConns(10)51	return db52}53// Save file to db54func insertFile(fileUpload FileUpload) bool {55	db := dbConn()56	insForm, err := db.Prepare("INSERT INTO Uploads(filename, size, mimeType, filePath) VALUES(?,?,?,?)")57	if err != nil {58		panic(err.Error())59	}60	insForm.Exec(fileUpload.Filename, fileUpload.Size, fileUpload.MimeType, fileUpload.FilePath)61	defer db.Close()62	return true63}64func setEnvVariable(envVar EnvVariable) {65	os.Setenv(envVar.Key, envVar.Value)66}67func getEnvVariable(key string) string {68	return os.Getenv(key)69}70func returnStatusCodeErr(writer http.ResponseWriter, errorCode string) {71	writer.WriteHeader(http.StatusForbidden)72	switch errorCode {73	case "500":74		writer.Write([]byte("500 HTTP Internal Server Error!"))75	case "403":76		writer.Write([]byte("403 HTTP Bad Request!"))77	}78}79// Validate if image80func checkIfImage(mimeType string) bool {81	imageMimeTypes := []string{"image/apng", "image/bmp", "image/gif", "image/jpeg", "image/png", "image/svg+xml", "image/tiff", "image/webp"}82	for _, imageMimeType := range imageMimeTypes {83		if imageMimeType == mimeType {84			return true85		}86	}87	return false88}89// Process File Upload90func uploadFile(writer http.ResponseWriter, request *http.Request) {91	fmt.Println("file is uploading...")92	request.Body = http.MaxBytesReader(writer, request.Body, 8<<20)93	file, handler, err := request.FormFile("file")94	if err != nil {95		fmt.Fprintf(writer, "413 HTTP Request Body Too Large! Max file sixe is 8 MB \n")96		log.Println(err)97		return98	}99	fileBytes, err := ioutil.ReadAll(file)100	if err != nil {101		returnStatusCodeErr(writer, "500")102		fmt.Println(err)103	}104	detectFile := mimetype.Detect(fileBytes)105	mime := detectFile.String()106	extension := detectFile.Extension()107	if request.FormValue("auth") != getEnvVariable("auth") || !checkIfImage(strings.ToLower(mime)) {108		returnStatusCodeErr(writer, "403")109		return110	}111	if err != nil {112		returnStatusCodeErr(writer, "500")113		fmt.Println("Error in retrieving the file: ")114		fmt.Println(err)115		return116	}117	defer file.Close()118	tempFile, err := ioutil.TempFile("files", "temp-*"+extension)119	if err != nil {120		returnStatusCodeErr(writer, "500")121		fmt.Println(err)122	}123	defer tempFile.Close()124	filePath := tempFile.Name()125	tempFile.Write(fileBytes)126	fileUpload := FileUpload{Filename: handler.Filename, Size: handler.Size, MimeType: mime, FilePath: filePath}127	result := insertFile(fileUpload)128	if !result {129		returnStatusCodeErr(writer, "500")130		return131	}132	fmt.Fprintf(writer, "File Successfully Uploaded\n")133}134// MAIN FUNCTION135func main() {136	fmt.Printf("Go Exam Starting.....")137	envVar := EnvVariable{Value: "123456778huidhsfksjfbk", Key: "auth"}138	setEnvVariable(envVar)139	setRoutes()140}...file_upload.go
Source:file_upload.go  
1package main2import (3	"github.com/x0xO/hhttp"4)5func main() {6	URL := "http://ptsv2.com/t/ys04l-1590171554/post"7	// with file path8	hhttp.NewClient().FileUpload(URL, "filefield", "/path/to/file.txt").Do()9	// without physical file10	hhttp.NewClient().FileUpload(URL, "filefield", "info.txt", "Hello from hhttp!").Do()11	// with multipart data12	multipartValues := map[string]string{"some": "values"}13	// with file path14	hhttp.NewClient().FileUpload(URL, "filefield", "/path/to/file.txt", multipartValues).Do()15	// without physical file16	hhttp.NewClient().FileUpload(URL, "filefield", "info.txt", "Hello from hhttp!", multipartValues).Do()17}...fileUpload
Using AI Code Generation
1import (2func main() {3    fmt.Println("Hello, playground")4    fileUpload()5}6import (7func fileUpload() {8    fmt.Println("Hello, playground")9}10I have a main.go file and a 2.go file. I want to call the method fileUpload() in the main.go file. I have the following code:But when I run the main.go file, I get the following error:How do I fix this?fileUpload
Using AI Code Generation
1import (2func main() {3	fileUpload()4}5func fileUpload() {6	file, err := os.Open("C:\\Users\\user\\Desktop\\1.txt")7	if err != nil {8		fmt.Println(err)9	}10	defer file.Close()11	if err != nil {12		fmt.Println(err)13	}14	defer response.Body.Close()15	contents, err := io.ReadAll(response.Body)16	if err != nil {17		fmt.Println(err)18	}19	fmt.Println(string(contents))20}fileUpload
Using AI Code Generation
1import (2func main() {3	fmt.Println("File upload")4	fileUpload()5}6import (7func fileUpload() {8	fmt.Println("File upload")9}10import (11func fileUpload() {12	fmt.Println("File upload")13}14import (15func fileUpload() {16	fmt.Println("File upload")17}18import (19func fileUpload() {20	fmt.Println("File upload")21}22import (23func fileUpload() {24	fmt.Println("File upload")25}26import (27func fileUpload() {28	fmt.Println("File upload")29}30import (31func fileUpload() {32	fmt.Println("File upload")33}34import (35func fileUpload() {36	fmt.Println("File upload")37}38import (39func fileUpload() {40	fmt.Println("File upload")41}42import (43func fileUpload() {44	fmt.Println("File upload")45}46import (47func fileUpload() {48	fmt.Println("File upload")49}50import (51func fileUpload() {52	fmt.Println("File upload")53}54import (Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
