2018-07-15 05:58:59 +02:00
|
|
|
//
|
|
|
|
// Copyright (c) 2018, Přemysl Janouch <p@janouch.name>
|
|
|
|
//
|
|
|
|
// Permission to use, copy, modify, and/or distribute this software for any
|
|
|
|
// purpose with or without fee is hereby granted.
|
|
|
|
//
|
|
|
|
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
|
|
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
|
|
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
|
|
|
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
|
|
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
|
|
|
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
|
|
|
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|
|
|
//
|
|
|
|
|
2018-07-15 10:45:12 +02:00
|
|
|
//
|
2018-07-15 05:58:59 +02:00
|
|
|
// This is an example TLS-autodetecting chat server.
|
|
|
|
//
|
2018-07-24 13:58:57 +02:00
|
|
|
// These clients are unable to properly shutdown the connection on their exit:
|
2018-07-15 05:58:59 +02:00
|
|
|
// telnet localhost 1234
|
|
|
|
// openssl s_client -connect localhost:1234
|
2018-07-15 10:45:12 +02:00
|
|
|
//
|
2018-07-24 13:58:57 +02:00
|
|
|
// While this one doesn't react to an EOF from the server:
|
|
|
|
// ncat -C localhost 1234
|
|
|
|
// ncat -C --ssl localhost 1234
|
|
|
|
//
|
2018-07-15 05:58:59 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"crypto/tls"
|
|
|
|
"flag"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
"syscall"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// --- Utilities ---------------------------------------------------------------
|
|
|
|
|
2018-07-15 10:45:12 +02:00
|
|
|
//
|
2018-07-15 05:58:59 +02:00
|
|
|
// Trivial SSL/TLS autodetection. The first block of data returned by Recvfrom
|
|
|
|
// must be at least three octets long for this to work reliably, but that should
|
|
|
|
// not pose a problem in practice. We might try waiting for them.
|
|
|
|
//
|
|
|
|
// SSL2: 1xxx xxxx | xxxx xxxx | <1>
|
|
|
|
// (message length) (client hello)
|
|
|
|
// SSL3/TLS: <22> | <3> | xxxx xxxx
|
|
|
|
// (handshake)| (protocol version)
|
|
|
|
//
|
2018-07-15 10:45:12 +02:00
|
|
|
func detectTLS(sysconn syscall.RawConn) (isTLS bool) {
|
2018-07-15 05:58:59 +02:00
|
|
|
sysconn.Read(func(fd uintptr) (done bool) {
|
|
|
|
var buf [3]byte
|
|
|
|
n, _, err := syscall.Recvfrom(int(fd), buf[:], syscall.MSG_PEEK)
|
|
|
|
switch {
|
|
|
|
case n == 3:
|
|
|
|
isTLS = buf[0]&0x80 != 0 && buf[2] == 1
|
|
|
|
fallthrough
|
|
|
|
case n == 2:
|
2018-08-06 21:39:40 +02:00
|
|
|
isTLS = isTLS || buf[0] == 22 && buf[1] == 3
|
2018-07-15 05:58:59 +02:00
|
|
|
case n == 1:
|
|
|
|
isTLS = buf[0] == 22
|
|
|
|
case err == syscall.EAGAIN:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
return isTLS
|
|
|
|
}
|
|
|
|
|
|
|
|
// --- Declarations ------------------------------------------------------------
|
|
|
|
|
2018-08-06 21:39:40 +02:00
|
|
|
type connCloseWriter interface {
|
2018-07-15 05:58:59 +02:00
|
|
|
net.Conn
|
|
|
|
CloseWrite() error
|
|
|
|
}
|
|
|
|
|
|
|
|
type client struct {
|
2018-08-06 21:39:40 +02:00
|
|
|
transport net.Conn // underlying connection
|
|
|
|
tls *tls.Conn // TLS, if detected
|
|
|
|
conn connCloseWriter // high-level connection
|
|
|
|
inQ []byte // unprocessed input
|
|
|
|
outQ []byte // unprocessed output
|
|
|
|
reading bool // whether a reading goroutine is running
|
|
|
|
writing bool // whether a writing goroutine is running
|
|
|
|
closing bool // whether we're closing the connection
|
|
|
|
killTimer *time.Timer // timeout
|
2018-07-15 10:45:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type preparedEvent struct {
|
|
|
|
client *client
|
|
|
|
host string // client's hostname or literal IP address
|
|
|
|
isTLS bool // the client seems to use TLS
|
2018-07-15 05:58:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type readEvent struct {
|
2018-07-15 10:45:12 +02:00
|
|
|
client *client
|
|
|
|
data []byte // new data from the client
|
|
|
|
err error // read error
|
2018-07-15 05:58:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type writeEvent struct {
|
2018-07-15 10:45:12 +02:00
|
|
|
client *client
|
|
|
|
written int // amount of bytes written
|
|
|
|
err error // write error
|
2018-07-15 05:58:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
2018-07-15 10:45:12 +02:00
|
|
|
sigs = make(chan os.Signal, 1)
|
|
|
|
conns = make(chan net.Conn)
|
|
|
|
prepared = make(chan preparedEvent)
|
|
|
|
reads = make(chan readEvent)
|
|
|
|
writes = make(chan writeEvent)
|
|
|
|
timeouts = make(chan *client)
|
2018-07-15 05:58:59 +02:00
|
|
|
|
|
|
|
tlsConf *tls.Config
|
|
|
|
clients = make(map[*client]bool)
|
|
|
|
listener net.Listener
|
|
|
|
inShutdown bool
|
|
|
|
shutdownTimer <-chan time.Time
|
|
|
|
)
|
|
|
|
|
|
|
|
// --- Server ------------------------------------------------------------------
|
|
|
|
|
|
|
|
// Broadcast to all /other/ clients (telnet-friendly, also in accordance to
|
|
|
|
// the plan of extending this to an IRCd).
|
|
|
|
func broadcast(line string, except *client) {
|
|
|
|
for c := range clients {
|
|
|
|
if c != except {
|
|
|
|
c.send(line)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-15 10:45:12 +02:00
|
|
|
// Initiate a clean shutdown of the whole daemon.
|
2018-07-15 05:58:59 +02:00
|
|
|
func initiateShutdown() {
|
|
|
|
log.Println("shutting down")
|
|
|
|
if err := listener.Close(); err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
|
|
|
for c := range clients {
|
2018-07-21 00:27:26 +02:00
|
|
|
c.closeLink()
|
2018-07-15 05:58:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
shutdownTimer = time.After(3 * time.Second)
|
|
|
|
inShutdown = true
|
|
|
|
}
|
|
|
|
|
2018-07-15 10:45:12 +02:00
|
|
|
// Forcefully tear down all connections.
|
2018-07-15 05:58:59 +02:00
|
|
|
func forceShutdown(reason string) {
|
2018-07-15 10:45:12 +02:00
|
|
|
if !inShutdown {
|
|
|
|
log.Fatalln("forceShutdown called without initiateShutdown")
|
|
|
|
}
|
|
|
|
|
2018-07-15 05:58:59 +02:00
|
|
|
log.Printf("forced shutdown (%s)\n", reason)
|
|
|
|
for c := range clients {
|
|
|
|
c.destroy()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// --- Client ------------------------------------------------------------------
|
|
|
|
|
|
|
|
func (c *client) send(line string) {
|
2018-07-24 13:58:57 +02:00
|
|
|
if c.conn != nil && !c.closing {
|
2018-07-15 05:58:59 +02:00
|
|
|
c.outQ = append(c.outQ, (line + "\r\n")...)
|
|
|
|
c.flushOutQ()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-15 10:45:12 +02:00
|
|
|
// Tear down the client connection, trying to do so in a graceful manner.
|
2018-07-21 00:27:26 +02:00
|
|
|
func (c *client) closeLink() {
|
2018-07-22 13:45:32 +02:00
|
|
|
if c.closing {
|
2018-07-15 05:58:59 +02:00
|
|
|
return
|
|
|
|
}
|
2018-07-15 10:45:12 +02:00
|
|
|
if c.conn == nil {
|
2018-07-15 05:58:59 +02:00
|
|
|
c.destroy()
|
2018-07-15 10:45:12 +02:00
|
|
|
return
|
2018-07-15 05:58:59 +02:00
|
|
|
}
|
2018-07-15 10:45:12 +02:00
|
|
|
|
2018-07-22 13:45:32 +02:00
|
|
|
// Since we send this goodbye, we don't need to call CloseWrite here.
|
2018-07-15 10:45:12 +02:00
|
|
|
c.send("Goodbye")
|
|
|
|
c.killTimer = time.AfterFunc(3*time.Second, func() {
|
|
|
|
timeouts <- c
|
|
|
|
})
|
|
|
|
|
2018-07-22 13:45:32 +02:00
|
|
|
c.closing = true
|
2018-07-15 05:58:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Close the connection and forget about the client.
|
|
|
|
func (c *client) destroy() {
|
|
|
|
// Try to send a "close notify" alert if the TLS object is ready,
|
|
|
|
// otherwise just tear down the transport.
|
2018-07-15 10:45:12 +02:00
|
|
|
if c.conn != nil {
|
2018-07-15 05:58:59 +02:00
|
|
|
_ = c.conn.Close()
|
|
|
|
} else {
|
|
|
|
_ = c.transport.Close()
|
|
|
|
}
|
|
|
|
|
2018-07-15 10:45:12 +02:00
|
|
|
// Clean up the goroutine, although a spurious event may still be sent.
|
|
|
|
if c.killTimer != nil {
|
|
|
|
c.killTimer.Stop()
|
|
|
|
}
|
|
|
|
|
2018-07-24 13:58:57 +02:00
|
|
|
log.Println("client destroyed")
|
2018-07-15 05:58:59 +02:00
|
|
|
delete(clients, c)
|
|
|
|
}
|
|
|
|
|
2018-07-15 10:45:12 +02:00
|
|
|
// Handle the results from initializing the client's connection.
|
2018-08-06 21:39:40 +02:00
|
|
|
func (c *client) onPrepared(isTLS bool) {
|
2018-07-15 10:45:12 +02:00
|
|
|
if isTLS {
|
|
|
|
c.tls = tls.Server(c.transport, tlsConf)
|
|
|
|
c.conn = c.tls
|
|
|
|
} else {
|
2018-08-06 21:39:40 +02:00
|
|
|
c.conn = c.transport.(connCloseWriter)
|
2018-07-15 10:45:12 +02:00
|
|
|
}
|
|
|
|
|
2018-07-22 14:55:15 +02:00
|
|
|
// TODO: If we've tried to send any data before now, we need to flushOutQ.
|
2018-07-15 10:45:12 +02:00
|
|
|
go read(c)
|
2018-07-22 13:45:32 +02:00
|
|
|
c.reading = true
|
2018-07-15 10:45:12 +02:00
|
|
|
}
|
|
|
|
|
2018-07-15 05:58:59 +02:00
|
|
|
// Handle the results from trying to read from the client connection.
|
|
|
|
func (c *client) onRead(data []byte, readErr error) {
|
2018-07-22 14:55:15 +02:00
|
|
|
if !c.reading {
|
|
|
|
// Abusing the flag to emulate CloseRead and skip over data, see below.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-07-15 05:58:59 +02:00
|
|
|
c.inQ = append(c.inQ, data...)
|
|
|
|
for {
|
|
|
|
advance, token, _ := bufio.ScanLines(c.inQ, false /* atEOF */)
|
|
|
|
if advance == 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
2018-07-15 10:45:12 +02:00
|
|
|
c.inQ = c.inQ[advance:]
|
2018-07-15 05:58:59 +02:00
|
|
|
line := string(token)
|
|
|
|
fmt.Println(line)
|
|
|
|
broadcast(line, c)
|
|
|
|
}
|
|
|
|
|
2018-07-22 13:45:32 +02:00
|
|
|
if readErr != nil {
|
|
|
|
c.reading = false
|
|
|
|
|
|
|
|
if readErr != io.EOF {
|
|
|
|
log.Println(readErr)
|
|
|
|
c.destroy()
|
|
|
|
} else if c.closing {
|
|
|
|
// Disregarding whether a clean shutdown has happened or not.
|
|
|
|
log.Println("client finished shutdown")
|
2018-07-15 10:45:12 +02:00
|
|
|
c.destroy()
|
|
|
|
} else {
|
2018-07-22 13:45:32 +02:00
|
|
|
log.Println("client EOF")
|
2018-07-21 00:27:26 +02:00
|
|
|
c.closeLink()
|
2018-07-15 10:45:12 +02:00
|
|
|
}
|
2018-07-22 14:55:15 +02:00
|
|
|
} else if len(c.inQ) > 8192 {
|
|
|
|
log.Println("client inQ overrun")
|
|
|
|
// TODO: Inform the client about inQ overrun in the farewell message.
|
|
|
|
c.closeLink()
|
|
|
|
|
|
|
|
// tls.Conn doesn't have the CloseRead method (and it needs to be able
|
|
|
|
// to read from the TCP connection even for writes, so there isn't much
|
|
|
|
// sense in expecting the implementation to do anything useful),
|
|
|
|
// otherwise we'd use it to block incoming packet data.
|
|
|
|
c.reading = false
|
2018-07-15 05:58:59 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-22 14:55:15 +02:00
|
|
|
// Spawn a goroutine to flush the outQ if possible and necessary.
|
2018-07-15 05:58:59 +02:00
|
|
|
func (c *client) flushOutQ() {
|
2018-07-22 13:45:32 +02:00
|
|
|
if !c.writing && c.conn != nil {
|
2018-07-15 05:58:59 +02:00
|
|
|
go write(c, c.outQ)
|
|
|
|
c.writing = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handle the results from trying to write to the client connection.
|
|
|
|
func (c *client) onWrite(written int, writeErr error) {
|
|
|
|
c.outQ = c.outQ[written:]
|
|
|
|
c.writing = false
|
|
|
|
|
|
|
|
if writeErr != nil {
|
|
|
|
log.Println(writeErr)
|
|
|
|
c.destroy()
|
|
|
|
} else if len(c.outQ) > 0 {
|
|
|
|
c.flushOutQ()
|
2018-07-22 13:45:32 +02:00
|
|
|
} else if c.closing {
|
|
|
|
if c.reading {
|
2018-07-15 10:45:12 +02:00
|
|
|
c.conn.CloseWrite()
|
|
|
|
} else {
|
|
|
|
c.destroy()
|
|
|
|
}
|
2018-07-15 05:58:59 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// --- Worker goroutines -------------------------------------------------------
|
|
|
|
|
|
|
|
func accept(ln net.Listener) {
|
|
|
|
for {
|
|
|
|
if conn, err := ln.Accept(); err != nil {
|
2018-07-15 10:45:12 +02:00
|
|
|
// TODO: Consider specific cases in error handling, some errors
|
|
|
|
// are transitional while others are fatal.
|
2018-07-15 05:58:59 +02:00
|
|
|
log.Println(err)
|
2018-07-15 10:45:12 +02:00
|
|
|
break
|
2018-07-15 05:58:59 +02:00
|
|
|
} else {
|
|
|
|
conns <- conn
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-15 10:45:12 +02:00
|
|
|
func prepare(client *client) {
|
|
|
|
conn := client.transport
|
|
|
|
host, _, err := net.SplitHostPort(conn.RemoteAddr().String())
|
|
|
|
if err != nil {
|
|
|
|
// In effect, we require TCP/UDP, as they have port numbers.
|
|
|
|
log.Fatalln(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// The Cgo resolver doesn't pthread_cancel getnameinfo threads, so not
|
|
|
|
// bothering with pointless contexts.
|
2018-07-23 05:33:50 +02:00
|
|
|
ch := make(chan string, 1)
|
2018-07-15 10:45:12 +02:00
|
|
|
go func() {
|
|
|
|
defer close(ch)
|
|
|
|
if names, err := net.LookupAddr(host); err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
} else {
|
|
|
|
ch <- names[0]
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
// While we can't cancel it, we still want to set a timeout on it.
|
|
|
|
select {
|
|
|
|
case <-time.After(5 * time.Second):
|
|
|
|
case resolved, ok := <-ch:
|
|
|
|
if ok {
|
|
|
|
host = resolved
|
|
|
|
}
|
|
|
|
}
|
2018-07-15 05:58:59 +02:00
|
|
|
|
2018-07-24 13:58:57 +02:00
|
|
|
// Note that in this demo application the autodetection prevents non-TLS
|
|
|
|
// clients from receiving any messages until they send something.
|
2018-07-15 10:45:12 +02:00
|
|
|
isTLS := false
|
|
|
|
if sysconn, err := conn.(syscall.Conn).SyscallConn(); err != nil {
|
2018-07-15 05:58:59 +02:00
|
|
|
// This is just for the TLS detection and doesn't need to be fatal.
|
|
|
|
log.Println(err)
|
2018-07-15 10:45:12 +02:00
|
|
|
} else {
|
|
|
|
isTLS = detectTLS(sysconn)
|
2018-07-15 05:58:59 +02:00
|
|
|
}
|
|
|
|
|
2018-07-24 13:58:57 +02:00
|
|
|
// FIXME: When the client sends no data, we still initialize its conn.
|
2018-07-15 10:45:12 +02:00
|
|
|
prepared <- preparedEvent{client, host, isTLS}
|
|
|
|
}
|
|
|
|
|
|
|
|
func read(client *client) {
|
2018-07-15 05:58:59 +02:00
|
|
|
// A new buffer is allocated each time we receive some bytes, because of
|
|
|
|
// thread-safety. Therefore the buffer shouldn't be too large, or we'd
|
|
|
|
// need to copy it each time into a precisely sized new buffer.
|
|
|
|
var err error
|
|
|
|
for err == nil {
|
|
|
|
var (
|
|
|
|
buf [512]byte
|
|
|
|
n int
|
|
|
|
)
|
|
|
|
n, err = client.conn.Read(buf[:])
|
|
|
|
reads <- readEvent{client, buf[:n], err}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Flush outQ, which is passed by parameter so that there are no data races.
|
|
|
|
func write(client *client, data []byte) {
|
|
|
|
// We just write as much as we can, the main goroutine does the looping.
|
|
|
|
n, err := client.conn.Write(data)
|
|
|
|
writes <- writeEvent{client, n, err}
|
|
|
|
}
|
|
|
|
|
|
|
|
// --- Main --------------------------------------------------------------------
|
|
|
|
|
|
|
|
func processOneEvent() {
|
|
|
|
select {
|
|
|
|
case <-sigs:
|
|
|
|
if inShutdown {
|
|
|
|
forceShutdown("requested by user")
|
|
|
|
} else {
|
|
|
|
initiateShutdown()
|
|
|
|
}
|
|
|
|
|
|
|
|
case <-shutdownTimer:
|
|
|
|
forceShutdown("timeout")
|
|
|
|
|
|
|
|
case conn := <-conns:
|
|
|
|
log.Println("accepted client connection")
|
|
|
|
c := &client{transport: conn}
|
|
|
|
clients[c] = true
|
2018-07-15 10:45:12 +02:00
|
|
|
go prepare(c)
|
|
|
|
|
|
|
|
case ev := <-prepared:
|
2018-08-06 21:39:40 +02:00
|
|
|
log.Println("client is ready, resolved to", ev.host)
|
2018-07-15 10:45:12 +02:00
|
|
|
if _, ok := clients[ev.client]; ok {
|
2018-08-06 21:39:40 +02:00
|
|
|
ev.client.onPrepared(ev.isTLS)
|
2018-07-15 10:45:12 +02:00
|
|
|
}
|
2018-07-15 05:58:59 +02:00
|
|
|
|
|
|
|
case ev := <-reads:
|
|
|
|
log.Println("received data from client")
|
|
|
|
if _, ok := clients[ev.client]; ok {
|
|
|
|
ev.client.onRead(ev.data, ev.err)
|
|
|
|
}
|
|
|
|
|
|
|
|
case ev := <-writes:
|
|
|
|
log.Println("sent data to client")
|
|
|
|
if _, ok := clients[ev.client]; ok {
|
|
|
|
ev.client.onWrite(ev.written, ev.err)
|
|
|
|
}
|
2018-07-15 10:45:12 +02:00
|
|
|
|
|
|
|
case c := <-timeouts:
|
|
|
|
if _, ok := clients[c]; ok {
|
|
|
|
log.Println("client timeouted")
|
|
|
|
c.destroy()
|
|
|
|
}
|
2018-07-15 05:58:59 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
// Just deal with unexpected flags, we don't use any ourselves.
|
|
|
|
flag.Parse()
|
|
|
|
|
|
|
|
if len(flag.Args()) != 3 {
|
|
|
|
log.Fatalf("usage: %s KEY CERT ADDRESS\n", os.Args[0])
|
|
|
|
}
|
|
|
|
|
|
|
|
cert, err := tls.LoadX509KeyPair(flag.Arg(1), flag.Arg(0))
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalln(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
tlsConf = &tls.Config{Certificates: []tls.Certificate{cert}}
|
|
|
|
listener, err = net.Listen("tcp", flag.Arg(2))
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalln(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
go accept(listener)
|
|
|
|
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
|
|
|
|
|
|
|
|
for !inShutdown || len(clients) > 0 {
|
|
|
|
processOneEvent()
|
|
|
|
}
|
|
|
|
}
|