croc/connect.go

252 lines
6.8 KiB
Go
Raw Normal View History

2017-10-18 01:50:20 +02:00
package main
import (
"bytes"
2017-10-18 01:50:20 +02:00
"fmt"
"io"
2017-10-18 05:15:48 +02:00
"io/ioutil"
2017-10-18 01:50:20 +02:00
"math"
"net"
"os"
2017-10-18 04:25:33 +02:00
"path"
2017-10-18 01:50:20 +02:00
"strconv"
2017-10-18 01:53:43 +02:00
"strings"
2017-10-18 01:50:20 +02:00
"sync"
"time"
2017-10-18 02:39:50 +02:00
"github.com/gosuri/uiprogress"
2017-10-18 01:50:20 +02:00
log "github.com/sirupsen/logrus"
)
2017-10-18 02:39:50 +02:00
var bars []*uiprogress.Bar
2017-10-18 01:50:20 +02:00
// runClient spawns threads for parallel uplink/downlink via TCP
func runClient(connectionType string, codePhrase string) {
logger := log.WithFields(log.Fields{
"codePhrase": codePhrase,
"connection": connectionType,
})
var wg sync.WaitGroup
wg.Add(numberConnections)
2017-10-18 02:39:50 +02:00
uiprogress.Start()
2017-10-18 05:54:52 +02:00
if !debugFlag {
bars = make([]*uiprogress.Bar, numberConnections)
}
2017-10-18 01:50:20 +02:00
for id := 0; id < numberConnections; id++ {
go func(id int) {
defer wg.Done()
port := strconv.Itoa(27001 + id)
2017-10-18 02:45:52 +02:00
connection, err := net.Dial("tcp", serverAddress+":"+port)
2017-10-18 01:50:20 +02:00
if err != nil {
panic(err)
}
defer connection.Close()
message := receiveMessage(connection)
2017-10-18 02:39:50 +02:00
logger.Debugf("relay says: %s", message)
logger.Debugf("telling relay: %s", connectionType+"."+codePhrase)
sendMessage(connectionType+"."+Hash(codePhrase), connection)
2017-10-18 01:53:43 +02:00
if connectionType == "s" { // this is a sender
2017-10-18 03:06:59 +02:00
if id == 0 {
fmt.Println("waiting for other to connect")
}
2017-10-18 02:39:50 +02:00
logger.Debug("waiting for ok from relay")
2017-10-18 01:50:20 +02:00
message = receiveMessage(connection)
2017-10-18 02:39:50 +02:00
logger.Debug("got ok from relay")
2017-10-18 01:50:20 +02:00
// wait for pipe to be made
2017-10-18 02:39:50 +02:00
time.Sleep(100 * time.Millisecond)
2017-10-18 01:53:43 +02:00
// Write data from file
2017-10-18 02:39:50 +02:00
logger.Debug("send file")
2017-10-18 04:25:33 +02:00
sendFile(id, connection, codePhrase)
2017-10-18 01:53:43 +02:00
} else { // this is a receiver
// receive file
2017-10-18 02:39:50 +02:00
logger.Debug("receive file")
2017-10-18 05:28:32 +02:00
fileName, fileIV, fileSalt, fileHash = receiveFile(id, connection, codePhrase)
2017-10-18 01:50:20 +02:00
}
}(id)
}
wg.Wait()
2017-10-18 02:39:50 +02:00
if connectionType == "r" {
2017-10-18 05:28:32 +02:00
catFile(fileName)
encrypted, err := ioutil.ReadFile(fileName + ".encrypted")
2017-10-18 05:15:48 +02:00
if err != nil {
log.Error(err)
return
}
fmt.Println("\n\ndecrypting...")
2017-10-18 05:57:42 +02:00
log.Debugf("codePhrase: [%s]", codePhrase)
log.Debugf("fileSalt: [%s]", fileSalt)
log.Debugf("fileIV: [%s]", fileIV)
2017-10-18 05:28:32 +02:00
decrypted, err := Decrypt(encrypted, codePhrase, fileSalt, fileIV)
2017-10-18 05:15:48 +02:00
if err != nil {
log.Error(err)
return
}
2017-10-18 06:12:35 +02:00
log.Debugf("writing %d bytes to %s", len(decrypted), fileName)
2017-10-18 06:08:58 +02:00
err = ioutil.WriteFile(fileName, decrypted, 0644)
if err != nil {
log.Error(err)
}
2017-10-18 06:04:59 +02:00
if !debugFlag {
os.Remove(fileName + ".encrypted")
}
2017-10-18 05:57:42 +02:00
log.Debugf("\n\n\ndownloaded hash: [%s]", HashBytes(decrypted))
log.Debugf("\n\n\nrelayed hash: [%s]", fileHash)
2017-10-18 05:28:32 +02:00
if fileHash != HashBytes(decrypted) {
fmt.Printf("\nUh oh! %s is corrupted! Sorry, try again.\n", fileName)
} else {
fmt.Printf("\nDownloaded %s!", fileName)
}
2017-10-18 02:39:50 +02:00
}
}
func catFile(fileNameToReceive string) {
// cat the file
os.Remove(fileNameToReceive)
2017-10-18 05:15:48 +02:00
finished, err := os.Create(fileNameToReceive + ".encrypted")
2017-10-18 02:39:50 +02:00
defer finished.Close()
if err != nil {
log.Fatal(err)
}
for id := 0; id < numberConnections; id++ {
fh, err := os.Open(fileNameToReceive + "." + strconv.Itoa(id))
if err != nil {
log.Fatal(err)
}
_, err = io.Copy(finished, fh)
if err != nil {
log.Fatal(err)
}
fh.Close()
os.Remove(fileNameToReceive + "." + strconv.Itoa(id))
}
2017-10-18 01:50:20 +02:00
}
2017-10-18 05:28:32 +02:00
func receiveFile(id int, connection net.Conn, codePhrase string) (fileNameToReceive string, iv string, salt string, hashOfFile string) {
2017-10-18 02:39:50 +02:00
logger := log.WithFields(log.Fields{
"function": "receiveFile #" + strconv.Itoa(id),
})
2017-10-18 01:53:43 +02:00
2017-10-18 06:21:10 +02:00
logger.Debug("waiting for file data")
fileDataBuffer := make([]byte, BUFFERSIZE)
connection.Read(fileDataBuffer)
fileDataString := strings.Trim(string(fileDataBuffer), ":")
pieces := strings.Split(fileDataString, "-")
fileSizeInt, _ := strconv.Atoi(pieces[0])
fileSize := int64(fileSizeInt)
2017-10-18 02:39:50 +02:00
logger.Debugf("filesize: %d", fileSize)
2017-10-18 01:53:43 +02:00
2017-10-18 06:21:10 +02:00
fileNameToReceive = pieces[1]
2017-10-18 05:50:31 +02:00
logger.Debugf("fileName: [%s]", fileNameToReceive)
2017-10-18 05:15:48 +02:00
2017-10-18 06:21:10 +02:00
iv = pieces[2]
2017-10-18 05:50:31 +02:00
logger.Debugf("iv: [%s]", iv)
2017-10-18 05:15:48 +02:00
2017-10-18 06:21:10 +02:00
salt = pieces[3]
2017-10-18 05:50:31 +02:00
logger.Debugf("salt: [%s]", salt)
2017-10-18 05:28:32 +02:00
2017-10-18 06:21:10 +02:00
hashOfFile = pieces[4]
2017-10-18 05:50:31 +02:00
logger.Debugf("hashOfFile: [%s]", hashOfFile)
2017-10-18 05:15:48 +02:00
2017-10-18 02:39:50 +02:00
os.Remove(fileNameToReceive + "." + strconv.Itoa(id))
newFile, err := os.Create(fileNameToReceive + "." + strconv.Itoa(id))
2017-10-18 01:53:43 +02:00
if err != nil {
panic(err)
}
defer newFile.Close()
2017-10-18 05:54:52 +02:00
if !debugFlag {
bars[id] = uiprogress.AddBar(int(fileSize)/1024 + 1).AppendCompleted().PrependElapsed()
}
2017-10-18 02:39:50 +02:00
logger.Debug("waiting for file")
2017-10-18 01:53:43 +02:00
var receivedBytes int64
for {
2017-10-18 05:54:52 +02:00
if !debugFlag {
bars[id].Incr()
}
2017-10-18 01:53:43 +02:00
if (fileSize - receivedBytes) < BUFFERSIZE {
2017-10-18 02:39:50 +02:00
logger.Debug("at the end")
2017-10-18 01:53:43 +02:00
io.CopyN(newFile, connection, (fileSize - receivedBytes))
// Empty the remaining bytes that we don't need from the network buffer
2017-10-18 02:39:50 +02:00
if (receivedBytes+BUFFERSIZE)-fileSize < BUFFERSIZE {
logger.Debug("empty remaining bytes from network buffer")
connection.Read(make([]byte, (receivedBytes+BUFFERSIZE)-fileSize))
}
2017-10-18 01:53:43 +02:00
break
}
io.CopyN(newFile, connection, BUFFERSIZE)
//Increment the counter
receivedBytes += BUFFERSIZE
}
2017-10-18 02:39:50 +02:00
logger.Debug("received file")
2017-10-18 05:15:48 +02:00
return
2017-10-18 01:53:43 +02:00
}
2017-10-18 04:25:33 +02:00
func sendFile(id int, connection net.Conn, codePhrase string) {
2017-10-18 01:50:20 +02:00
logger := log.WithFields(log.Fields{
2017-10-18 02:39:50 +02:00
"function": "sendFile #" + strconv.Itoa(id),
2017-10-18 01:50:20 +02:00
})
defer connection.Close()
2017-10-18 04:25:33 +02:00
var err error
numChunks := math.Ceil(float64(len(fileBytes)) / float64(BUFFERSIZE))
2017-10-18 01:50:20 +02:00
chunksPerWorker := int(math.Ceil(numChunks / float64(numberConnections)))
bytesPerConnection := int64(chunksPerWorker * BUFFERSIZE)
if id+1 == numberConnections {
bytesPerConnection = int64(len(fileBytes)) - (numberConnections-1)*bytesPerConnection
2017-10-18 01:50:20 +02:00
}
if id == 0 || id == numberConnections-1 {
2017-10-18 02:39:50 +02:00
logger.Debugf("numChunks: %v", numChunks)
logger.Debugf("chunksPerWorker: %v", chunksPerWorker)
logger.Debugf("bytesPerConnection: %v", bytesPerConnection)
2017-10-18 04:25:33 +02:00
logger.Debugf("fileNameToSend: %v", path.Base(fileName))
2017-10-18 01:50:20 +02:00
}
2017-10-18 06:21:10 +02:00
payload := strings.Join([]string{
strconv.FormatInt(int64(bytesPerConnection), 10), // filesize
path.Base(fileName),
fileIV,
fileSalt,
fileHash,
}, "-")
2017-10-18 05:28:32 +02:00
2017-10-18 06:21:10 +02:00
logger.Debugf("sending fileSize: %d", bytesPerConnection)
2017-10-18 06:03:48 +02:00
logger.Debugf("sending fileName: %s", path.Base(fileName))
2017-10-18 05:28:32 +02:00
logger.Debugf("sending iv: %s", fileIV)
logger.Debugf("sending salt: %s", fileSalt)
logger.Debugf("sending sha256sum: %s", fileHash)
2017-10-18 06:21:10 +02:00
logger.Debugf("payload is %d bytes", len(payload))
connection.Write([]byte(fillString(payload, BUFFERSIZE)))
2017-10-18 05:15:48 +02:00
2017-10-18 01:50:20 +02:00
sendBuffer := make([]byte, BUFFERSIZE)
file := bytes.NewBuffer(fileBytes)
2017-10-18 01:50:20 +02:00
chunkI := 0
for {
_, err = file.Read(sendBuffer)
if err == io.EOF {
//End of file reached, break out of for loop
2017-10-18 02:39:50 +02:00
logger.Debug("EOF")
2017-10-18 01:50:20 +02:00
break
}
if (chunkI >= chunksPerWorker*id && chunkI < chunksPerWorker*id+chunksPerWorker) || (id == numberConnections-1 && chunkI >= chunksPerWorker*id) {
connection.Write(sendBuffer)
}
chunkI++
}
2017-10-18 02:39:50 +02:00
logger.Debug("file is sent")
2017-10-18 01:50:20 +02:00
return
}