-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
80 lines (77 loc) · 1.42 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"errors"
"io"
"log"
"net"
"sync"
)
func listenForClients(listenAddr string) error {
ln, err := getNewListenerWithTls(listenAddr)
if err != nil {
return err
}
log.Println("Server will start listening clients on", listenAddr)
exitChan := getExitChanForServer()
connChan := make(chan net.Conn, 1)
var wg sync.WaitGroup
wg.Add(1)
go func() {
for {
conn, err := ln.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
break
}
log.Println("Error accepting new connection:", err)
}
connChan <- conn
}
wg.Done()
}()
loop:
for {
select {
case <-exitChan:
_ = ln.Close()
break loop
case conn := <-connChan:
wg.Add(1)
go handleConn(&wg, conn)
}
}
wg.Wait()
return nil
}
func handleConn(wg *sync.WaitGroup, conn net.Conn) {
defer wg.Done()
defer conn.Close()
res := readPass(conn, passArg)
if res != nil {
log.Println("Error handling new connection:", res)
return
} else {
log.Println("New stream initialized")
}
var controlByte [1]byte
for {
_, err := io.ReadFull(conn, controlByte[:])
if err != nil {
log.Println("Error reading control byte:", err)
return
}
switch controlByte[0] {
case 'f':
err := readFile(conn)
if err != nil {
log.Println("Error receiving file:", err)
return
}
case 'e':
return
default:
log.Println("Error: unknown control byte received:", controlByte[0])
return
}
}
}