archat-server/main.go

382 lines
8.0 KiB
Go
Raw Normal View History

2024-03-21 21:36:25 +00:00
package main
import (
"bufio"
"encoding/json"
"io"
"log"
"net"
"os"
"sync"
"time"
"golang.org/x/crypto/bcrypt"
2024-03-21 21:36:25 +00:00
)
2024-03-22 15:04:42 +00:00
type Account struct {
nickname string
passHash []byte
2024-03-22 15:04:42 +00:00
}
2024-03-21 22:54:13 +00:00
type ServerContext struct {
2024-03-22 15:04:42 +00:00
peersList []*Peer
2024-03-21 22:54:13 +00:00
peersListLock sync.RWMutex
2024-03-22 15:04:42 +00:00
accounts map[string]*Account
accountsLock sync.RWMutex
}
type HandlerContext struct {
peer *Peer
srvCtx *ServerContext
2024-03-21 22:54:13 +00:00
}
2024-03-21 21:36:25 +00:00
type Peer struct {
2024-03-22 15:04:42 +00:00
id int
conn net.Conn
hasAccount bool
account *Account
2024-03-21 21:36:25 +00:00
}
type PeerInfo struct {
2024-03-22 15:04:42 +00:00
ID int `json:"id"`
Addr string `json:"addr"`
HasNickaname bool `json:"hasNickname"`
Nickname string `json:"nickname"`
2024-03-21 21:36:25 +00:00
}
type EchoRequest struct {
EchoByte byte `json:"echoByte"`
}
type EchoResponse struct {
EchoByte byte `json:"echoByte"`
}
type ListPeersRequest struct {
}
type ListPeersResponse struct {
PeersInfo []PeerInfo `json:"peers"`
}
2024-03-22 15:04:42 +00:00
type AuthRequest struct {
Nickname string
Password string
}
type AuthResponse struct {
IsSuccess bool
}
2024-03-21 21:36:25 +00:00
const (
echoRID = 1
listPeersRID = 2
2024-03-22 15:04:42 +00:00
authRID = 3
2024-03-21 21:36:25 +00:00
)
2024-03-22 15:04:42 +00:00
func peerSliceIndexOf(s []*Peer, id int) int {
2024-03-21 21:36:25 +00:00
i := 0
2024-03-22 15:04:42 +00:00
var p *Peer
2024-03-21 21:36:25 +00:00
for i, p = range s {
if p.id == id {
break
}
}
return i
}
2024-03-22 15:04:42 +00:00
func peerSliceRemove(s *[]*Peer, i int) {
2024-03-21 21:36:25 +00:00
(*s)[i] = (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
}
2024-03-22 15:04:42 +00:00
func handleDisconnection(handlerCtx *HandlerContext) {
handlerCtx.srvCtx.peersListLock.Lock()
p := handlerCtx.srvCtx.peersList[peerSliceIndexOf(handlerCtx.srvCtx.peersList, handlerCtx.peer.id)]
2024-03-21 21:36:25 +00:00
log.Printf("[Server] %s disconnected\n", p.conn.RemoteAddr())
2024-03-22 15:04:42 +00:00
peerSliceRemove(&handlerCtx.srvCtx.peersList, peerSliceIndexOf(handlerCtx.srvCtx.peersList, handlerCtx.peer.id))
handlerCtx.srvCtx.peersListLock.Unlock()
2024-03-21 21:36:25 +00:00
}
2024-03-22 15:04:42 +00:00
func handlePeer(handlerCtx *HandlerContext) {
br := bufio.NewReader(handlerCtx.peer.conn)
bw := bufio.NewWriter(handlerCtx.peer.conn)
2024-03-21 21:36:25 +00:00
for {
reqBytes, err := br.ReadBytes('\n')
if err == io.EOF {
2024-03-22 15:04:42 +00:00
handleDisconnection(handlerCtx)
2024-03-21 21:36:25 +00:00
break
} else if err != nil {
log.Println(err)
break
}
if len(reqBytes) <= 1 {
log.Println("got request without id")
break
}
reqBytes = reqBytes[:len(reqBytes)-1]
operationCode := reqBytes[0]
reqJsonBytes := reqBytes[1:]
var resBytes []byte
if operationCode == echoRID {
2024-03-22 15:04:42 +00:00
resBytes, err = handleEcho(handlerCtx, reqJsonBytes)
2024-03-21 21:36:25 +00:00
} else if operationCode == listPeersRID {
2024-03-22 15:04:42 +00:00
resBytes, err = handleListPeers(handlerCtx, reqJsonBytes)
} else if operationCode == authRID {
resBytes, err = handleAuth(handlerCtx, reqJsonBytes)
2024-03-21 21:36:25 +00:00
}
if err != nil {
log.Println(err)
continue
}
resBytes = append(resBytes, '\n')
_, err = bw.Write(resBytes)
if err != nil {
log.Println(err)
continue
}
err = bw.Flush()
if err != nil {
log.Println(err)
}
}
}
2024-03-22 15:04:42 +00:00
func handleEcho(_ *HandlerContext, reqBytes []byte) (resBytes []byte, err error) {
2024-03-21 21:36:25 +00:00
var echoReq EchoRequest
err = json.Unmarshal(reqBytes, &echoReq)
if err != nil {
return nil, err
}
echoRes := EchoResponse(echoReq)
resBytes, err = json.Marshal(echoRes)
if err != nil {
return nil, err
}
return resBytes, nil
}
2024-03-22 15:04:42 +00:00
func handleListPeers(handlerCtx *HandlerContext, reqBytes []byte) (resBytes []byte, err error) {
2024-03-21 21:36:25 +00:00
var listPeersReq ListPeersRequest
err = json.Unmarshal(reqBytes, &listPeersReq)
if err != nil {
return nil, err
}
2024-03-22 15:04:42 +00:00
handlerCtx.srvCtx.peersListLock.RLock()
peersFreeze := make([]*Peer, len(handlerCtx.srvCtx.peersList))
copy(peersFreeze, handlerCtx.srvCtx.peersList)
handlerCtx.srvCtx.peersListLock.RUnlock()
2024-03-21 21:36:25 +00:00
listPeersRes := ListPeersResponse{make([]PeerInfo, 0)}
for _, peer := range peersFreeze {
listPeersRes.PeersInfo = append(
listPeersRes.PeersInfo,
2024-03-22 15:04:42 +00:00
PeerInfo{peer.id, peer.conn.RemoteAddr().String(), peer.hasAccount, peer.account.nickname},
2024-03-21 21:36:25 +00:00
)
}
resBytes, err = json.Marshal(listPeersRes)
if err != nil {
return nil, err
}
return resBytes, nil
}
2024-03-22 15:04:42 +00:00
func handleAuth(handlerCtx *HandlerContext, reqBytes []byte) (resBytes []byte, err error) {
var authReq AuthRequest
err = json.Unmarshal(reqBytes, &authReq)
if err != nil {
return nil, err
}
// Check if account already exists
handlerCtx.srvCtx.accountsLock.RLock()
account, ok := handlerCtx.srvCtx.accounts[authReq.Nickname]
handlerCtx.srvCtx.accountsLock.RUnlock()
var authRes AuthResponse
if ok {
// Check if password matches
if bcrypt.CompareHashAndPassword(account.passHash, []byte(authReq.Password)) == nil {
2024-03-22 15:04:42 +00:00
authRes = AuthResponse{true}
handlerCtx.srvCtx.peersListLock.Lock()
handlerCtx.peer.hasAccount = true
handlerCtx.peer.account = account
handlerCtx.srvCtx.peersListLock.Unlock()
} else {
authRes = AuthResponse{false}
}
} else {
authRes = AuthResponse{true}
passHash, err := bcrypt.GenerateFromPassword([]byte(authReq.Password), bcrypt.DefaultCost)
if err != nil {
authRes = AuthResponse{false}
} else {
newAcc := Account{authReq.Nickname, passHash}
handlerCtx.srvCtx.accountsLock.Lock()
handlerCtx.srvCtx.accounts[newAcc.nickname] = &newAcc
handlerCtx.srvCtx.accountsLock.Unlock()
handlerCtx.srvCtx.peersListLock.Lock()
handlerCtx.peer.hasAccount = true
handlerCtx.peer.account = &newAcc
handlerCtx.srvCtx.peersListLock.Unlock()
}
2024-03-22 15:04:42 +00:00
}
resBytes, err = json.Marshal(authRes)
if err != nil {
return nil, err
}
return resBytes, nil
}
2024-03-21 22:54:13 +00:00
func printConnectedPeers(srvCtx *ServerContext) {
srvCtx.peersListLock.RLock()
2024-03-22 15:04:42 +00:00
log.Println("[Server] displaying all connections:")
2024-03-21 21:36:25 +00:00
2024-03-21 22:54:13 +00:00
for _, p := range srvCtx.peersList {
2024-03-22 15:04:42 +00:00
nick := "-"
if p.hasAccount {
nick = p.account.nickname
}
log.Printf("[Server] ID#%d, Addr:%s, Auth:%t, Nick:%s\n", p.id, p.conn.RemoteAddr(), p.hasAccount, nick)
2024-03-21 21:36:25 +00:00
}
2024-03-21 22:54:13 +00:00
srvCtx.peersListLock.RUnlock()
2024-03-21 21:36:25 +00:00
}
func runServer() {
2024-03-21 22:54:13 +00:00
idCounter := 0
2024-03-22 15:04:42 +00:00
srvCtx := &ServerContext{peersList: make([]*Peer, 0), accounts: make(map[string]*Account)}
2024-03-21 21:36:25 +00:00
ln, err := net.Listen("tcp", ":8080")
if err != nil {
log.Println(err)
}
go func() {
for {
2024-03-21 22:54:13 +00:00
printConnectedPeers(srvCtx)
2024-03-21 21:36:25 +00:00
time.Sleep(time.Second * 5)
}
}()
for {
c, err := ln.Accept()
if err != nil {
log.Println(err)
break
}
log.Printf("[Server] client connected %s\n", c.RemoteAddr())
2024-03-21 22:54:13 +00:00
idCounter++
2024-03-22 15:04:42 +00:00
newPeer := Peer{idCounter, c, false, nil}
2024-03-21 22:54:13 +00:00
srvCtx.peersListLock.Lock()
2024-03-22 15:04:42 +00:00
srvCtx.peersList = append(srvCtx.peersList, &newPeer)
2024-03-21 22:54:13 +00:00
srvCtx.peersListLock.Unlock()
2024-03-22 15:04:42 +00:00
go handlePeer(&HandlerContext{&newPeer, srvCtx})
2024-03-21 21:36:25 +00:00
}
}
func runClient() {
conn, err := net.Dial("tcp", ":8080")
if err != nil {
log.Println("[Client] err connecting")
return
}
defer func() {
_ = conn.Close()
}()
br := bufio.NewReader(conn)
bw := bufio.NewWriter(conn)
log.Println("[Client] connected to server")
time.Sleep(time.Second * 1)
echoReq := EchoRequest{5}
reqBytes, _ := json.Marshal(echoReq)
bw.WriteByte(echoRID)
bw.Write(reqBytes)
bw.WriteByte('\n')
bw.Flush()
resBytes, _ := br.ReadBytes('\n')
var echoRes EchoResponse
json.Unmarshal(resBytes, &echoRes)
log.Printf("[Client] echo sent (5), got %d\n", echoRes.EchoByte)
2024-03-22 15:04:42 +00:00
authReq := AuthRequest{"maciek", "9maciek1"}
reqBytes, _ = json.Marshal(authReq)
bw.WriteByte(authRID)
bw.Write(reqBytes)
bw.WriteByte('\n')
bw.Flush()
resBytes, _ = br.ReadBytes('\n')
var authRes AuthResponse
json.Unmarshal(resBytes, &authRes)
log.Printf("[Client] authenticated: %t\n", authRes.IsSuccess)
2024-03-21 21:36:25 +00:00
listReq := ListPeersRequest{}
reqBytes, _ = json.Marshal(listReq)
bw.WriteByte(listPeersRID)
bw.Write(reqBytes)
bw.WriteByte('\n')
bw.Flush()
resBytes, _ = br.ReadBytes('\n')
var listRes ListPeersResponse
json.Unmarshal(resBytes, &listRes)
log.Println("[Client] printing all peers:")
for _, peer := range listRes.PeersInfo {
2024-03-22 15:04:42 +00:00
log.Printf("[Client] Peer#%d from %s, hasNick: %t, nick: %s", peer.ID, peer.Addr, peer.HasNickaname, peer.Nickname)
2024-03-21 21:36:25 +00:00
}
2024-03-22 15:04:42 +00:00
time.Sleep(time.Second * 10)
2024-03-21 21:36:25 +00:00
}
func main() {
args := os.Args[1:]
if len(args) != 1 {
log.Fatalln("You must provide only one argument which is type of " +
"application: 'server' or 'client'")
}
runType := args[0]
if runType == "client" {
runClient()
} else if runType == "server" {
runServer()
} else {
log.Fatalf("Unknown run type %s\n", runType)
}
}