Compare commits
9 Commits
seq
...
f062efc176
| Author | SHA1 | Date | |
|---|---|---|---|
| f062efc176 | |||
| bf95cadeac | |||
| cd8ac36097 | |||
| da3b784b05 | |||
| b93aff00d9 | |||
| 8d65145c2c | |||
| eb71ae1c51 | |||
| 0bd27c5a4c | |||
| f5bf217243 |
@@ -1,12 +1,30 @@
|
||||
all: client server
|
||||
server_clean:
|
||||
rm server
|
||||
|
||||
re: clean client server
|
||||
client_clean:
|
||||
rm client
|
||||
|
||||
clean:
|
||||
rm client.o server.o
|
||||
|
||||
client:
|
||||
go build -o client.o client.go
|
||||
clean: server_clean client_clean
|
||||
|
||||
server:
|
||||
go build -o server.o server.go
|
||||
go build server.go
|
||||
|
||||
client:
|
||||
go build client.go
|
||||
|
||||
build: server client
|
||||
|
||||
ins_server:
|
||||
go build -o ekho_server server.go
|
||||
mv ekho_server /usr/local/bin/
|
||||
cp ekho.service /etc/systemd/system/ekho.service
|
||||
mkdir -p ~/.config/ekho
|
||||
ln -s -r ./list.q ~/.config/ekho/list.q
|
||||
systemctl daemon-reload
|
||||
systemctl enable ekho
|
||||
systemctl start ekho
|
||||
systemctl status ekho
|
||||
|
||||
ins_client:
|
||||
go build -o ekho client.go
|
||||
mv ekho /usr/local/bin/
|
||||
|
||||
@@ -3,80 +3,86 @@
|
||||
## Why?
|
||||
To test my abilities to develop networked programs, and to enhance my skills in writing such.
|
||||
## Requirements
|
||||
|
||||
### Hardware
|
||||
- Client machine
|
||||
- Server machine (not required to be distinct from Client)
|
||||
|
||||
### Software
|
||||
- [Golang]
|
||||
- Linux distro (highly recommened)
|
||||
- ```make``` is also used in this guide, but the makefile is incredibly simple, and can be skipped entirely by running ```go build``` instead
|
||||
- Tested with [golang] v1.26
|
||||
- Installation has only been tested with [just] v1.53
|
||||
- Server installation assumes systemd (tested with v260.2)
|
||||
|
||||
### Installation
|
||||
Golang can be installed on Mac with
|
||||
``` sh
|
||||
brew install golang
|
||||
```
|
||||
Clone the repo
|
||||
``` sh
|
||||
git clone https://github.com/alexander-the-alright/ekho
|
||||
cd ekho
|
||||
```
|
||||
Using your favorite text editor, change the destination IP and Port to whatever works for you. This is defined on line 247 in client.go as 127.0.0.1:1300.
|
||||
|
||||
Now the server file needs to be run on the preferred port, as specified in the client file. This is defined on line 257 in server.go.
|
||||
#### Justfile
|
||||
It is recommended to use ```just``` for installation, as it has more
|
||||
capabilities than ```make```, however, there is a makefile included.
|
||||
To install the server with ```just```, run ```sudo just ins_server```.
|
||||
You will be prompted to enter a new port number to run the server on (
|
||||
or leave blank to use 1300). The port will be changed in the source
|
||||
file before compilation.
|
||||
To install the client with ```just```, run ```sudo just ins_client```.
|
||||
You will be prompted to enter the IP (or URL) and port of the server
|
||||
(or leave blank to use localhost:1300). The IP/URL and port will be
|
||||
changed in the source file before compilation.
|
||||
|
||||
#### Makefile
|
||||
If you are unable or willing to use ```just```, the included makefile
|
||||
still has most of the functionality, but it does not change any
|
||||
important parameters. The following changes are advised before
|
||||
installation.
|
||||
|
||||
The binary(s) can be obtained using the makefile
|
||||
If the server is being run on a separate machine, only run make with client flag
|
||||
``` sh
|
||||
make client
|
||||
```
|
||||
If both binaries are being run on the same machine, ```make all``` will suffice. Although, both of these commands can be bypassed with ```go build```, as this is all ```make``` does anyway.
|
||||
``` sh
|
||||
make all
|
||||
```
|
||||
1. On the client machine, change the IP/URL and port in the client source file. This can be
|
||||
done quickly with ```sed -i -e "s/127.0.0.1:1300/YOUR.IP.GOES.HERE:PORT/" client.go```
|
||||
2. On the server machine, change the port in the server source file. This can be done with a
|
||||
similar command: ```sed -i -e "s/1300/PORT/" server.go```. (note: this
|
||||
should match the port from bullet 1)
|
||||
3. On the server machine, change the user referenced in the systemd service file. This can be
|
||||
done with another sed command, ```sed -e -i "s/USER/YOUR_USERNAME/" ekho.service```
|
||||
|
||||
#### NOTE
|
||||
In previous versions, the suggested method of installation involved placing bash scripts in ```/etc/update-motd.d/```, however, there have been issues getting that installation method working (namely, having MOTD run user-defined commands), and the current quick and extremely dirty suggested installation method is to just append the user's shell config files (```.bashrc```, ```.bash_profile```, ```.zshrc```, etc) with the paths to the executables.
|
||||
After making these changes on the respective machines, run either
|
||||
```sudo make ins_client``` or ```sudo make ins_server``` to compile and install the client
|
||||
and/or server binaries.
|
||||
|
||||
For example, if the server used zsh, the installation could look something like this:
|
||||
``` sh
|
||||
echo "~/abs/path/to/server.o &" >> ~/.zshrc
|
||||
```
|
||||
Similarly for a client using Bash:
|
||||
``` sh
|
||||
echo "~/abs/path/to/client.o" >> ~/.bashrc
|
||||
```
|
||||
|
||||
Any help figuring out the issue with MOTD would be appreciated.
|
||||
#### After Installation
|
||||
After installation of the server binary, systemd will display the
|
||||
status of the new service. It should be ```enabled``` and
|
||||
```running```.
|
||||
|
||||
Finally done!
|
||||
|
||||
### Usage
|
||||
The client uses the following flags
|
||||
``` sh
|
||||
-h - display help message
|
||||
-a <s> - adds required argument <s> as a quote to server
|
||||
-l - list all quotes
|
||||
-r [i] - remove; may be run with or without argument
|
||||
-ip - specify alternate server destination
|
||||
-s - specify the size of the receipt buffer
|
||||
-h - display help message
|
||||
-a <string> - adds required argument <s> as a quote to server
|
||||
-ip <ip:port> - specify alternate server destination
|
||||
-l - list all quotes
|
||||
-r [i] - remove; may be run with or without argument
|
||||
-e - edit
|
||||
-s <i> - specify the size of the receipt buffer
|
||||
-v - display version and exit
|
||||
-vv - display version and about info and exit
|
||||
```
|
||||
The server uses the following flags
|
||||
``` sh
|
||||
-h - display help message
|
||||
-s - specify the size of the receipt buffer
|
||||
-s <i> - specify the size of the receipt buffer
|
||||
-v - display version and exit
|
||||
-vv - display version and about info and exit
|
||||
```
|
||||
|
||||
### How It Works
|
||||
The sequence diagram can be viewed in ```diag``` folder, which shows the sequence of networked messages for each usage of ekho.
|
||||
The source code is in the same folder, ```ekho-seq.txt```, and can be uploaded to [sequencediagram.org][seqdiag] to rerender the diagram and view any updates.
|
||||
|
||||
|
||||
### To Be Implemented
|
||||
- Log all uses/transaction data each day
|
||||
- Request, send, and receive the logfile for any day
|
||||
- Request, send, and receive the logfile
|
||||
- User-specific quotes/quotefiles
|
||||
- Installation (client-side, at least) via MOTD
|
||||
|
||||
- Colored printing and coloring quotes
|
||||
|
||||
[golang]: <https://go.dev/doc/install>
|
||||
[seqdiag]: <sequencediagram.org>
|
||||
[just]: <https://github.com/casey/just>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// =============================================================================
|
||||
// Auth: alex
|
||||
// File: client.go
|
||||
// Revn: 06-14-2024 3.0
|
||||
// Revn: 09-06-2026 3.0.0
|
||||
// Func: ask server for a message of the day quote
|
||||
//
|
||||
// TODO: remove ioutil import
|
||||
@@ -24,28 +24,39 @@
|
||||
// imported check() from soary
|
||||
// 09-29-2023: commented handle()
|
||||
//*10-02-2023: commented main(), and friends
|
||||
//*10-05-2023: /remove/ works
|
||||
//#10-05-2023: /remove/ works
|
||||
// removed -d flag
|
||||
// commented
|
||||
// 06-12-2024: began added PWFT to /la/
|
||||
// 06-13-2024: finished adding PWFT to /la/
|
||||
// commented PWFT stuff
|
||||
// STARTED BYTE-BASED PWFT REWRITE
|
||||
//*06-14-2024: finished byte-based PWFT rewrite
|
||||
//#06-14-2024: finished byte-based PWFT rewrite
|
||||
// commented
|
||||
//*01-09-2025: basically just copy/pasted from /la/ into /r1/, /r2/
|
||||
// 06-21-2026: copied v and vv flags from server
|
||||
// copied /edit/ switch case from /remove/ in main()
|
||||
// pulled /sa/ and /qa/ into separate functions
|
||||
// 09-03-2026: renamed in() -> inputNumber()
|
||||
// copied in() and removed all logic
|
||||
// added firstEdit() and secondEdit() and /e1/ and /e2/
|
||||
// 09-04-2026: rewrote in() with bufio instead of scanln
|
||||
//#09-06-2026: fixed blank message error in secondEdit()
|
||||
// comments
|
||||
//
|
||||
// =============================================================================
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
import (
|
||||
"bufio" // NewReader, ReadString
|
||||
"io" // io.EOF
|
||||
"io/ioutil" // ReadFile
|
||||
"flag" // BoolVar, StringVar, Parse
|
||||
"fmt" // Println
|
||||
"math/rand" // NewSource, New, Intn, *rand.Rand
|
||||
"net" // ResolveTCPAddr, DialTCP, conn.Write,Read
|
||||
"os" // Exit, Create
|
||||
"os" // Exit, Create, Stdin
|
||||
"strconv" // Atoi, Itoa
|
||||
"strings" // Split
|
||||
"time" // Now, UnixNano
|
||||
@@ -84,20 +95,37 @@ func check( err error ) {
|
||||
|
||||
// get user input
|
||||
func in( prompt string ) string {
|
||||
// instantiate reader
|
||||
reader := bufio.NewReader( os.Stdin )
|
||||
fmt.Print( prompt ) // print user prompt
|
||||
var input string // declare var to hold user input
|
||||
fmt.Scanln( &input ) // get user input
|
||||
// get user input, read until newline
|
||||
input, _ := reader.ReadString( '\n' )
|
||||
// strip trailing newline before returning
|
||||
return input[:len( input ) - 1]
|
||||
}
|
||||
|
||||
|
||||
// get user input, must be a number
|
||||
func inputNumber( prompt string ) string {
|
||||
// get user input
|
||||
//input := in( prompt )
|
||||
fmt.Print( prompt )
|
||||
var input string
|
||||
fmt.Scanln( &input )
|
||||
|
||||
// try to convert to an int, discard results
|
||||
_, err := strconv.Atoi( input )
|
||||
// if there was an error, user didn't input an int
|
||||
if err != nil {
|
||||
// warn user against this
|
||||
fmt.Println( "Input must be a number" )
|
||||
input = in( prompt ) // try to get user input again
|
||||
// try to get user input again
|
||||
//XXX input = in( prompt )
|
||||
fmt.Println( "err: ", err.Error() )
|
||||
// this, like handle() calling handle(), seems like a super
|
||||
// bad idea, stack-wise...
|
||||
}
|
||||
// once user has properly inputted a number, return string of num
|
||||
// once user has properly inputted a number, return string of num
|
||||
return input
|
||||
}
|
||||
|
||||
@@ -112,7 +140,7 @@ func seed() *rand.Rand {
|
||||
|
||||
|
||||
// get a random number
|
||||
func draw() string {
|
||||
func draw( qsize int ) string {
|
||||
rn := seed() // get a random seed
|
||||
r := rn.Intn( qsize ) // get a random number using seed
|
||||
// convert random number to ascii, because converting
|
||||
@@ -122,6 +150,273 @@ func draw() string {
|
||||
}
|
||||
|
||||
|
||||
// respond to size answer
|
||||
func sizeAnswer( subcom []string ) string {
|
||||
// subcom should contain only a size
|
||||
// convert to int, catch error
|
||||
size, err := strconv.Atoi( subcom[0] )
|
||||
|
||||
if err != nil { // if int conversion failed ( for some reason )
|
||||
os.Exit( 1 ) // just quit
|
||||
// TODO make exit codes unique, document them
|
||||
}
|
||||
|
||||
// draw a random number, add to quote request
|
||||
return "qr@" + draw( size )
|
||||
|
||||
}
|
||||
|
||||
|
||||
// receive quote, print
|
||||
func quoteAnswer( subcom []string ) string {
|
||||
fmt.Println( subcom[0] ) // whole-ass just print quote
|
||||
return "te@success" // set transaction end message
|
||||
}
|
||||
|
||||
|
||||
// add answer
|
||||
func addAnswer( subcom []string ) string {
|
||||
|
||||
var resp string = "te@"
|
||||
|
||||
// if server says add succeeded
|
||||
if subcom[0] == "success" {
|
||||
fmt.Println( "Add successful" ) // print success
|
||||
resp = resp + "success" // set transaction end message
|
||||
// if server says add failed
|
||||
} else if subcom[0] == "error" {
|
||||
fmt.Println( "Add failed" ) // print fail
|
||||
resp = resp + "error" // set transaction end message
|
||||
// unknown status message
|
||||
} else {
|
||||
// print unknown status
|
||||
fmt.Println( "Unknown status code: " + subcom[0] )
|
||||
// TODO should this be unknown instead of error?
|
||||
resp = resp + "error" // set transaction end message
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
|
||||
// receive answer to list
|
||||
func listAnswer( subcom []string ) string {
|
||||
|
||||
var resp string
|
||||
|
||||
if len( subcom ) > 1 { // multistage send condition
|
||||
if subcom[0] == "X" { // final message
|
||||
// TODO update
|
||||
// read entire temp storage file as byte array
|
||||
tfile, err := ioutil.ReadFile( "temp.q" )
|
||||
check( err ) // check read for errors
|
||||
// cast file to string, concat with recv'd string
|
||||
tstr := string( tfile ) + subcom[1]
|
||||
// split concat over newlines, separating quotes
|
||||
tlist := strings.Split( tstr, "\n" )
|
||||
// iterate over array, printing each quote
|
||||
for p, v := range tlist {
|
||||
fmt.Println( p + 1, "\t", v )
|
||||
}
|
||||
// delete temp storage file
|
||||
err = os.Remove( "temp.q" )
|
||||
check( err ) // check rm for errors
|
||||
resp = "te@X" // successful response message
|
||||
} else { // first or intermediate message
|
||||
// open temp quote storage file, creating if
|
||||
// necessary, with write-only permissions, in
|
||||
// append mode, wr u perm, r g/w perm
|
||||
f, err := os.OpenFile( "temp.q", os.O_WRONLY | os.O_APPEND | os.O_CREATE, 0644 )
|
||||
check( err ) // check file open for errors
|
||||
// write received message to file, keeping track
|
||||
// of bytes written
|
||||
n, err := f.WriteString( subcom[1] )
|
||||
check( err ) // check file write for errors
|
||||
// cast bytes already written field to int
|
||||
b, err := strconv.Atoi( subcom[0] )
|
||||
check( err ) // check cast for errors
|
||||
// add bytes just written to bytes already written, cast
|
||||
// back to string, and append to response variable
|
||||
resp = "lr@" + strconv.Itoa( b + n )
|
||||
}
|
||||
} else {
|
||||
// split recv'd message over \n, create quote list
|
||||
quotes := strings.Split( subcom[0], "\n" )
|
||||
for p, v := range quotes { // iterate over quotes
|
||||
// print num of quote, followed by that quote
|
||||
fmt.Println( p + 1, "\t", v )
|
||||
}
|
||||
resp = "te@success" // set transaction end message
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
|
||||
// first round edit request
|
||||
func firstEdit( subcom []string ) string {
|
||||
|
||||
var resp string
|
||||
|
||||
if len( subcom ) > 1 { // multistage send condition
|
||||
if subcom[0] == "X" { // final message
|
||||
// TODO update
|
||||
// read entire temp storage file as byte array
|
||||
tfile, err := ioutil.ReadFile( "temp.q" )
|
||||
check( err ) // check read for errors
|
||||
// cast file to string, concat with recv'd string
|
||||
tstr := string( tfile ) + subcom[1]
|
||||
// split concat over newlines, separating quotes
|
||||
tlist := strings.Split( tstr, "\n" )
|
||||
// iterate over array, printing each quote
|
||||
for p, v := range tlist {
|
||||
fmt.Println( p + 1, "\t", v )
|
||||
}
|
||||
// delete temp storage file
|
||||
err = os.Remove( "temp.q" )
|
||||
check( err ) // check rm for errors
|
||||
// ask user which quote to remove
|
||||
resp = "e2@" + inputNumber( "\n-> " )
|
||||
} else { // first or intermediate message
|
||||
// open temp quote storage file, creating if
|
||||
// necessary, with write-only permissions, in
|
||||
// append mode, wr u perm, r g/w perm
|
||||
f, err := os.OpenFile( "temp.q", os.O_WRONLY | os.O_APPEND | os.O_CREATE, 0644 )
|
||||
check( err ) // check file open for errors
|
||||
// write received message to file, keeping track
|
||||
// of bytes written
|
||||
n, err := f.WriteString( subcom[1] )
|
||||
check( err ) // check file write for errors
|
||||
// cast bytes already written field to int
|
||||
b, err := strconv.Atoi( subcom[0] )
|
||||
check( err ) // check cast for errors
|
||||
// add bytes just written to bytes already written, cast
|
||||
// back to string, and append to response variable
|
||||
resp = "e1@" + strconv.Itoa( b + n )
|
||||
}
|
||||
} else {
|
||||
// split recv'd message over \n, create quote list
|
||||
quotes := strings.Split( subcom[0], "\n" )
|
||||
for p, v := range quotes { // iterate over quotes
|
||||
// print num of quote, followed by that quote
|
||||
fmt.Println( p + 1, "\t", v )
|
||||
}
|
||||
// ask user which quote to edit
|
||||
resp = "e2@" + inputNumber( "\n-> " )
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
|
||||
// second round edit request ( and also third, technically )
|
||||
func secondEdit( subcom []string ) string {
|
||||
// success message and edit request pt2 come to the same place
|
||||
if subcom[0] == "success" {
|
||||
// print success and end transaction
|
||||
fmt.Println( "Edit successful" )
|
||||
return "te@success"
|
||||
}
|
||||
|
||||
// edit command is a removal and an add
|
||||
var resp string
|
||||
resp = "cr@r2@" + subcom[0] + "@ar@"
|
||||
// server response is text to be edited
|
||||
fmt.Println( "as is: " + subcom[1] )
|
||||
fmt.Print( "preview: " ) // won't be useful until pretty print
|
||||
_ = quoteAnswer( subcom[1:] ) // display quote properly
|
||||
|
||||
// get user input for new quote and send
|
||||
resp = resp + in( "\nupdate -> " )
|
||||
return resp
|
||||
}
|
||||
|
||||
|
||||
// list of all quotes, pick which to remove
|
||||
func firstRemove( subcom []string ) string {
|
||||
// the idea is that if the user doesn't specify which quote to
|
||||
// remove, list all quotes and let the user choose the quote
|
||||
// to remove. There was probably a way to handle this a little
|
||||
// more simply, but this, I feel, has some nuance to it that I
|
||||
// actually like
|
||||
|
||||
var resp string
|
||||
|
||||
if len( subcom ) > 1 { // multistage send condition
|
||||
if subcom[0] == "X" { // final message
|
||||
// TODO update
|
||||
// read entire temp storage file as byte array
|
||||
tfile, err := ioutil.ReadFile( "temp.q" )
|
||||
check( err ) // check read for errors
|
||||
// cast file to string, concat with recv'd string
|
||||
tstr := string( tfile ) + subcom[1]
|
||||
// split concat over newlines, separating quotes
|
||||
tlist := strings.Split( tstr, "\n" )
|
||||
// iterate over array, printing each quote
|
||||
for p, v := range tlist {
|
||||
fmt.Println( p + 1, "\t", v )
|
||||
}
|
||||
// delete temp storage file
|
||||
err = os.Remove( "temp.q" )
|
||||
check( err ) // check rm for errors
|
||||
// ask user which quote to remove
|
||||
resp = "r2@" + inputNumber( "\n-> " )
|
||||
} else { // first or intermediate message
|
||||
// open temp quote storage file, creating if
|
||||
// necessary, with write-only permissions, in
|
||||
// append mode, wr u perm, r g/w perm
|
||||
f, err := os.OpenFile( "temp.q", os.O_WRONLY | os.O_APPEND | os.O_CREATE, 0644 )
|
||||
check( err ) // check file open for errors
|
||||
// write received message to file, keeping track
|
||||
// of bytes written
|
||||
n, err := f.WriteString( subcom[1] )
|
||||
check( err ) // check file write for errors
|
||||
// cast bytes already written field to int
|
||||
b, err := strconv.Atoi( subcom[0] )
|
||||
check( err ) // check cast for errors
|
||||
// add bytes just written to bytes already written, cast
|
||||
// back to string, and append to response variable
|
||||
resp = "r1@" + strconv.Itoa( b + n )
|
||||
}
|
||||
} else {
|
||||
// split recv'd message over \n, create quote list
|
||||
quotes := strings.Split( subcom[0], "\n" )
|
||||
for p, v := range quotes { // iterate over quotes
|
||||
// print num of quote, followed by that quote
|
||||
fmt.Println( p + 1, "\t", v )
|
||||
}
|
||||
// ask user which quote to remove
|
||||
resp = "r2@" + inputNumber( "\n-> " )
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
|
||||
// second remove, determine if success or failure
|
||||
func secondRemove( subcom []string ) string {
|
||||
var resp string
|
||||
// if server says remove succeeded
|
||||
if subcom[0] == "success" {
|
||||
fmt.Println( "Remove successful\n" ) // success
|
||||
// list all quotes to validate remove succeeded
|
||||
// TODO should /aa/ also make /lr/ before /te/?
|
||||
resp = "lr@init" // set transaction end message
|
||||
} else if subcom[0] == "error" { // if server says remove failed
|
||||
fmt.Println( "Remove failed" ) // print failure
|
||||
resp = "te@error" // set transaction end message
|
||||
} else { // if unknown status message
|
||||
// TODO there's a known issue where if the buffer
|
||||
// size ( -s ) is less than 10, on the server side,
|
||||
// 'success' will get cut off ( r2@success )
|
||||
// and /r2/ will end up down here despite having
|
||||
// actually worked correctly, and will not display the
|
||||
// list, as it should on success
|
||||
// print unknown status
|
||||
fmt.Println( "Unknown error code: " + subcom[0] )
|
||||
// TODO should this be unknown instead of error?
|
||||
resp = "te@error" // set transaction end message
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
|
||||
// get server response and print
|
||||
func handle( conn net.Conn ) {
|
||||
|
||||
@@ -134,130 +429,37 @@ func handle( conn net.Conn ) {
|
||||
check( err ) // check for errors
|
||||
|
||||
// split recv'd message over @, separate header from message
|
||||
msg := strings.Split( string( buffer[:n] ), "@" )
|
||||
message := strings.Split( string( buffer[:n] ), "@" )
|
||||
command := message[0]
|
||||
|
||||
var resp string // declare response variable
|
||||
switch msg[0] { // switch/case over the header
|
||||
switch command { // switch/case over the header
|
||||
// if message is...
|
||||
case "sa": // /sa/, size answer
|
||||
// convert back half to int, catch error
|
||||
size, nerr := strconv.Atoi( msg[1] )
|
||||
if nerr == nil { // if there was no error
|
||||
qsize = size // set size global to recv'd size
|
||||
} else {
|
||||
// if int conversion failed, just quit
|
||||
// TODO make more robust
|
||||
os.Exit( 1 )
|
||||
}
|
||||
req := draw() // draw a random number
|
||||
resp = "qr@" + req // create quote query with rng
|
||||
case "ba": // /ba/, bad answer
|
||||
// TODO create server-side, and handle client-side
|
||||
fmt.Println( "error in " + msg[1] + ": " + msg[2] )
|
||||
resp = "te@error" // set transaction end message
|
||||
resp = sizeAnswer( message[1:] )
|
||||
case "qa": // /qa/, quote answer
|
||||
fmt.Println( msg[1] ) // whole-ass just print quote
|
||||
resp = "te@success" // set transaction end message
|
||||
case "la": // /la/, list answer
|
||||
if len( msg ) > 2 { // multistage send condition
|
||||
if msg[1] == "X" { // final message
|
||||
// TODO update
|
||||
// read entire temp storage file as byte array
|
||||
tfile, err := ioutil.ReadFile( "temp.q" )
|
||||
check( err ) // check read for errors
|
||||
// cast file to string, concat with recv'd string
|
||||
tstr := string( tfile ) + msg[2]
|
||||
// split concat over newlines, separating quotes
|
||||
tlist := strings.Split( tstr, "\n" )
|
||||
// iterate over array, printing each quote
|
||||
for p, v := range tlist {
|
||||
fmt.Println( p + 1, "\t", v )
|
||||
}
|
||||
// delete temp storage file
|
||||
err = os.Remove( "temp.q" )
|
||||
check( err ) // check rm for errors
|
||||
resp = "te@X" // successful response message
|
||||
} else { // first or intermediate message
|
||||
// open temp quote storage file, creating if
|
||||
// necessary, with write-only permissions, in
|
||||
// append mode, wr u perm, r g/w perm
|
||||
f, err := os.OpenFile( "temp.q", os.O_WRONLY | os.O_APPEND | os.O_CREATE, 0644 )
|
||||
check( err ) // check file open for errors
|
||||
// write received message to file, keeping track
|
||||
// of bytes written
|
||||
n, err = f.WriteString( msg[2] )
|
||||
check( err ) // check file write for errors
|
||||
// cast bytes already written field to int
|
||||
b, err := strconv.Atoi( msg[1] )
|
||||
check( err ) // check cast for errors
|
||||
// add bytes just written to bytes already
|
||||
// written, cast back to string, and append to
|
||||
// response variable
|
||||
resp = "lr@" + strconv.Itoa( b + n )
|
||||
}
|
||||
} else {
|
||||
// split recv'd message over \n, create quote list
|
||||
quotes := strings.Split( msg[1], "\n" )
|
||||
for p, v := range quotes { // iterate over quotes
|
||||
// print num of quote, followed by that quote
|
||||
fmt.Println( p + 1, "\t", v )
|
||||
}
|
||||
resp = "te@success" // set transaction end message
|
||||
}
|
||||
resp = quoteAnswer( message[1:] )
|
||||
case "aa": // /aa/, add answer
|
||||
// if server says add succeeded
|
||||
if msg[1] == "success" {
|
||||
fmt.Println( "Add successful" ) // print success
|
||||
resp = "te@success" // set transaction end message
|
||||
// if server says add failed
|
||||
} else if msg[1] == "error" {
|
||||
fmt.Println( "Add failed" ) // print fail
|
||||
resp = "te@error" // set transaction end message
|
||||
// unknown status message
|
||||
} else {
|
||||
// print unknown status
|
||||
fmt.Println( "Unknown status code: " + msg[1] )
|
||||
// TODO should this be unknown instead of error?
|
||||
resp = "te@error" // set transaction end message
|
||||
}
|
||||
resp = addAnswer( message[1:] )
|
||||
case "la": // /la/, list answer
|
||||
resp = listAnswer( message[1:] )
|
||||
case "e1": // /e1/, edit quote ( first transaction )
|
||||
resp = firstEdit( message[1:] )
|
||||
case "e2": // /e2/, edit quote ( second transaction )
|
||||
resp = secondEdit( message[1:] )
|
||||
case "r1": // /r1/, remove ( first transaction )
|
||||
// the idea is that if the user doesn't specify which quote to
|
||||
// remove, list all quotes and let the user choose the quote
|
||||
// to remove. There was probably a way to handle this a little
|
||||
// more simply, but this, I feel, has some nuance to it that I
|
||||
// actually like
|
||||
// redo /la/, list all quotes
|
||||
// split recv'd message over newline to create quote list
|
||||
quotes := strings.Split( msg[1], "\n" )
|
||||
for p, v := range quotes { // iterate over quotes
|
||||
// print num of quote, followed by that quote
|
||||
fmt.Println( p + 1, "\t", v )
|
||||
}
|
||||
// ask user which quote to remove
|
||||
resp = "r2@" + in( "\n-> " )
|
||||
resp = firstRemove( message[1:] )
|
||||
case "r2": // /r2/, remove ( second transaction )
|
||||
// if server says remove succeeded
|
||||
if msg[1] == "success" {
|
||||
fmt.Println( "Remove successful\n" ) // success
|
||||
// list all quotes to validate remove succeeded
|
||||
// TODO should /aa/ also make /lr/ before /te/?
|
||||
resp = "lr@dumvar" // set transaction end message
|
||||
// if server says remove failed
|
||||
} else if msg[1] == "error" {
|
||||
fmt.Println( "Remove failed" ) // print failure
|
||||
resp = "te@error" // set transaction end message
|
||||
// if unknown status message
|
||||
} else {
|
||||
// print unknown status
|
||||
fmt.Println( "Unknown error code: " + msg[1] )
|
||||
// TODO should this be unknown instead of error?
|
||||
resp = "te@error" // set transaction end message
|
||||
}
|
||||
resp = secondRemove( message[1:] )
|
||||
case "br": // /br/, bad request
|
||||
// client has asked for something nonsensical
|
||||
// TODO write out to file
|
||||
fmt.Println( "Client sent a bad request" )
|
||||
resp = "te@error" // set transaction end message
|
||||
case "ba": // /ba/, bad answer
|
||||
// TODO create server-side, and handle client-side
|
||||
fmt.Println( "error in " + message[1] + ": " + message[2] )
|
||||
resp = "te@error" // set transaction end message
|
||||
default: // something undefined entirely
|
||||
// TODO write out to file
|
||||
//fmt.Println( "Message header not recognized" )
|
||||
@@ -275,7 +477,7 @@ func handle( conn net.Conn ) {
|
||||
|
||||
|
||||
// globals
|
||||
var qsize int // keep track of num of quotes
|
||||
//var qsize int // keep track of num of quotes
|
||||
var conn net.Conn // keep track of connection
|
||||
|
||||
|
||||
@@ -283,18 +485,40 @@ var conn net.Conn // keep track of connection
|
||||
var add bool // add new quotes to quote file ( on server )
|
||||
var remove bool // remove quotes from quote file ( on server )
|
||||
var list bool // request entire quote file from server
|
||||
var edit bool // edit a pre-existing quote from quote file ( on server )
|
||||
var dest string // provide a new destination ip and port
|
||||
var tsize int // size of transmission buffer
|
||||
var VERS string // version
|
||||
|
||||
func main() {
|
||||
|
||||
var v bool // version flag
|
||||
var vv bool // big version flag
|
||||
|
||||
// define flags
|
||||
flag.BoolVar( &add, "a", false, "add quote to list" )
|
||||
flag.BoolVar( &add, "a", false, "add quote to list" )
|
||||
flag.BoolVar( &remove, "r", false, "remove quote from list" )
|
||||
flag.BoolVar( &list, "l", false, "print quote list" )
|
||||
flag.StringVar( &dest, "ip", ":1300", "ip:port of server" )
|
||||
flag.IntVar( &tsize, "s", 256, "transmission size ( bytes )" )
|
||||
flag.Parse() // process flags
|
||||
flag.BoolVar( &list, "l", false, "print quote list" )
|
||||
flag.BoolVar( &edit, "e", false, "edit quote from list" )
|
||||
flag.StringVar( &dest, "ip", "127.0.0.1:1300", "ip:port of server" )
|
||||
flag.IntVar( &tsize, "s", 256, "transmission size ( bytes )" )
|
||||
flag.BoolVar( &v, "v", false, "display version and exit" )
|
||||
flag.BoolVar( &vv, "vv", false, "display version and about info and exit" )
|
||||
flag.Parse()
|
||||
|
||||
// FIXME get better versioning method
|
||||
VERS = "3.0.0"
|
||||
|
||||
if vv { // display info and exit
|
||||
fmt.Println( "ekho client v" + VERS )
|
||||
fmt.Println( "ekho is named after Echo the Oread" )
|
||||
fmt.Println( "in Greek mythology, Echo was cursed by Hera to only be able to say the last words spoken to her" )
|
||||
fmt.Println( "i found this to be quite fitting for a MOTD server" )
|
||||
return
|
||||
} else if v { // display info and exit
|
||||
fmt.Println( VERS )
|
||||
return
|
||||
}
|
||||
|
||||
service := dest // declare server ip:port
|
||||
|
||||
@@ -328,6 +552,27 @@ func main() {
|
||||
fmt.Println( "/a/ flag must be used with an arugment" )
|
||||
os.Exit( 1 )
|
||||
}
|
||||
case edit: // if edit flag is active
|
||||
// if arguments were specified
|
||||
if len( flag.Args() ) > 0 {
|
||||
// argument is supposed to the number of the quote to
|
||||
// be edited, get first arg
|
||||
// cast to int just to make sure it's a valid number
|
||||
// assuming the user knows what they're doing
|
||||
_, rerr := strconv.Atoi( flag.Args()[0] )
|
||||
// if there was an error, just pretend there's no args
|
||||
if rerr != nil {
|
||||
command = "e1@init" // remove request 1
|
||||
} else {
|
||||
// if user knows the number, take care of it
|
||||
// arg[0] is a string, so concat is cool
|
||||
// jump right into edit request 2
|
||||
command = "e2@" + flag.Args()[0]
|
||||
}
|
||||
} else { // if no argument was specified for edit
|
||||
// jump right into edit request 1
|
||||
command = "e1@init"
|
||||
}
|
||||
case remove: // if remove flag is active
|
||||
// if arguments were specified
|
||||
if len( flag.Args() ) > 0 {
|
||||
@@ -338,8 +583,7 @@ func main() {
|
||||
_, rerr := strconv.Atoi( flag.Args()[0] )
|
||||
// if there was an error, just pretend there's no args
|
||||
if rerr != nil {
|
||||
command = "r1@dumvar" // remove request 1
|
||||
// TODO come up w/ useful argument, replace dumvar
|
||||
command = "r1@init" // remove request 1
|
||||
} else {
|
||||
// if user knows the number, take care of it
|
||||
// arg[0] is a string, so concat is cool
|
||||
@@ -348,7 +592,7 @@ func main() {
|
||||
}
|
||||
} else { // if no argument was specified for remove
|
||||
// jump right into remove request 1
|
||||
command = "r1@dumvar"
|
||||
command = "r1@init"
|
||||
}
|
||||
default: // if no flag was specified
|
||||
// begin transaction for quote request
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=Ekho MOTD Server
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
User=USER
|
||||
ExecStart=/usr/local/bin/ekho_server
|
||||
WorkingDirectory=/home/USER/.config/ekho
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,69 @@
|
||||
# delete server bin
|
||||
[private]
|
||||
server_clean:
|
||||
rm server
|
||||
|
||||
# delete client bin
|
||||
[private]
|
||||
client_clean:
|
||||
rm client
|
||||
|
||||
# delete binaries
|
||||
clean: server_clean client_clean
|
||||
|
||||
# build server bin
|
||||
server:
|
||||
go build server.go
|
||||
|
||||
# build client bin
|
||||
client:
|
||||
go build client.go
|
||||
|
||||
# build both bins
|
||||
build: client server
|
||||
|
||||
# delete binaries and make them again
|
||||
rebuild: clean build
|
||||
|
||||
# install server
|
||||
ins_server:
|
||||
#!/usr/bin/bash
|
||||
echo "enter port of server or leave blank to use default (1300)"
|
||||
read PORT
|
||||
if [[ $PORT -ne "" ]]; then
|
||||
sed -i -e "s/1300/$PORT/" server.go
|
||||
fi
|
||||
echo "go build -o ekho_server server.go"
|
||||
go build -o ekho_server server.go
|
||||
echo "mv ekho_server /usr/local/bin/"
|
||||
mv ekho_server /usr/local/bin/
|
||||
USER=($(users))
|
||||
sed -i -e "s/USER/${USER[0]}/" ekho.service
|
||||
echo "cp ekho.service /etc/systemd/system/"
|
||||
cp ekho.service /etc/systemd/system/
|
||||
mkdir -p ~/.config/ekho
|
||||
echo "ln -s -r ./list.q ~/.config/ekho/list.q"
|
||||
ln -s -r ./list.q ~/.config/ekho/list.q
|
||||
echo "systemctl daemon-reload"
|
||||
systemctl daemon-reload
|
||||
echo "systemctl enable ekho"
|
||||
systemctl enable ekho
|
||||
echo "systemctl start ekho"
|
||||
systemctl start ekho
|
||||
echo "systemctl status ekho"
|
||||
systemctl status ekho
|
||||
|
||||
|
||||
# install client
|
||||
ins_client:
|
||||
#!/usr/bin/bash
|
||||
echo "enter url or ip and port of server, 'aaa.bbb.ccc.ddd:port"
|
||||
read IP_PORT
|
||||
sed -i -e "s/:1300/$IP_PORT/" client.go
|
||||
echo "go build -o ekho client.go"
|
||||
go build -o ekho client.go
|
||||
sed -i -e "s/$IP_PORT/:1300/" client.go
|
||||
echo "mv ekho /usr/local/bin/"
|
||||
mv ekho /usr/local/bin/
|
||||
echo "add 'ekho' to shell config (config.fish, .bashrc, etc)"
|
||||
|
||||
@@ -1 +1,9 @@
|
||||
@user:
|
||||
shmuley
|
||||
floglin
|
||||
@all:
|
||||
blingo
|
||||
no but like actually blingo shmingo
|
||||
i would prefer not to
|
||||
@default:
|
||||
thank you for using ekho
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
// =============================================================================
|
||||
// Auth: alex
|
||||
// File: server.go
|
||||
// Revn: 06-14-2024 4.0
|
||||
// Revn: 09-06-2026 3.0.0
|
||||
// Func: host MOTD connection
|
||||
//
|
||||
// TODO: catch keyboard int. signal
|
||||
// remove ioutil import
|
||||
// add more /codes/ to handle
|
||||
// add flags, like specify port
|
||||
// TODO: add user-specific prints
|
||||
// write usage and errors to logfile
|
||||
// remove ioutil import
|
||||
// send logfile to client on request
|
||||
// add color printing to qfile
|
||||
// add flags?
|
||||
// add more /codes/ to handle
|
||||
// =============================================================================
|
||||
// CHANGE LOG
|
||||
// -----------------------------------------------------------------------------
|
||||
@@ -32,7 +33,7 @@
|
||||
// fixed bug in /r2/ where removing quote at final
|
||||
// position would break
|
||||
// removed deadcode from /r2/, unused "quit" bool?
|
||||
//*10-17-2023: fixed bug where quotes are read from and saved to two
|
||||
//#10-17-2023: fixed bug where quotes are read from and saved to two
|
||||
// different files
|
||||
// removed implicit newline at end of qfile to stop ghost
|
||||
// line bug in /la/
|
||||
@@ -43,6 +44,14 @@
|
||||
// 06-13-2024: removed debug print statements
|
||||
// commented
|
||||
//*06-14-2024: byte count-based PWFT rewrite
|
||||
//*06-17-2024: catch keyboard interrupts with os/signal and syscall
|
||||
//#01-09-2025: copied lr/la PWFT updates into r1/r2
|
||||
//*04-28-2026: removed implicit newline at end of qfile to stop ghost
|
||||
// line bug in /la/ AGAIN
|
||||
// 05-11-2026: updated fread() to handle users in qfile
|
||||
// 05-12-2026: added v and vv input flags
|
||||
// 09-05-2026: buncha shit happened, dropped the commit
|
||||
//#09-06-2026: added /e1/, /e2/, and /cr/, got edit working
|
||||
//
|
||||
// =============================================================================
|
||||
|
||||
@@ -55,9 +64,11 @@ import (
|
||||
"io/ioutil" // ReadFile
|
||||
"net" // ResovleTCPAddr, ListenTCP, listener.Accept
|
||||
// conn.Read,Write
|
||||
"os" // Exit
|
||||
"strconv" // Itoa
|
||||
"os" // Exit, Create, os.Signal
|
||||
"os/signal" // Notify
|
||||
"strconv" // Itoa, Atoi
|
||||
"strings" // Split
|
||||
"syscall" // syscall.SIGINT,SIGTERM
|
||||
)
|
||||
|
||||
|
||||
@@ -111,10 +122,10 @@ func fread() string {
|
||||
// bugs where a blank item was introduced into qlist and calling
|
||||
// /la/ would produce a blank line on the client side that didn't
|
||||
// really exist
|
||||
//qfile = qfile[:len( qfile ) - 1]
|
||||
qfile = qfile[:len( qfile )]
|
||||
// cast bytes to string, split string over newline into array
|
||||
qlist = strings.Split( string( qfile ), "\n" )
|
||||
// deal with the trailing
|
||||
|
||||
return string( qfile ) // return file as string
|
||||
}
|
||||
|
||||
@@ -130,9 +141,9 @@ func writeFile( f string ) {
|
||||
}
|
||||
|
||||
|
||||
// handle connections ( new and improved )
|
||||
func handle( conn net.Conn ) {
|
||||
|
||||
// receive from connection, send to get processed, send out response
|
||||
func receive( conn net.Conn ) {
|
||||
|
||||
// create buffer to hold read message
|
||||
buffer := make( []byte, tsize )
|
||||
//var buffer [256]byte
|
||||
@@ -140,9 +151,38 @@ func handle( conn net.Conn ) {
|
||||
n, err := conn.Read( buffer[:] )
|
||||
checkN( err, conn ) // make sure read worked
|
||||
|
||||
// message anatomy
|
||||
// command@number[@user]
|
||||
// @ @ delimiter
|
||||
// command command, like list request or quote request
|
||||
// number sequence or quote number
|
||||
// user quote username if applicable, default if not give
|
||||
// add request message anatomy
|
||||
// command@quote[@user]
|
||||
// quote quote to be added
|
||||
// user quote username, default if not given
|
||||
|
||||
// cast message to string, take first n bytes, split over @
|
||||
command := strings.Split( string( buffer[:n] ), "@" )
|
||||
|
||||
if command[0] == "te" {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
|
||||
resp := handle( command )
|
||||
|
||||
// write response to client
|
||||
_, err = conn.Write( []byte( resp ) )
|
||||
checkN( err, conn ) // make sure write worked
|
||||
|
||||
receive( conn ) // call handle() again to get response from client
|
||||
}
|
||||
|
||||
|
||||
// handle connections ( new and improved )
|
||||
func handle( command []string ) string {
|
||||
|
||||
// declare response string
|
||||
var resp string
|
||||
switch command[0] { // switch/case over opcode
|
||||
@@ -155,7 +195,7 @@ func handle( conn net.Conn ) {
|
||||
case "qr": // /qr/, quote request
|
||||
// convert message argument to string to make sure it's a
|
||||
// valid number
|
||||
num, nerr := strconv.Atoi( command[1] )
|
||||
num, nerr := strconv.Atoi( command[0] )
|
||||
// nerr will not be nil if comm[1] is not a number
|
||||
if nerr != nil {
|
||||
// formulate an error message
|
||||
@@ -173,7 +213,7 @@ func handle( conn net.Conn ) {
|
||||
// why bad? num is -
|
||||
default:
|
||||
// good num, get quote, send off
|
||||
resp = "qa@" + qlist[num] // quote answer
|
||||
resp = "qa@" + qlist[num - 1] // quote answer
|
||||
}
|
||||
}
|
||||
case "lr": // /lr/, list request
|
||||
@@ -206,7 +246,7 @@ func handle( conn net.Conn ) {
|
||||
} else {
|
||||
// get slice from start index to end, concat
|
||||
// with response
|
||||
resp = resp + qfile[num:end]
|
||||
resp = resp + qfile[bytes:end]
|
||||
}
|
||||
}
|
||||
} else { // file is smaller than the tx size
|
||||
@@ -220,9 +260,115 @@ func handle( conn net.Conn ) {
|
||||
qfile = qfile + "\n" + command[1]
|
||||
writeFile( qfile )
|
||||
resp = "aa@success" // add answer
|
||||
case "cr":
|
||||
if len( command ) != 5 {
|
||||
return "ba@bad request"
|
||||
}
|
||||
|
||||
//mes1 := strings.Join( command[1:3], "@" )
|
||||
//mes1 := strings.Join( command[3:], "@" )
|
||||
_ = handle( command[1:3] )
|
||||
_ = handle( command[3:] )
|
||||
|
||||
resp = "e2@success"
|
||||
case "e1":
|
||||
resp = "e1@" // begin crafting response
|
||||
// file too big for single transmission
|
||||
// initial header size is 5, e1@1@, so counting that into
|
||||
// the transmission size, the file must be longer than 251
|
||||
// ( default ) bytes to reach this block of code
|
||||
if len( qfile ) > ( tsize - 5 ) {
|
||||
if command[1] == "init" { // first request
|
||||
// add message number, delim, and the first
|
||||
// transmittable bytes
|
||||
resp = resp + "0@" + qfile[:( tsize - 5 )]
|
||||
} else { // subsequent requests
|
||||
// convert byte count to int
|
||||
bytes, err := strconv.Atoi( command[1] )
|
||||
check( err ) // make sure convert worked
|
||||
// replace tx'd bytes and delim to new header
|
||||
resp = resp + command[1] + "@"
|
||||
rlen := len( resp ) // capture header length
|
||||
// slices are always of size "txsize - header
|
||||
// length", so find end byte
|
||||
end := bytes + ( tsize - rlen )
|
||||
// if end goes beyond the bounds of the list
|
||||
if end > len( qfile ) {
|
||||
// replace byte count with X to signal
|
||||
// final message, concat the rest of the file,
|
||||
// beginning with the start index
|
||||
resp = "e1@X@" + qfile[bytes:]
|
||||
} else {
|
||||
// get slice from start index to end, concat
|
||||
// with response
|
||||
resp = resp + qfile[bytes:end]
|
||||
}
|
||||
}
|
||||
} else { // file is smaller than the tx size
|
||||
// just concat entire list to send
|
||||
resp = resp + qfile // list answer
|
||||
}
|
||||
case "e2":
|
||||
// convert message argument to string to make sure it's a
|
||||
// valid number
|
||||
num, nerr := strconv.Atoi( command[1] )
|
||||
// nerr will not be nil if comm[1] is not a number
|
||||
if nerr != nil {
|
||||
// formulate an error message
|
||||
// TODO flesh this out more
|
||||
resp = "ba@qr@!" // bad answer
|
||||
} else { // comm[1] was a number, but...
|
||||
switch { // how do we know it's a valid number
|
||||
case num > len( qlist ):
|
||||
// bad answer in quote request
|
||||
resp = "ba@qr@>"
|
||||
// why bad? num is >
|
||||
case num < 0:
|
||||
// bad answer in quote request
|
||||
resp = "ba@qr@-"
|
||||
// why bad? num is -
|
||||
default:
|
||||
// good num, get quote, send off
|
||||
resp = "e2@" + command[1] + "@" + qlist[num - 1]
|
||||
}
|
||||
}
|
||||
case "r1": // /r1/, remove request 1
|
||||
// same as list, just send whole file
|
||||
resp = "r1@" + qfile // remove request 1
|
||||
resp = "r1@" // begin crafting response
|
||||
// file too big for single transmission
|
||||
// initial header size is 5, r1@1@, so counting that into
|
||||
// the transmission size, the file must be longer than 251
|
||||
// ( default ) bytes to reach this block of code
|
||||
if len( qfile ) > ( tsize - 5 ) {
|
||||
if command[1] == "init" { // first request
|
||||
// add message number, delim, and the first
|
||||
// transmittable bytes
|
||||
resp = resp + "0@" + qfile[:( tsize - 5 )]
|
||||
} else { // subsequent requests
|
||||
// convert byte count to int
|
||||
bytes, err := strconv.Atoi( command[1] )
|
||||
check( err ) // make sure convert worked
|
||||
// replace tx'd bytes and delim to new header
|
||||
resp = resp + command[1] + "@"
|
||||
rlen := len( resp ) // capture header length
|
||||
// slices are always of size "txsize - header
|
||||
// length", so find end byte
|
||||
end := bytes + ( tsize - rlen )
|
||||
// if end goes beyond the bounds of the list
|
||||
if end > len( qfile ) {
|
||||
// replace byte count with X to signal
|
||||
// final message, concat the rest of the file,
|
||||
// beginning with the start index
|
||||
resp = "r1@X@" + qfile[bytes:]
|
||||
} else {
|
||||
// get slice from start index to end, concat
|
||||
// with response
|
||||
resp = resp + qfile[bytes:end]
|
||||
}
|
||||
}
|
||||
} else { // file is smaller than the tx size
|
||||
// just concat entire list to send
|
||||
resp = resp + qfile // list answer
|
||||
}
|
||||
case "r2": // /r2/, remove request 2
|
||||
// convert message argument to string to make sure it's a
|
||||
// valid number
|
||||
@@ -268,42 +414,69 @@ func handle( conn net.Conn ) {
|
||||
writeFile( qfile ) // write back to file
|
||||
// let client know remove was successful
|
||||
resp = "r2@success"
|
||||
// TODO for buffer sizes ( -s ) below 10, this
|
||||
// will cause a soft error on the other end
|
||||
// if it's less than 10, 'success' gets cut
|
||||
// off and client doesn't register it as an
|
||||
// actual success
|
||||
}
|
||||
}
|
||||
case "te": // /te/, transaction end
|
||||
// TODO should I be sending something?
|
||||
// TODO is it better to close now or outside of handle()
|
||||
conn.Close() // close connection and leave
|
||||
return // return from handle(), finish connection
|
||||
//conn.Close() // close connection and leave
|
||||
return "" // return from handle(), finish connection
|
||||
default: // opcode not recognized
|
||||
// TODO there should be more being down, here, right?
|
||||
return // return from handle(), finish connection
|
||||
return "" // return from handle(), finish connection
|
||||
}
|
||||
|
||||
// write response to client
|
||||
_, err = conn.Write( []byte( resp ) )
|
||||
checkN( err, conn ) // make sure write worked
|
||||
|
||||
handle( conn ) // call handle() again to get response from client
|
||||
return resp
|
||||
|
||||
}
|
||||
|
||||
|
||||
// globals
|
||||
var qlist []string // list of quotes
|
||||
//var qlist = make( map[string][]string )
|
||||
var qfile string // file object
|
||||
var tsize int // size of transmission buffer
|
||||
|
||||
var VERS string // version
|
||||
|
||||
// main, create port and wait for connection
|
||||
func main() {
|
||||
|
||||
// create buffered channel for catching keyboard interrupt signal
|
||||
sigs := make( chan os.Signal, 1 )
|
||||
// set interrupt and terminate signals to notify channel
|
||||
signal.Notify( sigs, syscall.SIGINT, syscall.SIGTERM )
|
||||
|
||||
// flag vars
|
||||
var v bool // simple version
|
||||
var vv bool // verbose version
|
||||
|
||||
// flag for default transmission size
|
||||
flag.IntVar( &tsize, "s", 256, "transmission size ( bytes )" )
|
||||
flag.IntVar( &tsize, "s", 256, "transmission size ( bytes )" )
|
||||
flag.BoolVar( &v, "v", false, "display version and exit" )
|
||||
flag.BoolVar( &vv, "vv", false, "display version and about info and exit" )
|
||||
flag.Parse()
|
||||
|
||||
qfile = fread() // read quote file, init ( global ) list of quotes
|
||||
// FIXME get better versioning method
|
||||
VERS = "3.0.0"
|
||||
|
||||
if vv { // display info and exit
|
||||
fmt.Println( "ekho server v" + VERS )
|
||||
fmt.Println( "ekho is named after Echo the Oread" )
|
||||
fmt.Println( "in Greek mythology, Echo was cursed by Hera to only be able to say the last words spoken to her" )
|
||||
fmt.Println( "i found this to be quite fitting for a MOTD server" )
|
||||
return
|
||||
} else if v { // display info and exit
|
||||
fmt.Println( VERS )
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
qfile = fread() // read quote file, init ( global ) list of quotes
|
||||
service := ":1300" // create service on ip and port
|
||||
|
||||
// resolve ip address and port
|
||||
@@ -313,15 +486,19 @@ func main() {
|
||||
// create listener object from ip:port
|
||||
listener, err := net.ListenTCP( "tcp", addr )
|
||||
|
||||
go func() { // keyboard interrupt thread
|
||||
// print kill message
|
||||
fmt.Println( "press ctrl+C to stop..." )
|
||||
<- sigs // blocking read of signal from channel
|
||||
fmt.Println( "\nexiting" ) // exit message
|
||||
os.Exit( 0 ) // exeunt
|
||||
}()
|
||||
|
||||
for {
|
||||
// wait, create connection when found
|
||||
conn, err := listener.Accept()
|
||||
check( err ) // make sure connection works
|
||||
|
||||
go handle( conn ) // handle connection
|
||||
go receive( conn ) // handle connection
|
||||
}
|
||||
|
||||
os.Exit( 0 ) // exeunt
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user