Compare commits
No commits in common. "main" and "v1.0.5" have entirely different histories.
|
@ -0,0 +1,27 @@
|
||||||
|
name: Go audit
|
||||||
|
run-name: ${{ gitea.actor }} pushed to main! 🚀
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
jobs:
|
||||||
|
audit:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: '>=1.22.0'
|
||||||
|
|
||||||
|
- name: Verify dependencies
|
||||||
|
run: go mod verify
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: go build -v ./...
|
||||||
|
|
||||||
|
- name: Run go vet
|
||||||
|
run: go vet ./...
|
|
@ -9,8 +9,6 @@
|
||||||
*.so
|
*.so
|
||||||
*.dylib
|
*.dylib
|
||||||
dist/
|
dist/
|
||||||
server.crt
|
|
||||||
server.key
|
|
||||||
|
|
||||||
# Test binary, built with `go test -c`
|
# Test binary, built with `go test -c`
|
||||||
*.test
|
*.test
|
||||||
|
|
41
README.md
41
README.md
|
@ -1,40 +1,11 @@
|
||||||
# mini-chat
|
# mini-chat
|
||||||
|
|
||||||
Tiny IRC-like chat server written in Go
|
Tiny IRC-like chat server built for compatibility with netcat and written in Go
|
||||||
|
|
||||||
<p align="center">
|
## Usage
|
||||||
<img width="90%" height="90%" src="https://git.bulgariu.xyz/raul/mini-chat/raw/branch/main/demo.gif"/>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
## Commands
|
### Starting the server
|
||||||
### Client
|
./mini-chat server --port 1337
|
||||||
```
|
|
||||||
Example:
|
|
||||||
./mini-chat client --ip 192.168.0.100 --port 1337
|
|
||||||
|
|
||||||
Usage:
|
### Connecting to the server
|
||||||
mini-chat client [flags]
|
./mini-chat client --ip $SERVER_IP --port $SERVER_PORT
|
||||||
|
|
||||||
Flags:
|
|
||||||
-a, --ascii Render UI in pure ASCII, might help with rendering issues
|
|
||||||
-h, --help help for client
|
|
||||||
--insecure [UNSAFE] Do not use TLS encryption
|
|
||||||
-i, --ip string Server IP to connect to
|
|
||||||
-p, --port string Server port to connect to (default "1302")
|
|
||||||
```
|
|
||||||
|
|
||||||
### Server
|
|
||||||
```
|
|
||||||
Example:
|
|
||||||
./mini-chat server --port 1337 --history chat.log --password coolh4x0r1337
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
mini-chat server [flags]
|
|
||||||
|
|
||||||
Flags:
|
|
||||||
-h, --help help for server
|
|
||||||
-r, --history string File to store and recover chat history from
|
|
||||||
--insecure [UNSAFE] Do not use TLS encryption
|
|
||||||
--password string Password for accessing the chat server
|
|
||||||
-p, --port string Port to use for listening (default "1302")
|
|
||||||
```
|
|
||||||
|
|
|
@ -10,6 +10,7 @@ import (
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// clientCmd represents the client command
|
||||||
var clientCmd = &cobra.Command{
|
var clientCmd = &cobra.Command{
|
||||||
Use: "client",
|
Use: "client",
|
||||||
Short: "Client interface for mini-chat",
|
Short: "Client interface for mini-chat",
|
||||||
|
@ -34,10 +35,18 @@ Example:
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
rootCmd.AddCommand(clientCmd)
|
rootCmd.AddCommand(clientCmd)
|
||||||
clientCmd.PersistentFlags().StringP("ip", "i", "", "Server IP to connect to")
|
|
||||||
clientCmd.PersistentFlags().StringP("port", "p", "1302", "Server port to connect to")
|
// Here you will define your flags and configuration settings.
|
||||||
clientCmd.Flags().Bool("insecure", false, "[UNSAFE] Do not use TLS encryption")
|
|
||||||
clientCmd.Flags().BoolP("ascii", "a", false, "Render UI in pure ASCII, might help with rendering issues")
|
// Cobra supports Persistent Flags which will work for this command
|
||||||
|
// and all subcommands, e.g.:
|
||||||
|
// clientCmd.PersistentFlags().String("foo", "", "A help for foo")
|
||||||
|
clientCmd.PersistentFlags().String("ip", "", "Server IP to connect to")
|
||||||
|
clientCmd.PersistentFlags().String("port", "1302", "Server port to connect to")
|
||||||
|
|
||||||
|
// Cobra supports local flags which will only run when this command
|
||||||
|
// is called directly, e.g.:
|
||||||
|
// clientCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
||||||
}
|
}
|
||||||
|
|
||||||
func setClientParameters(cmd *cobra.Command) error {
|
func setClientParameters(cmd *cobra.Command) error {
|
||||||
|
@ -59,17 +68,5 @@ func setClientParameters(cmd *cobra.Command) error {
|
||||||
}
|
}
|
||||||
serverIP = parameterIP
|
serverIP = parameterIP
|
||||||
|
|
||||||
insecure, err := cmd.Flags().GetBool("insecure")
|
|
||||||
if insecure == true {
|
|
||||||
clientInsecure = true
|
|
||||||
}
|
|
||||||
|
|
||||||
ascii, err := cmd.Flags().GetBool("ascii")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if ascii == true {
|
|
||||||
useASCII = true
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,18 +6,14 @@ package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"crypto/tls"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"github.com/jroimartin/gocui"
|
||||||
|
"github.com/nsf/termbox-go"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
"runtime"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/jroimartin/gocui"
|
|
||||||
"github.com/nsf/termbox-go"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Message struct {
|
type Message struct {
|
||||||
|
@ -26,80 +22,30 @@ type Message struct {
|
||||||
Server net.Conn
|
Server net.Conn
|
||||||
}
|
}
|
||||||
|
|
||||||
type ProfileData struct {
|
|
||||||
Username string
|
|
||||||
}
|
|
||||||
|
|
||||||
var Profile ProfileData
|
|
||||||
|
|
||||||
func (m Message) toSend() {
|
func (m Message) toSend() {
|
||||||
m.Server.Write([]byte(m.Contents))
|
m.Server.Write([]byte(m.Contents))
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
serverPort string = "1302"
|
serverPort string = "1302"
|
||||||
serverIP string
|
serverIP string
|
||||||
data Message
|
data Message
|
||||||
clientInsecure bool
|
|
||||||
useASCII bool
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func startSecureConnection() (net.Conn, error) {
|
|
||||||
conf := &tls.Config{
|
|
||||||
InsecureSkipVerify: true,
|
|
||||||
}
|
|
||||||
conn, err := tls.Dial("tcp", serverIP+":"+serverPort, conf)
|
|
||||||
return conn, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func startInsecureConnection() (net.Conn, error) {
|
|
||||||
conn, err := net.Dial("tcp", serverIP+":"+serverPort)
|
|
||||||
return conn, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func Client() {
|
func Client() {
|
||||||
var conn net.Conn
|
conn, err := net.Dial("tcp", serverIP+":"+serverPort)
|
||||||
var err error
|
|
||||||
if clientInsecure == true {
|
|
||||||
fmt.Println("WARNING: Starting unencrypted connection!")
|
|
||||||
conn, err = startInsecureConnection()
|
|
||||||
} else {
|
|
||||||
conn, err = startSecureConnection()
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Error occurred trying to connect to server: %v\n", err)
|
log.Fatalf("Error occurred trying to connect to server: %v\n", err)
|
||||||
}
|
}
|
||||||
defer conn.Close()
|
defer conn.Close()
|
||||||
data.Server = conn
|
data.Server = conn
|
||||||
|
|
||||||
nameRequest, b, err := receiveMessage(conn)
|
nameRequest, err := receiveMessage(conn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Error occurred reading from server while requesting name: %v\n", err)
|
log.Fatalf("Error occurred reading from server while requesting name: %v\n", err)
|
||||||
}
|
}
|
||||||
fmt.Print(nameRequest)
|
fmt.Print(nameRequest)
|
||||||
test := make([]byte, b)
|
sendName(conn)
|
||||||
copy(test, "Password: ")
|
|
||||||
|
|
||||||
if nameRequest == string(test) {
|
|
||||||
pass, err := scanLine()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
conn.Write([]byte(pass))
|
|
||||||
|
|
||||||
nameRequest, _, err := receiveMessage(conn)
|
|
||||||
if err != nil {
|
|
||||||
if err != io.EOF {
|
|
||||||
log.Fatalf("Error occurred reading from server while requesting name: %v\n", err)
|
|
||||||
}
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
fmt.Print(nameRequest)
|
|
||||||
sendName(conn)
|
|
||||||
} else {
|
|
||||||
sendName(conn)
|
|
||||||
}
|
|
||||||
GUI()
|
GUI()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -108,16 +54,21 @@ func Client() {
|
||||||
////////////////////////////////////////////////////
|
////////////////////////////////////////////////////
|
||||||
|
|
||||||
func listenMessages(g *gocui.Gui) {
|
func listenMessages(g *gocui.Gui) {
|
||||||
time.Sleep(time.Millisecond * 50)
|
time.Sleep(time.Millisecond * 250)
|
||||||
chatbox, err := g.View("chatbox")
|
chatbox, err := g.View("chatbox")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Panicln(err)
|
log.Panicln(err)
|
||||||
}
|
}
|
||||||
for {
|
for {
|
||||||
messageFromServer, _, err := receiveMessage(data.Server)
|
messageFromServer, err := receiveMessage(data.Server)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
g.Close()
|
// Avoid triggering an error if client quits the client
|
||||||
os.Exit(0)
|
if err == gocui.ErrQuit {
|
||||||
|
g.Close()
|
||||||
|
} else {
|
||||||
|
g.Close()
|
||||||
|
log.Fatalf("Error occurred reading from server: %v\n", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
formattedMessage := strings.TrimRight(messageFromServer, "\n")
|
formattedMessage := strings.TrimRight(messageFromServer, "\n")
|
||||||
|
@ -126,48 +77,23 @@ func listenMessages(g *gocui.Gui) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func receiveMessage(conn net.Conn) (s string, b int, err error) {
|
func receiveMessage(conn net.Conn) (s string, err error) {
|
||||||
serverMessage := make([]byte, 1536)
|
serverMessage := make([]byte, 2048)
|
||||||
n, err := conn.Read(serverMessage)
|
if _, err := conn.Read(serverMessage); err != nil {
|
||||||
if err != nil {
|
return "", err
|
||||||
return "", 0, err
|
|
||||||
}
|
}
|
||||||
|
finalMessage := string(serverMessage)
|
||||||
serverMessageReduced := make([]byte, n)
|
return finalMessage, nil
|
||||||
copy(serverMessageReduced, serverMessage)
|
|
||||||
|
|
||||||
finalMessage := string(serverMessageReduced)
|
|
||||||
serverMessage = nil
|
|
||||||
|
|
||||||
return finalMessage, n, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func scanLine() (line string, err error) {
|
|
||||||
switch runtime.GOOS {
|
|
||||||
case "linux":
|
|
||||||
message, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
line = message
|
|
||||||
case "windows":
|
|
||||||
message, err := bufio.NewReader(os.Stdin).ReadString('\r')
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
line = message
|
|
||||||
}
|
|
||||||
return line, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func sendName(conn net.Conn) {
|
func sendName(conn net.Conn) {
|
||||||
message, err := scanLine()
|
message, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Error occurred sending message to server: %v\n", err)
|
log.Fatalf("Error occurred sending message to server: %v\n", err)
|
||||||
}
|
}
|
||||||
Profile.Username = strings.TrimRight(message, "\n\r")
|
|
||||||
|
|
||||||
if _, err := conn.Write([]byte(Profile.Username + "\n")); err != nil {
|
if _, err := conn.Write([]byte(message)); err != nil {
|
||||||
log.Fatalf("Error occurred writing to server: %v\n", err)
|
log.Fatalf("Error occurred writing to server: %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -181,9 +107,6 @@ func GUI() {
|
||||||
g.SetManagerFunc(layout)
|
g.SetManagerFunc(layout)
|
||||||
g.Mouse = true
|
g.Mouse = true
|
||||||
g.Cursor = true
|
g.Cursor = true
|
||||||
if useASCII == true {
|
|
||||||
g.ASCII = true
|
|
||||||
}
|
|
||||||
initKeybindings(g)
|
initKeybindings(g)
|
||||||
|
|
||||||
go listenMessages(g)
|
go listenMessages(g)
|
||||||
|
@ -220,93 +143,50 @@ func sendToServer(g *gocui.Gui, v *gocui.View) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func scrollView(v *gocui.View, dy int) error {
|
|
||||||
if v != nil {
|
|
||||||
v.Autoscroll = false
|
|
||||||
ox, oy := v.Origin()
|
|
||||||
if err := v.SetOrigin(ox, oy+dy); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func autoscroll(g *gocui.Gui, v *gocui.View) error {
|
|
||||||
chatbox, err := g.View("chatbox")
|
|
||||||
if err != nil {
|
|
||||||
log.Panicf("Error happened setting autoscroll: %v\n", err)
|
|
||||||
}
|
|
||||||
chatbox.Autoscroll = true
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func initKeybindings(g *gocui.Gui) error {
|
func initKeybindings(g *gocui.Gui) error {
|
||||||
if err := g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit); err != nil {
|
if err := g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit); err != nil {
|
||||||
log.Panicln(err)
|
log.Panicln(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// if err := g.SetKeybinding("button", gocui.MouseLeft, gocui.ModNone, sendToServer); err != nil {
|
if err := g.SetKeybinding("button", gocui.MouseLeft, gocui.ModNone, sendToServer); err != nil {
|
||||||
// log.Panicln(err)
|
|
||||||
// }
|
|
||||||
|
|
||||||
if err := g.SetKeybinding("textarea", gocui.KeyCtrlA, gocui.ModNone, autoscroll); err != nil {
|
|
||||||
log.Panicln(err)
|
log.Panicln(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := g.SetKeybinding("textarea", gocui.KeyEnter, gocui.ModNone, sendToServer); err != nil {
|
if err := g.SetKeybinding("textarea", gocui.KeyEnter, gocui.ModNone, sendToServer); err != nil {
|
||||||
log.Panicln(err)
|
log.Panicln(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := g.SetKeybinding("chatbox", gocui.MouseWheelUp, gocui.ModNone,
|
|
||||||
func(g *gocui.Gui, v *gocui.View) error {
|
|
||||||
scrollView(v, -1)
|
|
||||||
return nil
|
|
||||||
}); err != nil {
|
|
||||||
log.Panicln(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := g.SetKeybinding("chatbox", gocui.MouseWheelDown, gocui.ModNone,
|
|
||||||
func(g *gocui.Gui, v *gocui.View) error {
|
|
||||||
scrollView(v, 1)
|
|
||||||
return nil
|
|
||||||
}); err != nil {
|
|
||||||
log.Panicln(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func layout(g *gocui.Gui) error {
|
func layout(g *gocui.Gui) error {
|
||||||
maxX, maxY := g.Size()
|
maxX, maxY := g.Size()
|
||||||
|
|
||||||
if chatbox, err := g.SetView("chatbox", 2, 1, maxX-2, maxY-5); err != nil {
|
if chatbox, err := g.SetView("chatbox", 2, 1, maxX/2+40, maxY-5); err != nil {
|
||||||
|
if err != gocui.ErrUnknownView {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
chatbox.Autoscroll = true
|
||||||
|
chatbox.Title = "Chat Box"
|
||||||
|
}
|
||||||
|
|
||||||
|
if button, err := g.SetView("button", maxX/2+32, maxY-4, maxX/2+40, maxY-2); err != nil {
|
||||||
if err != gocui.ErrUnknownView {
|
if err != gocui.ErrUnknownView {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
chatbox.Autoscroll = true
|
button.Wrap = true
|
||||||
chatbox.Title = "Chat Box (Find source at https://git.bulgariu.xyz/raul/mini-chat!)"
|
button.Frame = true
|
||||||
chatbox.Wrap = true
|
fmt.Fprintln(button, "Send it")
|
||||||
}
|
}
|
||||||
|
|
||||||
// if button, err := g.SetView("button", maxX/2+32, maxY-4, maxX-28, maxY-2); err != nil {
|
if textarea, err := g.SetView("textarea", 2, maxY-4, maxX/2+28, maxY-2); err != nil {
|
||||||
// if err != gocui.ErrUnknownView {
|
|
||||||
// return err
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// button.Wrap = true
|
|
||||||
// button.Frame = true
|
|
||||||
// fmt.Fprintln(button, "Send it")
|
|
||||||
// }
|
|
||||||
|
|
||||||
if textarea, err := g.SetView("textarea", 2, maxY-4, maxX-2, maxY-2); err != nil {
|
|
||||||
if err != gocui.ErrUnknownView {
|
if err != gocui.ErrUnknownView {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err := g.SetCurrentView("textarea"); err != nil {
|
if _, err := g.SetCurrentView("textarea"); err != nil {
|
||||||
log.Panicln(err)
|
log.Panicln(err)
|
||||||
}
|
}
|
||||||
textarea.Title = "(" + Profile.Username + ") " + "Send message" + " (Ctrl+A: Autoscroll)"
|
textarea.Title = "Send message"
|
||||||
textarea.Wrap = true
|
textarea.Wrap = true
|
||||||
textarea.Editable = true
|
textarea.Editable = true
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,10 +0,0 @@
|
||||||
#!/bin/bash
|
|
||||||
SSLCOMMAND=$(which openssl)
|
|
||||||
|
|
||||||
echo "[+] Generating server.key..."
|
|
||||||
$SSLCOMMAND genrsa -out server.key 2048
|
|
||||||
|
|
||||||
echo "[+] Generating server.crt..."
|
|
||||||
$SSLCOMMAND req -new -x509 -sha256 -key server.key -out server.crt -days 3650 -subj "/C=ES/ST=Valencia/L=Valencia/O=mini-chat /OU=mini-chat/CN=mini-chat"
|
|
||||||
|
|
||||||
echo "[+] Success!"
|
|
15
cmd/root.go
15
cmd/root.go
|
@ -9,13 +9,19 @@ import (
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// rootCmd represents the base command when called without any subcommands
|
||||||
var rootCmd = &cobra.Command{
|
var rootCmd = &cobra.Command{
|
||||||
Use: "mini-chat",
|
Use: "mini-chat",
|
||||||
Short: "Application for hosting and joining a simple chat server",
|
Short: "Application for hosting and joining a simple chat server",
|
||||||
|
|
||||||
Long: `Application for hosting and joining a simple chat server`,
|
Long: `Application for hosting and joining a simple chat server`,
|
||||||
|
// Uncomment the following line if your bare application
|
||||||
|
// has an action associated with it:
|
||||||
|
// Run: func(cmd *cobra.Command, args []string) { },
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Execute adds all child commands to the root command and sets flags appropriately.
|
||||||
|
// This is called by main.main(). It only needs to happen once to the rootCmd.
|
||||||
func Execute() {
|
func Execute() {
|
||||||
err := rootCmd.Execute()
|
err := rootCmd.Execute()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -24,4 +30,13 @@ func Execute() {
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
// Here you will define your flags and configuration settings.
|
||||||
|
// Cobra supports persistent flags, which, if defined here,
|
||||||
|
// will be global for your application.
|
||||||
|
|
||||||
|
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.chat-tests.yaml)")
|
||||||
|
|
||||||
|
// Cobra also supports local flags, which will only run
|
||||||
|
// when this action is called directly.
|
||||||
|
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,6 +9,7 @@ import (
|
||||||
"log"
|
"log"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// serverCmd represents the server command
|
||||||
var serverCmd = &cobra.Command{
|
var serverCmd = &cobra.Command{
|
||||||
Use: "server",
|
Use: "server",
|
||||||
Short: "Tiny chat server",
|
Short: "Tiny chat server",
|
||||||
|
@ -16,7 +17,7 @@ var serverCmd = &cobra.Command{
|
||||||
using a proper interface this time, not using netcat.
|
using a proper interface this time, not using netcat.
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
./mini-chat server --port 1337 --history chat.log --password coolh4x0r1337`,
|
./mini-chat server --port 1337`,
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
|
||||||
if err := setServerParameters(cmd); err != nil {
|
if err := setServerParameters(cmd); err != nil {
|
||||||
|
@ -29,10 +30,17 @@ Example:
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
rootCmd.AddCommand(serverCmd)
|
rootCmd.AddCommand(serverCmd)
|
||||||
serverCmd.PersistentFlags().StringP("port", "p", "1302", "Port to use for listening")
|
|
||||||
serverCmd.PersistentFlags().StringP("history", "r", "", "File to store and recover chat history from")
|
// Here you will define your flags and configuration settings.
|
||||||
serverCmd.PersistentFlags().String("password", "", "Password for accessing the chat server")
|
|
||||||
serverCmd.Flags().Bool("insecure", false, "[UNSAFE] Do not use TLS encryption")
|
// Cobra supports Persistent Flags which will work for this command
|
||||||
|
// and all subcommands, e.g.:
|
||||||
|
// serverCmd.PersistentFlags().String("foo", "", "A help for foo")
|
||||||
|
serverCmd.PersistentFlags().String("port", "1302", "port to use for listening")
|
||||||
|
|
||||||
|
// Cobra supports local flags which will only run when this command
|
||||||
|
// is called directly, e.g.:
|
||||||
|
// serverCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
||||||
}
|
}
|
||||||
|
|
||||||
func setServerParameters(cmd *cobra.Command) error {
|
func setServerParameters(cmd *cobra.Command) error {
|
||||||
|
@ -43,27 +51,5 @@ func setServerParameters(cmd *cobra.Command) error {
|
||||||
if parameterPort != "" {
|
if parameterPort != "" {
|
||||||
listenPort = parameterPort
|
listenPort = parameterPort
|
||||||
}
|
}
|
||||||
|
|
||||||
parameterHistory, err := cmd.Flags().GetString("history")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if parameterHistory != "" {
|
|
||||||
logLocation = parameterHistory
|
|
||||||
isLogging = true
|
|
||||||
}
|
|
||||||
|
|
||||||
parPassword, err := cmd.Flags().GetString("password")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if parPassword != "" {
|
|
||||||
password = parPassword
|
|
||||||
}
|
|
||||||
|
|
||||||
insecure, err := cmd.Flags().GetBool("insecure")
|
|
||||||
if insecure == true {
|
|
||||||
servInsecure = true
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,28 +6,19 @@ package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"crypto/tls"
|
|
||||||
_ "embed"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
listenPort string = "1302"
|
listenPort string = "1302"
|
||||||
password string = ""
|
|
||||||
isLogging bool = false
|
|
||||||
logLocation string
|
|
||||||
listenerList []chan string
|
|
||||||
servInsecure bool
|
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed gen-cert.sh
|
type Creator interface {
|
||||||
var script string
|
CreateUser()
|
||||||
|
}
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
Username string
|
Username string
|
||||||
|
@ -40,52 +31,8 @@ func (u User) CreateUser(usr string, ip string) User {
|
||||||
return u
|
return u
|
||||||
}
|
}
|
||||||
|
|
||||||
func createCerts() {
|
|
||||||
fmt.Println("[-] Certificates don't exist! Creating them...")
|
|
||||||
c := exec.Command("bash")
|
|
||||||
c.Stdin = strings.NewReader(script)
|
|
||||||
b, err := c.Output()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Error occurred creating certificates: %v\n", err)
|
|
||||||
}
|
|
||||||
fmt.Print(string(b))
|
|
||||||
}
|
|
||||||
|
|
||||||
func startInsecureServer() (net.Listener, error) {
|
|
||||||
ln, err := net.Listen("tcp", ":"+listenPort)
|
|
||||||
return ln, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func startSecureServer() (net.Listener, error) {
|
|
||||||
cer, err := tls.LoadX509KeyPair("server.crt", "server.key")
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
createCerts()
|
|
||||||
cer, err = tls.LoadX509KeyPair("server.crt", "server.key")
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Error happened loading certificates: %v\n", err)
|
|
||||||
}
|
|
||||||
config := &tls.Config{Certificates: []tls.Certificate{cer}}
|
|
||||||
ln, err := tls.Listen("tcp", ":"+listenPort, config)
|
|
||||||
return ln, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func getTime() string {
|
|
||||||
t := time.Now()
|
|
||||||
currentTime := fmt.Sprintf("%d-%02d-%02d | %02d:%02d:%02d", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
|
|
||||||
return currentTime
|
|
||||||
}
|
|
||||||
|
|
||||||
func Server() {
|
func Server() {
|
||||||
var ln net.Listener
|
ln, err := net.Listen("tcp", ":"+listenPort)
|
||||||
var err error
|
|
||||||
if servInsecure == true {
|
|
||||||
fmt.Println("WARNING: Starting unencrypted server!")
|
|
||||||
ln, err = startInsecureServer()
|
|
||||||
} else {
|
|
||||||
ln, err = startSecureServer()
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Error happened trying to listen on port: %v\n", err)
|
log.Fatalf("Error happened trying to listen on port: %v\n", err)
|
||||||
}
|
}
|
||||||
|
@ -96,12 +43,14 @@ func Server() {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Error happened trying to accept connection: %v\n", err)
|
log.Fatalf("Error happened trying to accept connection: %v\n", err)
|
||||||
}
|
}
|
||||||
chatChan := make(chan string, 30)
|
chatChan := make(chan string, 10)
|
||||||
listenerList = append(listenerList, chatChan)
|
listenerList = append(listenerList, chatChan)
|
||||||
go handleConn(conn, chatChan)
|
go handleConn(conn, chatChan)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var listenerList []chan string
|
||||||
|
|
||||||
func getUsername(conn net.Conn) (s string, err error) {
|
func getUsername(conn net.Conn) (s string, err error) {
|
||||||
conn.Write([]byte("What's your name?\nChoice: "))
|
conn.Write([]byte("What's your name?\nChoice: "))
|
||||||
name, err := bufio.NewReader(conn).ReadString('\n')
|
name, err := bufio.NewReader(conn).ReadString('\n')
|
||||||
|
@ -129,55 +78,9 @@ func removeFromList(chatChan chan string) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func populateChat(conn net.Conn) {
|
|
||||||
if isLogging == false {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
file, err := os.Open(logLocation)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("Error opening file for populating: %v\n", err)
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
scanner := bufio.NewScanner(file)
|
|
||||||
// For WHATEVER reason, writing to a TLS-based conn here appends newlines by default,
|
|
||||||
// so we have to split it off here to avoid ending up with chat logs full of
|
|
||||||
// unnecessary newlines
|
|
||||||
if servInsecure == true {
|
|
||||||
for scanner.Scan() {
|
|
||||||
conn.Write([]byte(fmt.Sprintln(scanner.Text())))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for scanner.Scan() {
|
|
||||||
conn.Write([]byte(fmt.Sprint(scanner.Text())))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func getPasswd(conn net.Conn) error {
|
|
||||||
conn.Write([]byte("Password: "))
|
|
||||||
userPassNewline, err := bufio.NewReader(conn).ReadString('\n')
|
|
||||||
userPass := strings.TrimRight(userPassNewline, "\n")
|
|
||||||
if err != nil {
|
|
||||||
e := fmt.Errorf("Node %v didn't respond to password prompt!\n", getIP(conn))
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
if userPass != password {
|
|
||||||
e := fmt.Errorf("Node %v attempted connecting with an incorrect password!\n", getIP(conn))
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleConn(conn net.Conn, chatChan chan string) {
|
func handleConn(conn net.Conn, chatChan chan string) {
|
||||||
defer conn.Close()
|
defer conn.Close()
|
||||||
|
|
||||||
if password != "" {
|
|
||||||
if err := getPasswd(conn); err != nil {
|
|
||||||
log.Print(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
go receiveMessageServer(conn, chatChan)
|
go receiveMessageServer(conn, chatChan)
|
||||||
|
|
||||||
//////////////////////////////////
|
//////////////////////////////////
|
||||||
|
@ -191,13 +94,11 @@ func handleConn(conn net.Conn, chatChan chan string) {
|
||||||
}
|
}
|
||||||
userIP := getIP(conn)
|
userIP := getIP(conn)
|
||||||
//////////////////////////////////
|
//////////////////////////////////
|
||||||
populateChat(conn)
|
|
||||||
|
|
||||||
newUserTemplate := new(User)
|
newUserTemplate := new(User)
|
||||||
newUser := newUserTemplate.CreateUser(userName, userIP)
|
newUser := newUserTemplate.CreateUser(userName, userIP)
|
||||||
joinMessage := fmt.Sprintf("[%v] %v has joined the chat!", getTime(), newUser.Username)
|
joinMessage := fmt.Sprintf("%v has joined the chat!", newUser.Username)
|
||||||
fmt.Println(joinMessage + " [" + newUser.IP + "]")
|
fmt.Println(joinMessage)
|
||||||
addToLog(fmt.Sprintln(joinMessage))
|
|
||||||
//conn.Write([]byte(joinMessage))
|
//conn.Write([]byte(joinMessage))
|
||||||
sendMessage(joinMessage)
|
sendMessage(joinMessage)
|
||||||
|
|
||||||
|
@ -205,9 +106,8 @@ func handleConn(conn net.Conn, chatChan chan string) {
|
||||||
for {
|
for {
|
||||||
message, err := getUserInput(conn)
|
message, err := getUserInput(conn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
quitMessage := fmt.Sprintf("[%v] %v has disconnected!", getTime(), newUser.Username)
|
quitMessage := fmt.Sprintf("%v has disconnected!", newUser.Username)
|
||||||
fmt.Println(quitMessage + " [" + newUser.IP + "]")
|
fmt.Println(quitMessage)
|
||||||
addToLog(fmt.Sprintln(quitMessage))
|
|
||||||
sendMessage(quitMessage)
|
sendMessage(quitMessage)
|
||||||
//removeFromList(chatChan)
|
//removeFromList(chatChan)
|
||||||
// if _, err := conn.Write([]byte(quitMessage)); err != nil {
|
// if _, err := conn.Write([]byte(quitMessage)); err != nil {
|
||||||
|
@ -215,10 +115,8 @@ func handleConn(conn net.Conn, chatChan chan string) {
|
||||||
// }
|
// }
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
finalMessage := fmt.Sprintf("[%v] %v: %v", getTime(), newUser.Username, strings.TrimRight(message, "\n"))
|
finalMessage := fmt.Sprintf("[%v] %v: %v", newUser.IP, newUser.Username, strings.TrimRight(message, "\n"))
|
||||||
fm := fmt.Sprintf("%v\n", finalMessage)
|
fmt.Printf("%v\n", finalMessage)
|
||||||
fmt.Print(fm)
|
|
||||||
addToLog(fm)
|
|
||||||
sendMessage(finalMessage)
|
sendMessage(finalMessage)
|
||||||
|
|
||||||
//chatChan <- finalMessage
|
//chatChan <- finalMessage
|
||||||
|
@ -250,15 +148,3 @@ func getIP(conn net.Conn) (IP string) {
|
||||||
}
|
}
|
||||||
return IP
|
return IP
|
||||||
}
|
}
|
||||||
|
|
||||||
func addToLog(s string) {
|
|
||||||
if isLogging == false {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
file, err := os.OpenFile(logLocation, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0640)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("Error occurred: %v\n", err)
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
file.WriteString(s)
|
|
||||||
}
|
|
||||||
|
|
Loading…
Reference in New Issue