server.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package main
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "encoding/binary"
  6. "fmt"
  7. "net"
  8. "time"
  9. )
  10. func serveConnection(conn net.Conn) {
  11. defer logPanic()
  12. defer conn.Close()
  13. fmt.Printf("Connection from %s\n", conn.RemoteAddr().String())
  14. buf := make([]byte, 4)
  15. for {
  16. _, err := conn.Read(buf)
  17. errCheckPanic(err, "Connection failed with %s", conn.RemoteAddr().String())
  18. id := binary.LittleEndian.Uint16(buf[:2])
  19. board, ok := config.Boards[id]
  20. if !ok {
  21. fmt.Printf("Connection with ID %d is not registerd", id)
  22. break
  23. }
  24. board.LastSeen = time.Now()
  25. msglen := binary.LittleEndian.Uint16(buf[2:])
  26. fmt.Printf("Connection from ID %d message length %d\n %x\n", id, msglen, buf)
  27. payload := make([]byte, msglen)
  28. _, err = conn.Read(payload)
  29. errCheckPanic(err, "Connection failed %s device #%d", conn.RemoteAddr().String(), id)
  30. fmt.Printf("Payload: %x\n", payload)
  31. message := make([]byte, msglen-16)
  32. block, err := aes.NewCipher(board.KEY)
  33. errCheckPanic(err, "Decryption failed %s device #%d", conn.RemoteAddr().String(), id)
  34. mode := cipher.NewCBCDecrypter(block, payload[:16])
  35. mode.CryptBlocks(message, payload[16:])
  36. fmt.Printf("Message: %s\n", string(message))
  37. }
  38. }
  39. func serve(address string) {
  40. ln, err := net.Listen("tcp", address)
  41. errCheckExit(err,"Failed accept connection")
  42. defer ln.Close()
  43. fmt.Printf("Service socket ready at %s\n", address)
  44. for {
  45. conn, err := ln.Accept()
  46. errCheckExit(err,"Failed accept connection %s", conn.RemoteAddr().String())
  47. go serveConnection(conn)
  48. }
  49. }