Cleanup logging

This commit is contained in:
Justin Hawkins 2022-01-16 20:35:35 +10:30
parent d8672139f5
commit 739aca19e7
5 changed files with 43 additions and 64 deletions

View File

@ -1,5 +1,7 @@
{
"cSpell.words": [
"Debugf",
"Infof",
"isatty",
"netgiv",
"pflag"

View File

@ -32,19 +32,12 @@ func (c *Client) Connect() error {
d := net.Dialer{Timeout: 5 * time.Second}
conn, err := d.Dial("tcp", address)
// serverAddress, err := net.ResolveTCPAddr("tcp", address)
// if err != nil {
// return err
// }
// conn, err := d.Dial("tcp", serverAddress)
if err != nil {
return fmt.Errorf("problem connecting to server, is it running?: %v", err)
}
defer conn.Close()
log.Printf("Connection on %s\n", address)
log.Debugf("established connection on %s", address)
tcpConn, ok := conn.(*net.TCPConn)
if !ok {
@ -58,7 +51,7 @@ func (c *Client) Connect() error {
dec := gob.NewDecoder(&secureConnection)
if c.list {
log.Printf("requesting file list")
log.Debugf("requesting file list")
err := c.connectToServer(secure.OperationTypeList, enc, dec)
if err != nil {
@ -75,13 +68,13 @@ func (c *Client) Connect() error {
if err != nil {
panic(err)
}
log.Printf("%d: %s (%s)", listPacket.Id, listPacket.Kind, humanize.Bytes(uint64(listPacket.FileSize)))
fmt.Printf("%d: %s (%s)\n", listPacket.Id, listPacket.Kind, humanize.Bytes(uint64(listPacket.FileSize)))
}
conn.Close()
log.Printf("done listing")
log.Debugf("done listing")
} else if c.receive {
log.Printf("receiving a file")
log.Debugf("receiving a file")
err := c.connectToServer(secure.OperationTypeReceive, enc, dec)
if err != nil {
@ -114,9 +107,9 @@ func (c *Client) Connect() error {
break
}
}
log.Printf("finished")
log.Debugf("finished")
} else if res.Status == secure.ReceiveDataStartResponseNotFound {
log.Printf("ngf not found")
log.Error("ngf not found")
} else {
panic("unknown status")
}
@ -164,13 +157,13 @@ func (c *Client) Connect() error {
Size: 5000,
Data: buf,
}
enc.Encode(send)
err = enc.Encode(send)
// time.Sleep(time.Second)
if err != nil {
log.Fatal(err)
}
}
log.Println("Bytes:", nBytes, "Chunks:", nChunks)
log.Debugf("Sent %s in %d chunks", humanize.Bytes(uint64(nBytes)), nChunks)
conn.Close()

View File

@ -13,15 +13,13 @@ import (
)
func main() {
// log.SetFlags(log.Lshortfile)
// flag.Int("port", 4912, "Port to run server/client on.")
// addr := flag.String("a", "127.0.0.1", "address to connect to.")
isServer := flag.Bool("s", false, "Run netgiv in server mode")
// client mode flags
isList := flag.Bool("l", false, "Set if requesting a list")
isSend := flag.Bool("c", false, "sending stdin to netgiv server (copy)")
isReceive := flag.Bool("p", false, "receive file from netgiv server to stdout (paste)")
debug := flag.Bool("debug", false, "turn on debug logging")
flag.String("address", "", "IP address/hostname of the netgiv server")
helpConfig := flag.Bool("help-config", false, "Show help on netgiv configuration")
@ -102,6 +100,10 @@ environment variable. This may be preferable in some environments.
}
if *debug {
log.SetLevel(log.DebugLevel)
}
if *isServer {
s := Server{port: port, authToken: authtoken}
s.Run()

View File

@ -6,9 +6,10 @@ import (
"encoding/binary"
"errors"
"io"
"log"
"net"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/nacl/box"
)
@ -62,32 +63,16 @@ func (s *SecureConnection) Read(p []byte) (int, error) {
outputBytes := make([]byte, 0)
// log.Printf("READ: start, p %d/%d, buffer contains currently contains %d bytes", len(p), cap(p), s.Buffer.Len())
n, err := s.Conn.Read(message)
if err != nil && err != io.EOF {
log.Printf("read: error in connection read %v", err)
log.Errorf("read: error in connection read %v", err)
return 0, err
}
if err == io.EOF {
eof = true
}
// if n == 0 && bytes.Buffer.{
// return 0, io.EOF
// }
// log.Printf("read: got %d bytes on the wire, error is %v", n, err)
// log.Printf("looks like %v", message[:n])
// if eof {
// log.Printf("eof is true - this is our final read!")
// }
// log.Printf("writing n=%d", n)
// log.Printf("writing buffersize=%v", s.Buffer)
// log.Printf("writing n=%d buffersize=%d this: %v", n, s.Buffer.Len(), s.Buffer.Bytes()[:n])
s.Buffer.Write(message[:n])
// log.Printf("read: appended them to the buffer which is now %d bytes", len(s.Buffer.Bytes()))
for {
@ -104,11 +89,11 @@ func (s *SecureConnection) Read(p []byte) (int, error) {
encryptedBytes := make([]byte, actualPacketEnd)
n, err := s.Buffer.Read(encryptedBytes)
if err != nil && err != io.EOF {
log.Printf("failed to get encrypted bytes from buffer?")
log.Errorf("failed to get encrypted bytes from buffer?")
return 0, errors.New("failed to get encrypted bytes from buffer")
}
if n != int(actualPacketEnd) {
log.Printf("failed to get right number of encrypted bytes from buffer")
log.Errorf("failed to get right number of encrypted bytes from buffer")
return 0, errors.New("failed to get right number of encrypted bytes from buffer")
}
@ -123,7 +108,7 @@ func (s *SecureConnection) Read(p []byte) (int, error) {
outputBytes = append(outputBytes, decryptedMessage...)
if eof && s.Buffer.Len() == 0 {
log.Printf("returning the final packet")
log.Debugf("returning the final packet")
break
}
@ -136,25 +121,21 @@ func (s *SecureConnection) Read(p []byte) (int, error) {
copy(p, outputBytes)
// log.Printf("returning %d decrypted bytes with err: %w", len(outputBytes), err)
// log.Printf("READ: end, p %d/%d, buffer contains currently contains %d bytes", len(p), cap(p), s.Buffer.Len())
return len(outputBytes), err
}
func (s *SecureConnection) Write(p []byte) (int, error) {
// func (s *SecureConnection) Write(o encoding.BinaryMarshaler) (int, error) {
var nonce [24]byte
// Create a new nonce for each message sent
rand.Read(nonce[:])
// log.Printf("before encryption it is %d bytes", len(p))
encryptedMessage := box.SealAfterPrecomputation(nil, p, &nonce, s.SharedKey)
sm := SecureMessage{Msg: encryptedMessage, Nonce: nonce}
// Write it to the connection
wireBytes := sm.toByteArray()
// log.Printf("putting %d bytes on the wire\n nonce: %v\n bytes: %v", len(wireBytes), nonce, wireBytes)
return s.Conn.Write(wireBytes)
}

View File

@ -38,6 +38,7 @@ var ngfs []NGF
var globalId uint32
func (s *Server) Run() {
log.Debugf("starting server on :%d", s.port)
address := fmt.Sprintf(":%d", s.port)
networkAddress, _ := net.ResolveTCPAddr("tcp", address)
@ -95,12 +96,12 @@ func (s *Server) handleConnection(conn *net.TCPConn) {
err := dec.Decode(&start)
if err == io.EOF {
log.Printf("connection has been closed prematurely")
log.Errorf("connection has been closed prematurely")
return
}
if err != nil {
log.Printf("error while expecting PacketStart: %v", err)
log.Errorf("error while expecting PacketStart: %v", err)
return
}
@ -108,14 +109,14 @@ func (s *Server) handleConnection(conn *net.TCPConn) {
startResponse := secure.PacketStartResponse{}
if start.ProtocolVersion != "1.0" {
log.Printf("bad protocol version")
log.Errorf("bad protocol version")
startResponse.Response = secure.PacketStartResponseEnumWrongProtocol
enc.Encode(startResponse)
return
}
if start.AuthToken != s.authToken {
log.Print("bad authtoken")
log.Errorf("bad authtoken")
startResponse.Response = secure.PacketStartResponseEnumBadAuthToken
enc.Encode(startResponse)
return
@ -128,13 +129,13 @@ func (s *Server) handleConnection(conn *net.TCPConn) {
conn.SetDeadline(time.Now().Add(time.Second * 5))
if start.OperationType == secure.OperationTypeSend {
log.Printf("file incoming")
log.Debugf("file incoming")
sendStart := secure.PacketSendDataStart{}
err = dec.Decode(&sendStart)
if err != nil {
log.Printf("error - expecting PacketSendDataStart: %v", err)
log.Errorf("error - expecting PacketSendDataStart: %v", err)
return
}
file, err := os.CreateTemp("", "netgiv_")
@ -153,7 +154,7 @@ func (s *Server) handleConnection(conn *net.TCPConn) {
}
if err != nil {
log.Printf("got error with temp file: %v", err)
log.Errorf("got error with temp file: %v", err)
return
}
sendData := secure.PacketSendDataNext{}
@ -165,7 +166,7 @@ func (s *Server) handleConnection(conn *net.TCPConn) {
break
}
if err != nil {
log.Printf("error while expecting PacketSendDataNext: %s", err)
log.Errorf("error while expecting PacketSendDataNext: %s", err)
return
}
@ -193,7 +194,7 @@ func (s *Server) handleConnection(conn *net.TCPConn) {
}
info, err := file.Stat()
if err != nil {
log.Printf("couldn't stat file %s", err)
log.Errorf("couldn't stat file %s", err)
return
}
ngf.Size = uint64(info.Size())
@ -233,7 +234,7 @@ func (s *Server) handleConnection(conn *net.TCPConn) {
if requestedNGF == nil {
// not found
log.Printf("user requested %d, not found", req.Id)
log.Errorf("user requested %d, not found", req.Id)
res := secure.PacketReceiveDataStartResponse{
Status: secure.ReceiveDataStartResponseNotFound,
}
@ -253,16 +254,16 @@ func (s *Server) handleConnection(conn *net.TCPConn) {
}
err = enc.Encode(res)
if err != nil {
log.Printf("error sending PacketReceiveDataStartResponse: %v", err)
log.Errorf("error sending PacketReceiveDataStartResponse: %v", err)
return
}
// now just start sending the file in batches
buf := make([]byte, 2048)
filename := requestedNGF.StorePath
log.Printf("opening %s", filename)
log.Debugf("opening %s", filename)
f, err := os.Open(filename)
if err != nil {
log.Printf("could not find file %s: %v", filename, err)
log.Errorf("could not find file %s: %v", filename, err)
return
}
@ -271,7 +272,7 @@ func (s *Server) handleConnection(conn *net.TCPConn) {
eof := false
if err != nil && err != io.EOF {
log.Printf("error reading data: %v", err)
log.Errorf("error reading data: %v", err)
break
}
if err == io.EOF {
@ -285,7 +286,7 @@ func (s *Server) handleConnection(conn *net.TCPConn) {
}
err = enc.Encode(chunk)
if err != nil {
log.Printf("error sending chunk: %v", err)
log.Errorf("error sending chunk: %v", err)
}
if eof {
@ -296,7 +297,7 @@ func (s *Server) handleConnection(conn *net.TCPConn) {
return
} else if start.OperationType == secure.OperationTypeList {
log.Printf("client requesting file list")
log.Debugf("client requesting file list")
for _, ngf := range ngfs {
p := secure.PacketListData{}
@ -306,12 +307,12 @@ func (s *Server) handleConnection(conn *net.TCPConn) {
p.Filename = ngf.Filename
enc.Encode(p)
}
log.Printf("done sending list, closing connection")
log.Debugf("done sending list, closing connection")
return
} else {
log.Printf("bad operation")
log.Errorf("bad operation")
return
}