1
0
mirror of https://github.com/schollz/croc.git synced 2024-11-28 09:35:14 +03:00
croc/connect.go

403 lines
10 KiB
Go
Raw Normal View History

2017-10-18 02:50:20 +03:00
package main
import (
2017-10-18 16:05:48 +03:00
"encoding/hex"
"encoding/json"
2017-10-18 02:50:20 +03:00
"fmt"
"io"
2017-10-18 06:15:48 +03:00
"io/ioutil"
2017-10-18 02:50:20 +03:00
"math"
"net"
"os"
"strconv"
2017-10-18 02:53:43 +03:00
"strings"
2017-10-18 02:50:20 +03:00
"sync"
"time"
2017-10-18 03:39:50 +03:00
"github.com/gosuri/uiprogress"
2017-10-18 02:50:20 +03:00
log "github.com/sirupsen/logrus"
)
2017-10-18 16:05:48 +03:00
type Connection struct {
Server string
File FileMetaData
NumberOfConnections int
Code string
HashedCode string
IsSender bool
Debug bool
DontEncrypt bool
bars []*uiprogress.Bar
}
type FileMetaData struct {
Name string
Size int
Hash string
IV string
Salt string
bytes []byte
}
func NewConnection(flags *Flags) *Connection {
c := new(Connection)
c.Debug = flags.Debug
c.DontEncrypt = flags.DontEncrypt
c.Server = flags.Server
c.Code = flags.Code
c.NumberOfConnections = flags.NumberOfConnections
if len(flags.File) > 0 {
c.File.Name = flags.File
c.IsSender = true
} else {
c.IsSender = false
}
log.SetFormatter(&log.TextFormatter{})
if c.Debug {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.WarnLevel)
}
2017-10-18 16:59:58 +03:00
return c
}
func (c *Connection) Run() {
forceSingleThreaded := false
if c.IsSender {
fdata, err := ioutil.ReadFile(c.File.Name)
if err != nil {
log.Fatal(err)
return
}
if len(fdata) < MAX_NUMBER_THREADS*BUFFERSIZE {
forceSingleThreaded = true
log.Debug("forcing single thread")
}
}
2017-10-18 16:59:58 +03:00
log.Debug("checking code validity")
for {
// check code
goodCode := true
m := strings.Split(c.Code, "-")
numThreads, errParse := strconv.Atoi(m[0])
if len(m) < 2 {
goodCode = false
} else if numThreads > MAX_NUMBER_THREADS || numThreads < 1 || (forceSingleThreaded && numThreads != 1) {
2017-10-18 16:59:58 +03:00
c.NumberOfConnections = MAX_NUMBER_THREADS
goodCode = false
} else if errParse != nil {
goodCode = false
}
log.Debug(m)
if !goodCode {
if c.IsSender {
if forceSingleThreaded {
c.NumberOfConnections = 1
}
2017-10-18 16:59:58 +03:00
c.Code = strconv.Itoa(c.NumberOfConnections) + "-" + GetRandomName()
} else {
if len(c.Code) != 0 {
fmt.Println("Code must begin with number of threads (e.g. 3-some-code)")
}
c.Code = getInput("Enter receive code: ")
}
} else {
break
}
}
// assign number of connections
c.NumberOfConnections, _ = strconv.Atoi(strings.Split(c.Code, "-")[0])
2017-10-18 16:05:48 +03:00
if c.IsSender {
// encrypt the file
log.Debug("encrypting...")
fdata, err := ioutil.ReadFile(c.File.Name)
if err != nil {
log.Fatal(err)
return
}
c.File.bytes, c.File.Salt, c.File.IV = Encrypt(fdata, c.Code, c.DontEncrypt)
log.Debug("...finished encryption")
c.File.Hash = HashBytes(fdata)
c.File.Size = len(c.File.bytes)
if c.Debug {
ioutil.WriteFile(c.File.Name+".encrypted", c.File.bytes, 0644)
}
fmt.Printf("Sending %d byte file named '%s'\n", c.File.Size, c.File.Name)
fmt.Printf("Code is: %s\n", c.Code)
}
c.runClient()
}
2017-10-18 03:39:50 +03:00
2017-10-18 02:50:20 +03:00
// runClient spawns threads for parallel uplink/downlink via TCP
2017-10-18 16:05:48 +03:00
func (c *Connection) runClient() {
2017-10-18 02:50:20 +03:00
logger := log.WithFields(log.Fields{
2017-10-18 16:05:48 +03:00
"code": c.Code,
"sender?": c.IsSender,
2017-10-18 02:50:20 +03:00
})
2017-10-18 16:05:48 +03:00
c.HashedCode = Hash(c.Code)
2017-10-18 02:50:20 +03:00
var wg sync.WaitGroup
2017-10-18 16:05:48 +03:00
wg.Add(c.NumberOfConnections)
2017-10-18 03:39:50 +03:00
uiprogress.Start()
2017-10-18 16:05:48 +03:00
if !c.Debug {
c.bars = make([]*uiprogress.Bar, c.NumberOfConnections)
2017-10-18 06:54:52 +03:00
}
2017-10-18 16:05:48 +03:00
gotOK := false
2017-10-18 16:59:58 +03:00
gotResponse := false
2017-10-18 16:05:48 +03:00
for id := 0; id < c.NumberOfConnections; id++ {
2017-10-18 02:50:20 +03:00
go func(id int) {
defer wg.Done()
port := strconv.Itoa(27001 + id)
2017-10-18 16:05:48 +03:00
connection, err := net.Dial("tcp", c.Server+":"+port)
2017-10-18 02:50:20 +03:00
if err != nil {
panic(err)
}
defer connection.Close()
message := receiveMessage(connection)
2017-10-18 03:39:50 +03:00
logger.Debugf("relay says: %s", message)
2017-10-18 16:05:48 +03:00
if c.IsSender {
logger.Debugf("telling relay: %s", "s."+c.Code)
metaData, err := json.Marshal(c.File)
if err != nil {
log.Error(err)
}
encryptedMetaData, salt, iv := Encrypt(metaData, c.Code)
sendMessage("s."+c.HashedCode+"."+hex.EncodeToString(encryptedMetaData)+"-"+salt+"-"+iv, connection)
} else {
logger.Debugf("telling relay: %s", "r."+c.Code)
sendMessage("r."+c.HashedCode+".0.0.0", connection)
}
if c.IsSender { // this is a sender
2017-10-18 04:06:59 +03:00
if id == 0 {
2017-10-18 16:05:48 +03:00
fmt.Printf("\nSending (<-%s)..\n", connection.RemoteAddr().String())
2017-10-18 04:06:59 +03:00
}
2017-10-18 03:39:50 +03:00
logger.Debug("waiting for ok from relay")
2017-10-18 02:50:20 +03:00
message = receiveMessage(connection)
2017-10-18 03:39:50 +03:00
logger.Debug("got ok from relay")
2017-10-18 02:50:20 +03:00
// wait for pipe to be made
2017-10-18 03:39:50 +03:00
time.Sleep(100 * time.Millisecond)
2017-10-18 02:53:43 +03:00
// Write data from file
2017-10-18 03:39:50 +03:00
logger.Debug("send file")
2017-10-18 16:05:48 +03:00
c.sendFile(id, connection)
2017-10-18 02:53:43 +03:00
} else { // this is a receiver
2017-10-18 16:05:48 +03:00
logger.Debug("waiting for meta data from sender")
message = receiveMessage(connection)
m := strings.Split(message, "-")
encryptedData, salt, iv := m[0], m[1], m[2]
encryptedBytes, err := hex.DecodeString(encryptedData)
if err != nil {
log.Error(err)
return
}
decryptedBytes, _ := Decrypt(encryptedBytes, c.Code, salt, iv, c.DontEncrypt)
err = json.Unmarshal(decryptedBytes, &c.File)
if err != nil {
log.Error(err)
return
}
log.Debugf("meta data received: %v", c.File)
// have the main thread ask for the okay
if id == 0 {
fmt.Printf("Receiving file (%d bytes) into: %s\n", c.File.Size, c.File.Name)
2017-10-18 16:59:58 +03:00
getOK := getInput("ok? (y/n): ")
if getOK == "y" {
2017-10-18 16:05:48 +03:00
gotOK = true
}
2017-10-18 16:59:58 +03:00
gotResponse = true
2017-10-18 16:05:48 +03:00
}
// wait for the main thread to get the okay
for limit := 0; limit < 1000; limit++ {
2017-10-18 16:59:58 +03:00
if gotResponse {
2017-10-18 16:05:48 +03:00
break
}
time.Sleep(10 * time.Millisecond)
}
if !gotOK {
2017-10-18 16:59:58 +03:00
sendMessage("not ok", connection)
} else {
sendMessage("ok", connection)
logger.Debug("receive file")
c.receiveFile(id, connection)
2017-10-18 16:05:48 +03:00
}
2017-10-18 02:50:20 +03:00
}
}(id)
}
wg.Wait()
2017-10-18 03:39:50 +03:00
2017-10-18 16:05:48 +03:00
if !c.IsSender {
2017-10-18 16:59:58 +03:00
if !gotOK {
return
}
2017-10-18 16:05:48 +03:00
c.catFile(c.File.Name)
encrypted, err := ioutil.ReadFile(c.File.Name + ".encrypted")
2017-10-18 06:15:48 +03:00
if err != nil {
log.Error(err)
return
}
fmt.Println("\n\ndecrypting...")
2017-10-18 16:05:48 +03:00
log.Debugf("Code: [%s]", c.Code)
log.Debugf("Salt: [%s]", c.File.Salt)
log.Debugf("IV: [%s]", c.File.IV)
decrypted, err := Decrypt(encrypted, c.Code, c.File.Salt, c.File.IV, c.DontEncrypt)
2017-10-18 06:15:48 +03:00
if err != nil {
log.Error(err)
return
}
2017-10-18 16:05:48 +03:00
log.Debugf("writing %d bytes to %s", len(decrypted), c.File.Name)
err = ioutil.WriteFile(c.File.Name, decrypted, 0644)
2017-10-18 07:08:58 +03:00
if err != nil {
log.Error(err)
}
2017-10-18 16:05:48 +03:00
if !c.Debug {
os.Remove(c.File.Name + ".encrypted")
2017-10-18 07:04:59 +03:00
}
2017-10-18 06:57:42 +03:00
log.Debugf("\n\n\ndownloaded hash: [%s]", HashBytes(decrypted))
2017-10-18 16:05:48 +03:00
log.Debugf("\n\n\nrelayed hash: [%s]", c.File.Hash)
2017-10-18 06:28:32 +03:00
2017-10-18 16:05:48 +03:00
if c.File.Hash != HashBytes(decrypted) {
fmt.Printf("\nUh oh! %s is corrupted! Sorry, try again.\n", c.File.Name)
2017-10-18 06:28:32 +03:00
} else {
2017-10-18 16:09:32 +03:00
fmt.Printf("\nReceived file written to %s", c.File.Name)
2017-10-18 06:28:32 +03:00
}
2017-10-18 16:09:32 +03:00
} else {
fmt.Println("File sent.")
// TODO: Add confirmation
2017-10-18 03:39:50 +03:00
}
}
2017-10-18 16:05:48 +03:00
func (c *Connection) catFile(fname string) {
2017-10-18 03:39:50 +03:00
// cat the file
2017-10-18 16:05:48 +03:00
os.Remove(fname)
finished, err := os.Create(fname + ".encrypted")
2017-10-18 03:39:50 +03:00
defer finished.Close()
if err != nil {
log.Fatal(err)
}
2017-10-18 16:05:48 +03:00
for id := 0; id < c.NumberOfConnections; id++ {
fh, err := os.Open(fname + "." + strconv.Itoa(id))
2017-10-18 03:39:50 +03:00
if err != nil {
log.Fatal(err)
}
_, err = io.Copy(finished, fh)
if err != nil {
log.Fatal(err)
}
fh.Close()
2017-10-18 16:05:48 +03:00
os.Remove(fname + "." + strconv.Itoa(id))
2017-10-18 03:39:50 +03:00
}
2017-10-18 02:50:20 +03:00
}
2017-10-18 16:05:48 +03:00
func (c *Connection) receiveFile(id int, connection net.Conn) error {
2017-10-18 03:39:50 +03:00
logger := log.WithFields(log.Fields{
"function": "receiveFile #" + strconv.Itoa(id),
})
2017-10-18 02:53:43 +03:00
2017-10-18 16:05:48 +03:00
logger.Debug("waiting for chunk size from sender")
fileSizeBuffer := make([]byte, 10)
connection.Read(fileSizeBuffer)
fileDataString := strings.Trim(string(fileSizeBuffer), ":")
fileSizeInt, _ := strconv.Atoi(fileDataString)
chunkSize := int64(fileSizeInt)
logger.Debugf("chunk size: %d", chunkSize)
2017-10-18 06:15:48 +03:00
2017-10-18 16:05:48 +03:00
os.Remove(c.File.Name + "." + strconv.Itoa(id))
newFile, err := os.Create(c.File.Name + "." + strconv.Itoa(id))
2017-10-18 02:53:43 +03:00
if err != nil {
panic(err)
}
defer newFile.Close()
2017-10-18 16:05:48 +03:00
if !c.Debug {
c.bars[id] = uiprogress.AddBar(int(chunkSize)/1024 + 1).AppendCompleted().PrependElapsed()
2017-10-18 06:54:52 +03:00
}
2017-10-18 03:39:50 +03:00
logger.Debug("waiting for file")
2017-10-18 02:53:43 +03:00
var receivedBytes int64
for {
2017-10-18 16:05:48 +03:00
if !c.Debug {
c.bars[id].Incr()
2017-10-18 06:54:52 +03:00
}
2017-10-18 16:05:48 +03:00
if (chunkSize - receivedBytes) < BUFFERSIZE {
2017-10-18 03:39:50 +03:00
logger.Debug("at the end")
2017-10-18 16:05:48 +03:00
io.CopyN(newFile, connection, (chunkSize - receivedBytes))
2017-10-18 02:53:43 +03:00
// Empty the remaining bytes that we don't need from the network buffer
2017-10-18 16:05:48 +03:00
if (receivedBytes+BUFFERSIZE)-chunkSize < BUFFERSIZE {
2017-10-18 03:39:50 +03:00
logger.Debug("empty remaining bytes from network buffer")
2017-10-18 16:05:48 +03:00
connection.Read(make([]byte, (receivedBytes+BUFFERSIZE)-chunkSize))
2017-10-18 03:39:50 +03:00
}
2017-10-18 02:53:43 +03:00
break
}
io.CopyN(newFile, connection, BUFFERSIZE)
receivedBytes += BUFFERSIZE
}
2017-10-18 03:39:50 +03:00
logger.Debug("received file")
2017-10-18 16:05:48 +03:00
return nil
2017-10-18 02:53:43 +03:00
}
2017-10-18 16:05:48 +03:00
func (c *Connection) sendFile(id int, connection net.Conn) {
2017-10-18 02:50:20 +03:00
logger := log.WithFields(log.Fields{
2017-10-18 03:39:50 +03:00
"function": "sendFile #" + strconv.Itoa(id),
2017-10-18 02:50:20 +03:00
})
defer connection.Close()
2017-10-18 05:25:33 +03:00
var err error
2017-10-18 16:05:48 +03:00
numChunks := math.Ceil(float64(c.File.Size) / float64(BUFFERSIZE))
chunksPerWorker := int(math.Ceil(numChunks / float64(c.NumberOfConnections)))
2017-10-18 02:50:20 +03:00
2017-10-18 16:05:48 +03:00
chunkSize := int64(chunksPerWorker * BUFFERSIZE)
if id+1 == c.NumberOfConnections {
chunkSize = int64(c.File.Size) - int64(c.NumberOfConnections-1)*chunkSize
2017-10-18 02:50:20 +03:00
}
2017-10-18 16:05:48 +03:00
if id == 0 || id == c.NumberOfConnections-1 {
2017-10-18 03:39:50 +03:00
logger.Debugf("numChunks: %v", numChunks)
logger.Debugf("chunksPerWorker: %v", chunksPerWorker)
2017-10-18 16:05:48 +03:00
logger.Debugf("bytesPerchunkSizeConnection: %v", chunkSize)
2017-10-18 02:50:20 +03:00
}
2017-10-18 16:05:48 +03:00
logger.Debugf("sending chunk size: %d", chunkSize)
connection.Write([]byte(fillString(strconv.FormatInt(int64(chunkSize), 10), 10)))
2017-10-18 06:15:48 +03:00
2017-10-18 02:50:20 +03:00
sendBuffer := make([]byte, BUFFERSIZE)
2017-10-20 04:08:13 +03:00
// open encrypted file
file, err := os.Open(c.File.Name + ".enc")
if err != nil {
log.Error(err)
return
}
defer file.Close()
2017-10-18 02:50:20 +03:00
chunkI := 0
2017-10-18 16:05:48 +03:00
if !c.Debug {
c.bars[id] = uiprogress.AddBar(chunksPerWorker).AppendCompleted().PrependElapsed()
}
2017-10-18 02:50:20 +03:00
for {
_, err = file.Read(sendBuffer)
if err == io.EOF {
//End of file reached, break out of for loop
2017-10-18 03:39:50 +03:00
logger.Debug("EOF")
2017-10-18 02:50:20 +03:00
break
}
2017-10-18 16:05:48 +03:00
if (chunkI >= chunksPerWorker*id && chunkI < chunksPerWorker*id+chunksPerWorker) || (id == c.NumberOfConnections-1 && chunkI >= chunksPerWorker*id) {
2017-10-18 02:50:20 +03:00
connection.Write(sendBuffer)
2017-10-18 16:05:48 +03:00
if !c.Debug {
c.bars[id].Incr()
}
2017-10-18 02:50:20 +03:00
}
chunkI++
}
2017-10-18 03:39:50 +03:00
logger.Debug("file is sent")
2017-10-18 02:50:20 +03:00
return
}