1
0
mirror of https://github.com/schollz/croc.git synced 2024-11-24 08:02:33 +03:00

run through gofumpt

This commit is contained in:
Tai Groot 2022-12-05 11:21:04 -08:00
parent 8a4326bc0d
commit fa7ae114f5
No known key found for this signature in database
GPG Key ID: D00C269A87614812
13 changed files with 62 additions and 63 deletions

View File

@ -166,9 +166,9 @@ func determinePass(c *cli.Context) (pass string) {
func send(c *cli.Context) (err error) {
setDebugLevel(c)
comm.Socks5Proxy = c.String("socks5")
portsString:=c.String("ports")
if portsString=="" {
portsString="9009,9010,9011,9012,9013"
portsString := c.String("ports")
if portsString == "" {
portsString = "9009,9010,9011,9012,9013"
}
crocOptions := croc.Options{
SharedSecret: c.String("code"),
@ -340,7 +340,7 @@ func saveConfig(c *cli.Context, crocOptions croc.Options) {
log.Error(err)
return
}
err = os.WriteFile(configFile, bConfig, 0644)
err = os.WriteFile(configFile, bConfig, 0o644)
if err != nil {
log.Error(err)
return
@ -448,7 +448,7 @@ func receive(c *cli.Context) (err error) {
log.Error(err)
return
}
err = os.WriteFile(configFile, bConfig, 0644)
err = os.WriteFile(configFile, bConfig, 0o644)
if err != nil {
log.Error(err)
return

View File

@ -39,7 +39,7 @@ func NewConnection(address string, timelimit ...time.Duration) (c *Comm, err err
}
socks5ProxyURL, urlParseError := url.Parse(Socks5Proxy)
if urlParseError != nil {
err = fmt.Errorf("Unable to parse socks proxy url: %s", urlParseError)
err = fmt.Errorf("unable to parse socks proxy url: %s", urlParseError)
log.Debug(err)
return
}
@ -115,7 +115,7 @@ func (c *Comm) Write(b []byte) (n int, err error) {
func (c *Comm) Read() (buf []byte, numBytes int, bs []byte, err error) {
// long read deadline in case waiting for file
if err := c.connection.SetReadDeadline(time.Now().Add(3 * time.Hour)); err != nil {
if err = c.connection.SetReadDeadline(time.Now().Add(3 * time.Hour)); err != nil {
log.Warnf("error setting read deadline: %v", err)
}
// must clear the timeout setting
@ -152,7 +152,7 @@ func (c *Comm) Read() (buf []byte, numBytes int, bs []byte, err error) {
numBytes = int(numBytesUint32)
// shorten the reading deadline in case getting weird data
if err := c.connection.SetReadDeadline(time.Now().Add(10 * time.Second)); err != nil {
if err = c.connection.SetReadDeadline(time.Now().Add(10 * time.Second)); err != nil {
log.Warnf("error setting read deadline: %v", err)
}
buf = make([]byte, numBytes)

View File

@ -31,7 +31,7 @@ func TestComm(t *testing.T) {
log.Error(err)
}
log.Debugf("client %s connected", connection.RemoteAddr().String())
go func(port string, connection net.Conn) {
go func(_ string, connection net.Conn) {
c := New(connection)
err = c.Send([]byte("hello, world"))
assert.Nil(t, err)
@ -63,5 +63,4 @@ func TestComm(t *testing.T) {
assert.NotNil(t, a.Send(token))
_, err = a.Write(token)
assert.NotNil(t, err)
}

View File

@ -189,7 +189,8 @@ func New(ops Options) (c *Client, err error) {
// initialize throttler
if len(c.Options.ThrottleUpload) > 1 && c.Options.IsSender {
upload := c.Options.ThrottleUpload[:len(c.Options.ThrottleUpload)-1]
uploadLimit, err := strconv.ParseInt(upload, 10, 64)
var uploadLimit int64
uploadLimit, err = strconv.ParseInt(upload, 10, 64)
if err != nil {
panic("Could not parse given Upload Limit")
}
@ -289,7 +290,7 @@ func GetFilesInfo(fnames []string, zipfolder bool) (filesInfo []FileInfo, emptyF
if path[len(path)-1:] != "/" {
path += "/"
}
path := filepath.Dir(path)
path = filepath.Dir(path)
dest := filepath.Base(path) + ".zip"
utils.ZipDirectory(dest, path)
stat, errStat = os.Lstat(dest)
@ -325,7 +326,7 @@ func GetFilesInfo(fnames []string, zipfolder bool) (filesInfo []FileInfo, emptyF
if !info.IsDir() {
filesInfo = append(filesInfo, FileInfo{
Name: info.Name(),
FolderRemote: strings.Replace(remoteFolder, string(os.PathSeparator), "/", -1) + "/",
FolderRemote: strings.ReplaceAll(remoteFolder, string(os.PathSeparator), "/") + "/",
FolderSource: filepath.Dir(pathName),
Size: info.Size(),
ModTime: info.ModTime(),
@ -338,8 +339,8 @@ func GetFilesInfo(fnames []string, zipfolder bool) (filesInfo []FileInfo, emptyF
if isEmptyFolder {
emptyFolders = append(emptyFolders, FileInfo{
// Name: info.Name(),
FolderRemote: strings.Replace(strings.TrimPrefix(pathName,
filepath.Dir(absPath)+string(os.PathSeparator)), string(os.PathSeparator), "/", -1) + "/",
FolderRemote: strings.ReplaceAll(strings.TrimPrefix(pathName,
filepath.Dir(absPath)+string(os.PathSeparator)), string(os.PathSeparator), "/") + "/",
})
}
}
@ -449,7 +450,7 @@ func (c *Client) setupLocalRelay() {
func (c *Client) broadcastOnLocalNetwork(useipv6 bool) {
var timeLimit time.Duration
//if we don't use an external relay, the broadcast messages need to be sent continuously
// if we don't use an external relay, the broadcast messages need to be sent continuously
if c.Options.OnlyLocal {
timeLimit = -1 * time.Second
} else {
@ -605,7 +606,7 @@ func (c *Client) Send(filesInfo []FileInfo, emptyFoldersToTransfer []FileInfo, t
ips = append([]string{c.Options.RelayPorts[0]}, ips...)
}
bips, _ := json.Marshal(ips)
if err := conn.Send(bips); err != nil {
if err = conn.Send(bips); err != nil {
log.Errorf("error sending: %v", err)
}
} else if bytes.Equal(data, handshakeRequest) {
@ -784,7 +785,7 @@ func (c *Client) Receive() (err error) {
// and try to connect to them
log.Debug("sending ips?")
var data []byte
if err := c.conn[0].Send(ipRequest); err != nil {
if err = c.conn[0].Send(ipRequest); err != nil {
log.Errorf("ips send error: %v", err)
}
data, err = c.conn[0].Receive()
@ -793,7 +794,7 @@ func (c *Client) Receive() (err error) {
}
log.Debugf("ips data: %s", data)
var ips []string
if err := json.Unmarshal(data, &ips); err != nil {
if err = json.Unmarshal(data, &ips); err != nil {
log.Debugf("ips unmarshal error: %v", err)
}
if len(ips) > 1 {
@ -837,7 +838,7 @@ func (c *Client) Receive() (err error) {
}
}
if err := c.conn[0].Send(handshakeRequest); err != nil {
if err = c.conn[0].Send(handshakeRequest); err != nil {
log.Errorf("handshake send error: %v", err)
}
c.Options.RelayPorts = strings.Split(banner, ",")
@ -933,7 +934,7 @@ func (c *Client) transfer() (err error) {
c.CurrentFile.Close()
c.CurrentFileIsClosed = true
}
if err := os.Remove(pathToFile); err != nil {
if err = os.Remove(pathToFile); err != nil {
log.Warnf("error removing %s: %v", pathToFile, err)
}
fmt.Print("\n")
@ -1356,7 +1357,7 @@ func (c *Client) recipientInitializeFile() (err error) {
var errOpen error
c.CurrentFile, errOpen = os.OpenFile(
pathToFile,
os.O_WRONLY, 0666)
os.O_WRONLY, 0o666)
var truncate bool // default false
c.CurrentFileChunks = []int64{}
c.CurrentFileChunkRanges = []int64{}
@ -1493,7 +1494,7 @@ func (c *Client) createEmptyFileAndFinish(fileInfo FileInfo, i int) (err error)
}
func (c *Client) updateIfRecipientHasFileInfo() (err error) {
if !(!c.Options.IsSender && c.Step2FileInfoTransferred && !c.Step3RecipientRequestFile) {
if c.Options.IsSender || !c.Step2FileInfoTransferred || c.Step3RecipientRequestFile {
return
}
// find the next file to transfer and send that number
@ -1720,7 +1721,7 @@ func (c *Client) receiveData(i int) {
if !c.CurrentFileIsClosed && (c.TotalChunksTransferred == len(c.CurrentFileChunks) || c.TotalSent == c.FilesToTransfer[c.FilesToTransferCurrentNum].Size) {
c.CurrentFileIsClosed = true
log.Debug("finished receiving!")
if err := c.CurrentFile.Close(); err != nil {
if err = c.CurrentFile.Close(); err != nil {
log.Debugf("error closing %s: %v", c.CurrentFile.Name(), err)
} else {
log.Debugf("Successful closing %s", c.CurrentFile.Name())

View File

@ -92,7 +92,7 @@ func TestCrocEmptyFolder(t *testing.T) {
pathName := "../../testEmpty"
defer os.RemoveAll(pathName)
defer os.RemoveAll("./testEmpty")
os.MkdirAll(pathName, 0755)
os.MkdirAll(pathName, 0o755)
log.Debug("setting up sender")
sender, err := New(Options{
@ -158,7 +158,7 @@ func TestCrocSymlink(t *testing.T) {
pathName := "../link-in-folder"
defer os.RemoveAll(pathName)
defer os.RemoveAll("./link-in-folder")
os.MkdirAll(pathName, 0755)
os.MkdirAll(pathName, 0o755)
os.Symlink("../../README.md", filepath.Join(pathName, "README.link"))
log.Debug("setting up sender")
@ -203,7 +203,7 @@ func TestCrocSymlink(t *testing.T) {
if errGet != nil {
t.Errorf("failed to get minimal info: %v", errGet)
}
err := sender.Send(filesInfo, emptyFolders, totalNumberFolders)
err = sender.Send(filesInfo, emptyFolders, totalNumberFolders)
if err != nil {
t.Errorf("send failed: %v", err)
}
@ -211,7 +211,7 @@ func TestCrocSymlink(t *testing.T) {
}()
time.Sleep(100 * time.Millisecond)
go func() {
err := receiver.Receive()
err = receiver.Receive()
if err != nil {
t.Errorf("receive failed: %v", err)
}
@ -307,10 +307,10 @@ func TestCrocError(t *testing.T) {
defer os.Remove(tmpfile.Name()) // clean up
if _, err := tmpfile.Write(content); err != nil {
if _, err = tmpfile.Write(content); err != nil {
panic(err)
}
if err := tmpfile.Close(); err != nil {
if err = tmpfile.Close(); err != nil {
panic(err)
}

View File

@ -39,7 +39,7 @@ func Encrypt(plaintext []byte, key []byte) (encrypted []byte, err error) {
// http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
// Section 8.2
ivBytes := make([]byte, 12)
if _, err := rand.Read(ivBytes); err != nil {
if _, err = rand.Read(ivBytes); err != nil {
log.Fatalf("can't initialize crypto: %v", err)
}
b, err := aes.NewCipher(key)
@ -85,7 +85,7 @@ func NewArgon2(passphrase []byte, usersalt []byte) (aead cipher.AEAD, salt []byt
salt = make([]byte, 8)
// http://www.ietf.org/rfc/rfc2898.txt
// Salt.
if _, err := rand.Read(salt); err != nil {
if _, err = rand.Read(salt); err != nil {
log.Fatalf("can't get random salt: %v", err)
}
} else {

View File

@ -52,19 +52,19 @@ func TestEncryption(t *testing.T) {
assert.Equal(t, msg, dec)
// check reusing the salt
key2, _, err := New([]byte("password"), salt)
key2, _, _ := New([]byte("password"), salt)
dec, err = Decrypt(enc, key2)
assert.Nil(t, err)
assert.Equal(t, msg, dec)
// check reusing the salt
key2, _, err = New([]byte("wrong password"), salt)
key2, _, _ = New([]byte("wrong password"), salt)
dec, err = Decrypt(enc, key2)
assert.NotNil(t, err)
assert.NotEqual(t, msg, dec)
// error with no password
dec, err = Decrypt([]byte(""), key)
_, err = Decrypt([]byte(""), key)
assert.NotNil(t, err)
// error with small password
@ -84,19 +84,19 @@ func TestEncryptionChaCha(t *testing.T) {
assert.Equal(t, msg, dec)
// check reusing the salt
key2, _, err := NewArgon2([]byte("password"), salt)
key2, _, _ := NewArgon2([]byte("password"), salt)
dec, err = DecryptChaCha(enc, key2)
assert.Nil(t, err)
assert.Equal(t, msg, dec)
// check reusing the salt
key2, _, err = NewArgon2([]byte("wrong password"), salt)
key2, _, _ = NewArgon2([]byte("wrong password"), salt)
dec, err = DecryptChaCha(enc, key2)
assert.NotNil(t, err)
assert.NotEqual(t, msg, dec)
// error with no password
dec, err = DecryptChaCha([]byte(""), key)
_, err = DecryptChaCha([]byte(""), key)
assert.NotNil(t, err)
// error with small password

View File

@ -57,7 +57,7 @@ func replaceInFile(fname, start, end, replacement string) (err error) {
fmt.Sprintf("%s%s%s", start, replacement, end),
1,
)
err = os.WriteFile(fname, []byte(newF), 0644)
err = os.WriteFile(fname, []byte(newF), 0o644)
return
}

View File

@ -20,7 +20,7 @@ func TestMessage(t *testing.T) {
m := Message{Type: TypeMessage, Message: "hello, world"}
e, salt, err := crypt.New([]byte("pass"), nil)
assert.Nil(t, err)
fmt.Println(salt)
fmt.Println(string(salt))
b, err := Encode(e, m)
assert.Nil(t, err)
fmt.Printf("%x\n", b)
@ -67,7 +67,7 @@ func TestSend(t *testing.T) {
log.Error(err)
}
log.Debugf("client %s connected", connection.RemoteAddr().String())
go func(port string, connection net.Conn) {
go func(_ string, connection net.Conn) {
c := comm.New(connection)
err = c.Send([]byte("hello, world"))
assert.Nil(t, err)

View File

@ -22,8 +22,8 @@ var (
INTERNAL_DNS = false
)
// publicDns are servers to be queried if a local lookup fails
var publicDns = []string{
// publicDNS are servers to be queried if a local lookup fails
var publicDNS = []string{
"1.0.0.1", // Cloudflare
"1.1.1.1", // Cloudflare
"[2606:4700:4700::1111]", // Cloudflare
@ -103,15 +103,15 @@ func lookup(address string) (ipaddress string, err error) {
s string
err error
}
result := make(chan Result, len(publicDns))
for _, dns := range publicDns {
result := make(chan Result, len(publicDNS))
for _, dns := range publicDNS {
go func(dns string) {
var r Result
r.s, r.err = remoteLookupIP(address, dns)
result <- r
}(dns)
}
for i := 0; i < len(publicDns); i++ {
for i := 0; i < len(publicDNS); i++ {
ipaddress = (<-result).s
if ipaddress != "" {
return
@ -135,7 +135,7 @@ func localLookupIP(address string) (ipaddress string, err error) {
func remoteLookupIP(address, dns string) (ipaddress string, err error) {
r := &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
Dial: func(ctx context.Context, network, _ string) (net.Conn, error) {
d := new(net.Dialer)
return d.DialContext(ctx, network, dns+":53")
},

View File

@ -93,7 +93,8 @@ func (s *server) run() (err error) {
if s.host != "" {
ip := net.ParseIP(s.host)
if ip == nil {
tcpIP, err := net.ResolveIPAddr("ip", s.host)
var tcpIP *net.IPAddr
tcpIP, err = net.ResolveIPAddr("ip", s.host)
if err != nil {
return err
}
@ -227,7 +228,7 @@ func (s *server) clientCommunication(port string, c *comm.Comm) (room string, er
if strings.TrimSpace(string(passwordBytes)) != s.password {
err = fmt.Errorf("bad password")
enc, _ := crypt.Encrypt([]byte(err.Error()), strongKeyForEncryption)
if err := c.Send(enc); err != nil {
if err = c.Send(enc); err != nil {
return "", fmt.Errorf("send error: %w", err)
}
return
@ -350,11 +351,11 @@ func (s *server) deleteRoom(room string) {
}
s.rooms.rooms[room] = roomInfo{first: nil, second: nil}
delete(s.rooms.rooms, room)
}
// chanFromConn creates a channel from a Conn object, and sends everything it
// Read()s from the socket to the channel.
//
// Read()s from the socket to the channel.
func chanFromConn(conn net.Conn) chan []byte {
c := make(chan []byte, 1)
if err := conn.SetReadDeadline(time.Now().Add(3 * time.Hour)); err != nil {

View File

@ -43,7 +43,7 @@ func GetConfigDir() (homedir string, err error) {
}
if _, err = os.Stat(homedir); os.IsNotExist(err) {
err = os.MkdirAll(homedir, 0700)
err = os.MkdirAll(homedir, 0o700)
}
return
}
@ -268,7 +268,6 @@ func MissingChunks(fname string, fsize int64, chunkSize int) (chunkRanges []int6
}
}
chunkRanges = append(chunkRanges, int64(curCount+1))
chunks = chunkRanges
}
return
}
@ -374,7 +373,7 @@ func IsLocalIP(ipaddress string) bool {
}
func ZipDirectory(destination string, source string) (err error) {
if _, err := os.Stat(destination); err == nil {
if _, err = os.Stat(destination); err == nil {
log.Fatalf("%s file already exists!\n", destination)
}
fmt.Fprintf(os.Stderr, "Zipping %s to %s\n", source, destination)
@ -399,8 +398,8 @@ func ZipDirectory(destination string, source string) (err error) {
log.Fatalln(err)
}
defer f1.Close()
zip_path := strings.ReplaceAll(path, source, strings.TrimSuffix(destination, ".zip"))
w1, err := writer.Create(zip_path)
zipPath := strings.ReplaceAll(path, source, strings.TrimSuffix(destination, ".zip"))
w1, err := writer.Create(zipPath)
if err != nil {
log.Fatalln(err)
}
@ -408,7 +407,7 @@ func ZipDirectory(destination string, source string) (err error) {
log.Fatalln(err)
}
fmt.Fprintf(os.Stderr, "\r\033[2K")
fmt.Fprintf(os.Stderr, "\rAdding %s", zip_path)
fmt.Fprintf(os.Stderr, "\rAdding %s", zipPath)
}
return nil
})
@ -420,7 +419,6 @@ func ZipDirectory(destination string, source string) (err error) {
}
func UnzipDirectory(destination string, source string) error {
archive, err := zip.OpenReader(source)
if err != nil {
log.Fatalln(err)

View File

@ -17,7 +17,7 @@ const TCP_BUFFER_SIZE = 1024 * 64
var bigFileSize = 75000000
func bigFile() {
os.WriteFile("bigfile.test", bytes.Repeat([]byte("z"), bigFileSize), 0666)
os.WriteFile("bigfile.test", bytes.Repeat([]byte("z"), bigFileSize), 0o666)
}
func BenchmarkMD5(b *testing.B) {
@ -119,9 +119,9 @@ func TestMissingChunks(t *testing.T) {
rand.Seed(1)
bigBuff := make([]byte, fileSize)
rand.Read(bigBuff)
os.WriteFile("missing.test", bigBuff, 0644)
os.WriteFile("missing.test", bigBuff, 0o644)
empty := make([]byte, chunkSize)
f, err := os.OpenFile("missing.test", os.O_RDWR, 0644)
f, err := os.OpenFile("missing.test", os.O_RDWR, 0o644)
assert.Nil(t, err)
for block := 0; block < fileSize/chunkSize; block++ {
if block == 0 || block == 4 || block == 5 || block >= 7 {
@ -178,10 +178,10 @@ func TestHashFile(t *testing.T) {
defer os.Remove(tmpfile.Name()) // clean up
if _, err := tmpfile.Write(content); err != nil {
if _, err = tmpfile.Write(content); err != nil {
panic(err)
}
if err := tmpfile.Close(); err != nil {
if err = tmpfile.Close(); err != nil {
panic(err)
}
hashed, err := HashFile(tmpfile.Name(), "xxhash")