tricrypt/cmd/server/main.go

90 lines
1.8 KiB
Go
Raw Normal View History

2024-02-23 14:28:59 +01:00
package main
import (
2024-02-25 02:36:00 +01:00
"crypto/rand"
2024-02-23 17:48:25 +01:00
"crypto/tls"
2024-02-23 14:28:59 +01:00
"fmt"
2024-02-23 18:23:31 +01:00
"io"
2024-02-23 14:28:59 +01:00
"log"
2024-02-23 17:48:25 +01:00
"net"
2024-05-01 16:20:53 +02:00
"git.qowevisa.me/Qowevisa/gotell/communication"
2024-02-23 17:48:25 +01:00
"git.qowevisa.me/Qowevisa/gotell/env"
2024-02-23 14:28:59 +01:00
)
2024-02-23 17:48:25 +01:00
func main() {
2024-02-23 18:02:43 +01:00
host, err := env.GetHost()
if err != nil {
2024-02-23 18:23:31 +01:00
log.Fatal(err)
2024-02-23 18:02:43 +01:00
}
port, err := env.GetPort()
if err != nil {
2024-02-23 18:23:31 +01:00
log.Fatal(err)
2024-02-23 18:02:43 +01:00
}
2024-02-25 02:36:00 +01:00
cert, err := tls.LoadX509KeyPair(
env.ServerFullchainFileName,
env.ServerPrivKeyFileName,
)
2024-02-23 15:32:08 +01:00
if err != nil {
2024-02-25 02:36:00 +01:00
log.Fatalf("server: loadkeys: %s", err)
2024-02-23 14:28:59 +01:00
}
2024-02-25 02:36:00 +01:00
config := tls.Config{Certificates: []tls.Certificate{cert}, ClientAuth: tls.NoClientCert}
config.Rand = rand.Reader
service := fmt.Sprintf("%s:%d", host, port)
listener, err := tls.Listen("tcp", service, &config)
2024-02-23 18:23:31 +01:00
if err != nil {
2024-02-25 02:36:00 +01:00
log.Fatalf("server: listen: %s", err)
2024-02-23 18:23:31 +01:00
}
2024-02-25 02:36:00 +01:00
log.Printf("server: listening on %s", service)
2024-02-23 17:48:25 +01:00
2024-02-25 02:36:00 +01:00
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("server: accept: %s", err)
break
}
log.Printf("server: accepted from %s", conn.RemoteAddr())
go handleClient(conn)
2024-02-23 18:23:31 +01:00
}
2024-02-25 02:36:00 +01:00
}
2024-02-23 17:48:25 +01:00
2024-02-25 02:36:00 +01:00
func handleClient(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 512)
2024-05-01 16:20:53 +02:00
ask, err := communication.AskClientNickname()
if err != nil {
log.Printf("ERROR: %#v\n", err)
} else {
2024-05-01 16:32:23 +02:00
log.Printf("Trying to send %#v\n", ask)
_, err = conn.Write(ask)
if err != nil {
log.Printf("ERROR: %#v\n", err)
}
2024-05-01 16:20:53 +02:00
}
2024-02-23 18:23:31 +01:00
for {
2024-02-25 02:36:00 +01:00
log.Print("server: conn: waiting")
n, err := conn.Read(buf)
if err != nil {
if err != io.EOF {
log.Printf("server: conn: read: %s", err)
}
break
}
answer := append([]byte("Hello! I see your message:"), buf[:n]...)
2024-05-01 16:32:23 +02:00
msg, err := communication.JustGetMessage(answer)
if err != nil {
log.Printf("ERROR: %#v\n", err)
continue
}
log.Printf("server: conn: sending %#v\n", msg)
_, err = conn.Write(msg)
2024-02-23 17:48:25 +01:00
if err != nil {
2024-02-25 02:36:00 +01:00
log.Printf("server: conn: write: %s", err)
break
2024-02-23 17:48:25 +01:00
}
}
2024-02-25 02:36:00 +01:00
log.Println("server: conn: closed")
2024-02-23 17:48:25 +01:00
}