50 Commits

Author SHA1 Message Date
Will Storey
463ea8c92b v1.11.0 2019-01-01 12:49:54 -08:00
Will Storey
13acc33937 doc: Clarify release doc 2019-01-01 12:49:42 -08:00
Will Storey
21ae068f0a Build releases on arm too 2019-01-01 12:49:24 -08:00
Will Storey
fb17b8d925 travis: Drop gometalinter until it works with modules 2019-01-01 12:41:40 -08:00
Will Storey
d700275f6d doc: Add TODOs 2019-01-01 12:36:31 -08:00
Will Storey
899174b637 Use modules 2019-01-01 12:34:30 -08:00
Will Storey
bf3111099c travis: Test on newest Go 1.x 2019-01-01 12:29:15 -08:00
Will Storey
686f90d09b README: Simplify features and talk about the lack of them 2019-01-01 12:29:15 -08:00
Will Storey
b711f684bb README: Add design goal to blurb 2019-01-01 12:29:15 -08:00
Will Storey
c3f2a30bcc README: Simplify feature list 2019-01-01 12:29:15 -08:00
Will Storey
b72b347ad7 README: Move name section down 2019-01-01 12:29:15 -08:00
Will Storey
0c518ee29f README: Simplify installation section 2019-01-01 12:29:15 -08:00
Will Storey
2515bf86dc README: Simplify config file section 2019-01-01 12:29:15 -08:00
Will Storey
bd474d41ab README: Simplify TLS instructions
Drop mention of CN since it's deprecated.
2019-01-01 12:29:15 -08:00
Will Storey
64d12b4b64 Reword changelog entry 2019-01-01 12:28:46 -08:00
Will Storey
0668830673 Rewrite network setup section in README 2018-08-19 17:28:21 -07:00
Will Storey
c546b898dd Add a TODO 2018-08-19 10:06:56 -07:00
Will Storey
79fdad75d7 Fix flakey test 2018-08-19 09:38:35 -07:00
Will Storey
77247c68e2 Remove nested list from README 2018-08-19 09:33:11 -07:00
Will Storey
c8aa82fef0 Try to fix nested list in README 2018-08-19 09:30:08 -07:00
Will Storey
5e4d23b129 Fix version number in changelog 2018-08-19 09:30:00 -07:00
Will Storey
f404abae1a Clean up TODO a bit 2018-08-19 09:23:31 -07:00
Will Storey
fcd7ce72e7 Move dev README to doc 2018-08-19 09:20:27 -07:00
Will Storey
1a755c6a69 Do not automatically rehash
I changed my mind!
2018-08-19 09:19:54 -07:00
Will Storey
45654064b3 Improve TLS certificate instructions in README 2018-08-19 09:18:39 -07:00
Will Storey
225d255340 Include conf directory in release 2018-08-18 13:57:51 -07:00
Will Storey
b942a8ffbd Update setup instructions to mention releases 2018-08-18 13:56:35 -07:00
Will Storey
8ace47acf8 Tweak release instructions 2018-08-18 13:55:07 -07:00
Will Storey
5d28885283 1.10.0 2018-08-18 13:45:27 -07:00
Will Storey
4e482eb0a6 Set up goreleaser 2018-08-18 13:45:24 -07:00
Will Storey
8137e42749 Add readme section about TLS certificates 2018-08-18 13:39:49 -07:00
Will Storey
29f9e003e2 Validate TLS certificates on outbound connections 2018-08-18 13:39:46 -07:00
Will Storey
35e884e784 Rehash config automatically once a week 2018-08-18 13:24:55 -07:00
Will Storey
8f354f9899 Reload certificate and key at rehash time 2018-08-18 13:21:09 -07:00
Will Storey
a4ecf9673c Remove comment about tls.Config MinVersion 2018-08-18 13:21:09 -07:00
Will Storey
5afcc1b961 Load certificate differently
This will allow us to reload it when we rehash.
2018-08-18 13:21:06 -07:00
Will Storey
300f4bd5cd Accept more lints 2018-08-18 11:59:33 -07:00
Will Storey
6fdc314b51 Rename tests only directory 2018-08-18 11:59:07 -07:00
Will Storey
6ae9f51e32 Add to TODO 2018-08-18 11:51:15 -07:00
Will Storey
6a142fc094 Clean up README 2018-08-18 11:51:09 -07:00
Will Storey
49b8e2d874 Delete unused functions 2018-08-18 11:40:26 -07:00
Will Storey
96821bbab9 Remove unnecessary conversions 2018-08-18 11:40:26 -07:00
Will Storey
d066174dae Accept some lints 2018-08-18 11:40:26 -07:00
Will Storey
3eb2bebcc7 Use time.Since where possible 2018-08-18 11:40:26 -07:00
Will Storey
2b20607015 Break out of a loop as intended 2018-08-18 11:40:26 -07:00
Will Storey
b638a5fcfe Explicitly ignore some errors 2018-08-18 11:40:26 -07:00
Will Storey
dede2d2f03 Wrap an error 2018-08-18 11:40:23 -07:00
Will Storey
bd2f4b8a78 Run gometalinter in Travis 2018-08-18 11:37:24 -07:00
Will Storey
48fafe8191 tests: Get linking working again
It broke when I added stricter SID checks during linking.
2018-08-18 11:24:20 -07:00
Will Storey
30e944356c Add boxcat files (some renamed) 2018-08-14 18:19:26 -07:00
41 changed files with 1079 additions and 3096 deletions

8
.gometalinter.json Normal file
View File

@@ -0,0 +1,8 @@
{
"Disable": [
"goconst",
"gocyclo",
"vetshadow"
],
"Vendor": true
}

14
.goreleaser.yml Normal file
View File

@@ -0,0 +1,14 @@
builds:
-
goos:
- linux
goarch:
- amd64
- arm
archive:
wrap_in_directory: true
files:
- CHANGELOG.md
- conf/*
- COPYING
- README.md

View File

@@ -1,3 +1,5 @@
language: go
go:
- 1.9.x
- "1.x"
script:
- go test -v ./...

View File

@@ -1,4 +1,19 @@
# 1.9.0
# 1.11.0 (2019-01-01)
* No longer automatically rehash once a week. I changed my mind about this!
# 1.10.0 (2018-08-18)
* Rehashing now reloads the TLS certificate and key.
* Rehashing now automatically happens once a week. This is so we load new
certificates.
* Require valid TLS certificates on outbound TLS connections. This means
servers we connect to must have valid certificates that match the name we
connect to them as.
# 1.9.0 (2018-07-28)
* Started tracking changes in a changelog.
* If a message is invalid, send a notice to opers about it rather than just

8
Gopkg.lock generated
View File

@@ -13,9 +13,15 @@
packages = ["."]
revision = "f421bdb90dcc93b6e3724a50b1f2b360a6d72a44"
[[projects]]
name = "github.com/pkg/errors"
packages = ["."]
revision = "645ef00459ed84a119197bfb8d8205042c6df63d"
version = "v0.8.0"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "3bb124c1ad76d31bb309c200a3eea258673d458d10d51667a1dbd61e915e624c"
inputs-digest = "9cb9d754ea09adacef36be72eb569ca57e813554c871a875647e9d24bf96e360"
solver-name = "gps-cdcl"
solver-version = 1

View File

@@ -28,3 +28,7 @@
[[constraint]]
branch = "master"
name = "github.com/horgh/irc"
[[constraint]]
name = "github.com/pkg/errors"
version = "0.8.0"

View File

@@ -1,3 +0,0 @@
# Releasing
* Bump values in `version.go`
* `git tag -a xxx <commit>`

View File

@@ -5,84 +5,68 @@ Status](https://travis-ci.org/horgh/catbox.svg)](https://travis-ci.org/horgh/cat
[![Go Report
Card](https://goreportcard.com/badge/github.com/horgh/catbox)](https://goreportcard.com/report/github.com/horgh/catbox)
This is a minimal IRC daemon. I run a small network using
[ircd-ratbox](http://ratbox.org/) and had the idea to create an IRC server
capable of linking to it and eventually replacing it. My goal is to have a
minimal server that will meet this network's needs.
# Status
catbox is capable of linking to itself and to ircd-ratbox servers. It is in
active use on my network.
# Why the name?
My domain name is summercat.com, cats love boxes, and a tribute to
ircd-ratbox.
catbox is an IRC server with a focus on being small and understandable. The
goal is security.
# Features
* Server to server communication using the TS6 protocol. In addition to
being able to link to other catbox servers, it can link with other TS6
servers such as ircd-ratbox.
* Most basic IRC commands and features are present.
* Channel modes: +n, +s, +o.
* User modes: +i, +o, +C.
* Global IRC operators.
* Network wide operator communication with WALLOPS.
* Private (WHOIS shows no channels, LIST isn't supported).
* Server connections are based on hosts rather than IPs. This means servers
can have dynamic IPs.
* Network wide connection notices sent to operators.
* Flood protection.
* K: line style connection banning.
* Server to server linking
* IRC operators
* Private (WHOIS shows no channels, LIST isn't supported)
* Flood protection
* K: line style connection banning
* TLS
catbox implements enough of [RFC 1459](https://tools.ietf.org/html/rfc1459)
to be recognisable as IRC and be minimally functional. I likely won't add
much more and don't intend it to be complete. If I don't think something is
required it likely won't be here.
# Setup
1. Build the server. You need a working [Go
compiler](https://golang.org/dl/). An easy way to do this is to run `go
get -u github.com/horgh/catbox`.
2. Configure it. This is done through configuration files. Examples are in
the `conf` directory. Copy and edit them. All settings are optional and
have defaults.
3. Start the daemon: `catbox -conf catbox.conf`
# Installation
1. Download catbox from the Releases tab on GitHub, or build from source
(`go build`).
2. Configure catbox through config files. There are example configs in the
`conf` directory. All settings are optional and have defaults.
3. Run it, e.g. `./catbox -conf catbox.conf`. I typically run catbox
inside tmux using [this program](bin/tmux-run.sh).
# Configuration
## catbox.conf
This file holds global settings for the server.
You'll probably want to change `listen-host`, `listen-port`, and
`server-name` at minimum.
Global server settings.
## opers.conf
This file defines IRC operators. A user can become an operator by using the
`OPER` command with a username and password combination listed in this file.
IRC operators.
## servers.conf
This file defines servers to link to and accept links from.
The servers to link with.
## users.conf
This file defines privileges and hostname spoofs for users. The only
privilege right now is flood exemption.
Privileges and hostname spoofs for users.
The only privilege right now is flood exemption.
# TLS
If you want to listen on a TLS port, you must have a certificate and key
available.
## TLS
A setup for a network might look like this:
To generate a self-signed certificate for TLS:
* Give each server a certificate with 2 SANs: Its own hostname, e.g.
server1.example.com, and the network hostname, e.g. irc.example.com.
* Set up irc.example.com with DNS round-robin listing each server's IP.
* List each server by its own hostname in servers.conf.
openssl req -newkey rsa:4096 -x509 -keyout key.pem -out certificate.pem -days 3650 -nodes
Clients connect to the network hostname and verify against it. Servers
connect to each other by server hostname and verify against it.
# Tests
In addition to the unit level tests here, there are some integration tests
in [another repository](https://github.com/horgh/boxcat).
# Why the name?
My domain name is summercat.com, cats love boxes, and a tribute to
ircd-ratbox, the IRC daemon I used in the past.
# Logo

View File

@@ -39,7 +39,7 @@ func getArgs() *Args {
}
func printUsage(err error) {
fmt.Fprintf(os.Stderr, "%s\n", err)
fmt.Fprintf(os.Stderr, "Usage: %s <arguments>\n", os.Args[0])
_, _ = fmt.Fprintf(os.Stderr, "%s\n", err) // nolint: gas
_, _ = fmt.Fprintf(os.Stderr, "Usage: %s <arguments>\n", os.Args[0]) // nolint: gas
flag.PrintDefaults()
}

9
doc/README.dev.md Normal file
View File

@@ -0,0 +1,9 @@
# Releasing
* Bump values in `version.go`
* Update `CHANGELOG.md`
* Commit
* `git push`
* `git tag -a vx.y.z -m vx.y.z`
* `export GITHUB_TOKEN=tokenhere`
* `goreleaser`
* Don't need to push tags I believe, goreleaser does it.

View File

@@ -1,27 +1,35 @@
# TODO
## Higher priority
* Wake up less
* Back off on connection failures
* Convert tests to use stretchr/testify.
* Show IPs to opers in WHOIS with 378 numeric.
* Op desync issue - should be de-opped if we have an op and link to a
server where the channel already exists. Can see not-op on one side and
op on the catbox side. I think this is because of us clearing modes on
SJOIN commands, but those cleared modes only get sent locally.
* PASS command for users to authenticate.
* Authenticated user should show in WHOIS with 330 numeric.
* Automatically spoof people's hosts.
* WHOWAS.
* Many log calls should probably go to opers. Right now they will probably
always be missed.
* Additional tests.
* Loading config should error if there is an unknown option
* Channel mode +i
## Uncategorized/unprioritized
* Command to dump out entire state. Servers, channels, nicks, modes, etc.
This could be used for monitoring that every server is in sync.
* Switch config to TOML
* Loading config should error if there is an unknown option
* Make canonicalizeNick and canonicalizeChannel return error if the names
are invalid? Right now it is a bit error prone because we can
canonicalize invalid names.
* Consider combining cleanup user logic in server's killCommand() with
cleanupKilledUser()
* Consolidate repeated topic setting logic (user TOPIC, server TOPIC, TB)
* Additional automated testing. More unit tests here and more integration
tests in the boxcat repository.
* Add command to dump out config (the current catbox config as seen from
the config file). Partly this will be useful because not everything gets
reloaded on rehash.
@@ -42,7 +50,7 @@
## RFC
* Channel modes: +v/+b/+i/+k/etc
* Channel modes: +v/+b/+k/etc
* KICK
@@ -61,11 +69,8 @@
## Non-standard
* Upgrade in place (is this possible with TLS connections without
disconnecting them?)
* Server console.
* Upgrade without losing connections
* Inform clients when someone whois's them.
* Inform clients when someone WHOIS's them.
* Exchange K:Lines during server burst
* Persistent K:Lines (currently they are in memory only)
@@ -80,3 +85,6 @@
* Daemonize.
* There is no support in Go for this right now.
* Using init system seems sufficient
* Upgrade in place without losing connections
* Not really feasible with current TLS library as connection state can't
be kept.

7
go.mod Normal file
View File

@@ -0,0 +1,7 @@
module github.com/horgh/catbox
require (
github.com/horgh/config v0.0.0-20190101202014-d9e8eabe6dbb
github.com/horgh/irc v0.0.0-20190101203129-f09ebee6408d
github.com/pkg/errors v0.8.0
)

13
go.sum Normal file
View File

@@ -0,0 +1,13 @@
github.com/horgh/config v0.0.0-20180303191532-3d1f920eb228 h1:R302KZFIBabAYgFZ0hgqRTeCF43Lm5rir+UnJYW3idQ=
github.com/horgh/config v0.0.0-20180303191532-3d1f920eb228/go.mod h1:DSwQKBmwAzGuDhYajjeJshx5PCPCJfSZJXtbV+8/nck=
github.com/horgh/config v0.0.0-20190101202014-d9e8eabe6dbb h1:u6pj1d0h6XSjJ84iixIMvSZT1fbLC1g4qqkV54EMOfo=
github.com/horgh/config v0.0.0-20190101202014-d9e8eabe6dbb/go.mod h1:DSwQKBmwAzGuDhYajjeJshx5PCPCJfSZJXtbV+8/nck=
github.com/horgh/irc v0.0.0-20180101050313-f421bdb90dcc h1:FXH8Jqdcz9BbR94qHrCVGA5FhbcWNC+HpIXYwVgOc2I=
github.com/horgh/irc v0.0.0-20180101050313-f421bdb90dcc/go.mod h1:UqEB9NVUSZzN4ESuQX3yEvi80Mgg2O4kttl8oU9+nds=
github.com/horgh/irc v0.0.0-20190101203129-f09ebee6408d h1:ANDjU4bIeLO80xssAxig8qftG6ohyg08IqsIPnKqafg=
github.com/horgh/irc v0.0.0-20190101203129-f09ebee6408d/go.mod h1:JLhFcwXOnpvhMer1MERfJuFIoJnADayDWe0VkMN3LP4=
github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View File

@@ -15,7 +15,7 @@ import (
// LocalClient holds state about a local connection.
// All connections are in this state until they register as either a user client
// or as a server.
type LocalClient struct {
type LocalClient struct { // nolint: maligned
// Conn is the TCP connection to the client.
Conn Conn

View File

@@ -676,7 +676,7 @@ func (s *LocalServer) uidCommand(m irc.Message) {
sid := TS6SID(m.Prefix)
// Do we know the server the message originates on?
usersServer, exists := s.Catbox.Servers[TS6SID(sid)]
usersServer, exists := s.Catbox.Servers[sid]
if !exists {
s.quit(fmt.Sprintf("UID message from unknown server %s", sid))
return
@@ -763,7 +763,7 @@ func (s *LocalServer) uidCommand(m irc.Message) {
u := &User{
DisplayNick: displayNick,
HopCount: int(hopCount),
NickTS: int64(nickTS),
NickTS: nickTS,
Modes: umodes,
Username: username,
Hostname: hostname,

View File

@@ -181,7 +181,7 @@ func (u *LocalUser) join(channelName string) {
// First build the portion that is common to every NAMREPLY so we can get
// its length.
namMessage := irc.Message{
Prefix: string(u.Catbox.Config.ServerName),
Prefix: u.Catbox.Config.ServerName,
Command: "353",
// Last parameter is where nicks go. We'll have " :" since it's blank
// right now (when we encode to determine base size).

81
main.go
View File

@@ -15,6 +15,7 @@ import (
"time"
"github.com/horgh/irc"
"github.com/pkg/errors"
)
// Catbox holds the state for this local server.
@@ -85,7 +86,9 @@ type Catbox struct {
ConnectionCount int
// Our TLS configuration.
TLSConfig *tls.Config
TLSConfig *tls.Config
Certificate *tls.Certificate
CertificateMutex *sync.RWMutex
// TCP plaintext and TLS listeners.
Listener net.Listener
@@ -149,9 +152,9 @@ type Event struct {
// EventType is a type of event we can tell the server about.
type EventType int
const (
const ( // nolint: deadcode
// NullEvent is a default event. This means the event was not populated.
NullEvent EventType = iota
NullEvent EventType = iota // nolint: megacheck
// NewClientEvent means a new client connected.
NewClientEvent
@@ -221,7 +224,7 @@ func main() {
if cb.Restart {
log.Printf("Shutdown completed. Restarting...")
if err := syscall.Exec(
if err := syscall.Exec( // nolint: gas
binPath,
[]string{
binPath,
@@ -267,34 +270,59 @@ func newCatbox(configFile string) (*Catbox, error) {
if cb.Config.ListenPortTLS != "-1" || cb.Config.CertificateFile != "" ||
cb.Config.KeyFile != "" {
cert, err := tls.LoadX509KeyPair(cb.Config.CertificateFile,
cb.Config.KeyFile)
if err != nil {
return nil, fmt.Errorf("unable to load certificate/key: %s", err)
}
cb.CertificateMutex = &sync.RWMutex{}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
GetCertificate: cb.getCertificate,
PreferServerCipherSuites: true,
SessionTicketsDisabled: true,
// Unfortunately it is usual to use self signed certificates with IRC. We
// need this to connect to such servers.
InsecureSkipVerify: true,
// It would be nice to be able to be more restrictive on TLS version and
// ciphers, but in practice many clients do not support the strictest.
// It would be nice to be able to be more restrictive on ciphers, but in
// practice many clients do not support the strictest.
//CipherSuites: []uint16{
// tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
// tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
//},
//MinVersion: tls.VersionTLS12,
}
cb.TLSConfig = tlsConfig
if err := cb.loadCertificate(); err != nil {
return nil, err
}
}
return &cb, nil
}
// Return the current certificate.
//
// We use tls.Config's GetCertificate so that we can swap out the certificate
// while running without having to recreate the net.Listener.
func (cb *Catbox) getCertificate(
hello *tls.ClientHelloInfo,
) (*tls.Certificate, error) {
cb.CertificateMutex.RLock()
defer cb.CertificateMutex.RUnlock()
if cb.Certificate == nil {
return nil, errors.New("certificate not set")
}
return cb.Certificate, nil
}
// Load the certificate and key from files.
func (cb *Catbox) loadCertificate() error {
if cb.Config.CertificateFile == "" || cb.Config.KeyFile == "" {
return nil
}
cert, err := tls.LoadX509KeyPair(cb.Config.CertificateFile, cb.Config.KeyFile)
if err != nil {
return errors.Wrap(err, "error loading certificate/key")
}
cb.CertificateMutex.Lock()
defer cb.CertificateMutex.Unlock()
cb.Certificate = &cert
return nil
}
// start starts up the server.
//
// We open the TCP port, start goroutines, and then receive messages on our
@@ -614,7 +642,7 @@ func (cb *Catbox) introduceClient(conn net.Conn) {
tlsVersion, tlsCipherSuite, err := client.getTLSState()
if err != nil {
log.Printf("Client %s: %s", client, err)
_ = conn.Close()
_ = conn.Close() // nolint: gosec
return
}
@@ -998,7 +1026,7 @@ func (cb *Catbox) connectToServer(linkInfo *ServerDefinition) {
tlsVersion, tlsCipherSuite, err := client.getTLSState()
if err != nil {
log.Printf("Disconnecting from server %s: %s", linkInfo.Name, err)
_ = conn.Close()
_ = conn.Close() // nolint: gosec
return
}
@@ -1006,7 +1034,7 @@ func (cb *Catbox) connectToServer(linkInfo *ServerDefinition) {
cb.noticeOpers(fmt.Sprintf(
"Disconnecting from %s because of TLS version: %s", linkInfo.Name,
tlsVersion))
_ = conn.Close()
_ = conn.Close() // nolint: gosec
return
}
@@ -1346,7 +1374,7 @@ func (cb *Catbox) createWHOISResponse(user, replyUser *User,
// 317 RPL_WHOISIDLE. Only if local.
if user.isLocal() {
idleDuration := time.Now().Sub(user.LocalUser.LastMessageTime)
idleDuration := time.Since(user.LocalUser.LastMessageTime)
idleSeconds := int(idleDuration.Seconds())
msgs = append(msgs, irc.Message{
@@ -1468,8 +1496,13 @@ func (cb *Catbox) rehash(byUser *User) {
// ListenHost
// ListenPort
// ListenPortTLS
// CertificateFile
// KeyFile
cb.Config.CertificateFile = cfg.CertificateFile
cb.Config.KeyFile = cfg.KeyFile
if err := cb.loadCertificate(); err != nil {
cb.noticeOpers(fmt.Sprintf("Error loading certificate/key: %s", err))
log.Printf("%+v", err)
}
// Changing these may require relinking servers as they are part of the
// link handshake:

5
net.go
View File

@@ -6,6 +6,8 @@ import (
"log"
"net"
"time"
"github.com/pkg/errors"
)
// Conn is a connection to a client/server
@@ -52,7 +54,8 @@ func (c Conn) Read() (string, error) {
line, err := c.rw.ReadString('\n')
if err != nil {
return line, err // May be something read even with error.
// There may be something read even with error.
return line, errors.Wrap(err, "error reading")
}
return line, nil

View File

@@ -45,10 +45,6 @@ func (s *Server) isLocal() bool {
return s.LocalServer != nil
}
func (s *Server) isRemote() bool {
return !s.isLocal()
}
// Turn our capabilities into a single space separated string.
func (s *Server) capabsString() string {
str := ""

304
tests/catbox_test.go Normal file
View File

@@ -0,0 +1,304 @@
package tests
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
// Catbox holds information about a harnessed catbox.
type Catbox struct {
Name string
SID string
Port uint16
Stderr io.ReadCloser
Stdout io.ReadCloser
Command *exec.Cmd
WaitGroup *sync.WaitGroup
ConfigDir string
LogChan <-chan string
}
const catboxDir = ".."
func harnessCatbox(
name,
sid string,
) (*Catbox, error) {
if err := buildCatbox(); err != nil {
return nil, fmt.Errorf("error building catbox: %s", err)
}
catbox, err := startCatbox(name, sid)
if err != nil {
return nil, fmt.Errorf("error starting catbox: %s", err)
}
var wg sync.WaitGroup
logChan := make(chan string, 1024)
wg.Add(1)
go logReader(&wg, fmt.Sprintf("%s stderr", name), catbox.Stderr, logChan)
wg.Add(1)
go logReader(&wg, fmt.Sprintf("%s stdout", name), catbox.Stdout, logChan)
wg.Add(1)
go func() {
defer wg.Done()
if err := catbox.Command.Wait(); err != nil {
log.Printf("catbox exited: %s", err)
}
}()
catbox.WaitGroup = &wg
catbox.LogChan = logChan
// It is important to wait for catbox to fully start. If we don't, then
// certain things we do in tests will not work well. For example, trying to
// reload the conf by sending a SIGHUP will kill the process.
startedRE := regexp.MustCompile(
`^\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} catbox started$`)
if !waitForLog(logChan, startedRE) {
catbox.stop()
return nil, fmt.Errorf("error waiting for catbox to start")
}
return catbox, nil
}
var builtCatbox bool
func buildCatbox() error {
if builtCatbox {
return nil
}
cmd := exec.Command("go", "build")
cmd.Dir = catboxDir
log.Printf("Running %s in [%s]...", cmd.Args, cmd.Dir)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error building catbox: %s: %s", err, output)
}
builtCatbox = true
return nil
}
func startCatbox(
name,
sid string,
) (*Catbox, error) {
tmpDir, err := ioutil.TempDir("", "boxcat-")
if err != nil {
return nil, fmt.Errorf("error retrieving a temporary directory: %s", err)
}
catboxConf := filepath.Join(tmpDir, "catbox.conf")
listener, port, err := getRandomPort()
if err != nil {
_ = os.RemoveAll(tmpDir)
return nil, fmt.Errorf("error opening random port: %s", err)
}
catbox, err := runCatbox(catboxConf, listener, port, name, sid)
if err != nil {
_ = os.RemoveAll(tmpDir)
_ = listener.Close()
return nil, fmt.Errorf("error running catbox: %s", err)
}
catbox.ConfigDir = tmpDir
return catbox, nil
}
func getRandomPort() (net.Listener, uint16, error) {
ln, err := net.Listen("tcp4", "127.0.0.1:")
if err != nil {
return nil, 0, fmt.Errorf("error opening a random port: %s", err)
}
addr := ln.Addr().String()
colonIndex := strings.Index(addr, ":")
portString := addr[colonIndex+1:]
port, err := strconv.ParseUint(portString, 10, 16)
if err != nil {
_ = ln.Close()
return nil, 0, fmt.Errorf("error parsing port: %s", err)
}
return ln, uint16(port), nil
}
func runCatbox(
conf string,
ln net.Listener,
port uint16,
name,
sid string,
) (*Catbox, error) {
var extra string
if err := writeConf(conf, name, sid, extra); err != nil {
return nil, err
}
cmd := exec.Command("./catbox",
"-conf", conf,
"-listen-fd", "3",
)
cmd.Dir = catboxDir
f, err := ln.(*net.TCPListener).File()
if err != nil {
return nil, fmt.Errorf("error retrieving listener file: %s", err)
}
cmd.ExtraFiles = []*os.File{f}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, fmt.Errorf("error retrieving stderr pipe: %s", err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
_ = stderr.Close()
return nil, fmt.Errorf("error retrieving stdout pipe: %s", err)
}
if err := cmd.Start(); err != nil {
_ = stderr.Close()
_ = stdout.Close()
return nil, fmt.Errorf("error starting: %s", err)
}
return &Catbox{
Name: name,
Port: port,
Command: cmd,
Stderr: stderr,
Stdout: stdout,
}, nil
}
func writeConf(
filename,
serverName,
sid,
extra string,
) error {
// -1 because we pass in fd.
buf := fmt.Sprintf(`
listen-port = %d
server-name = %s
ts6-sid = %s
connect-attempt-time = 100ms
%s
`,
-1,
serverName,
sid,
extra,
)
if err := ioutil.WriteFile(filename, []byte(buf), 0644); err != nil {
return fmt.Errorf("error writing conf: %s: %s", serverName, err)
}
return nil
}
func logReader(
wg *sync.WaitGroup,
prefix string,
r io.Reader,
ch chan<- string,
) {
defer wg.Done()
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if line == "" {
continue
}
log.Printf("%s: %s", prefix, line)
select {
case ch <- line:
default:
}
}
// Don't fail on scanner.Err(). We expect the process to go away at any time
// so we can see errors like "file already closed".
}
func (c *Catbox) stop() {
if err := c.Command.Process.Kill(); err != nil {
log.Printf("error killing catbox: %s", err)
}
c.WaitGroup.Wait()
if err := os.RemoveAll(c.ConfigDir); err != nil {
log.Fatalf("error cleaning up temporary directory: %s", err)
}
}
func (c *Catbox) linkServer(other *Catbox) error {
conf := filepath.Join(c.ConfigDir, "catbox.conf")
serversConf := filepath.Join(c.ConfigDir, "servers.conf")
extra := fmt.Sprintf("servers-config = %s", serversConf)
if err := writeConf(conf, c.Name, c.SID, extra); err != nil {
return err
}
serversConfContent := fmt.Sprintf(`%s = %s,%d,%s,0`,
other.Name, "127.0.0.1", other.Port, "testing")
if err := ioutil.WriteFile(serversConf, []byte(serversConfContent),
0644); err != nil {
return fmt.Errorf("error writing server conf: %s: %s", serversConf, err)
}
if err := c.Command.Process.Signal(syscall.SIGHUP); err != nil {
return fmt.Errorf("error sending SIGHUP: %s", err)
}
return nil
}
func waitForLog(ch <-chan string, re *regexp.Regexp) bool {
timeoutChan := time.After(10 * time.Second)
for {
select {
case s := <-ch:
if re.MatchString(s) {
return true
}
case <-timeoutChan:
return false
}
}
}

295
tests/client_test.go Normal file
View File

@@ -0,0 +1,295 @@
package tests
import (
"bufio"
"fmt"
"log"
"net"
"strings"
"sync"
"time"
"github.com/horgh/irc"
)
// Client represents a client connection.
type Client struct {
nick string
serverHost string
serverPort uint16
writeTimeout time.Duration
readTimeout time.Duration
conn net.Conn
rw *bufio.ReadWriter
recvChan chan irc.Message
sendChan chan irc.Message
errChan chan error
doneChan chan struct{}
wg *sync.WaitGroup
channels map[string]struct{}
mutex *sync.Mutex
}
// NewClient creates a Client.
func NewClient(nick, serverHost string, serverPort uint16) *Client {
return &Client{
nick: nick,
serverHost: serverHost,
serverPort: serverPort,
writeTimeout: 30 * time.Second,
readTimeout: 100 * time.Millisecond,
channels: map[string]struct{}{},
mutex: &sync.Mutex{},
}
}
// Start starts a client's connection and registers.
//
// The client responds to PING commands.
//
// All messages received from the server will be sent on the receive channel.
//
// Messages you send to the send channel will be sent to the server.
//
// If an error occurs, we send a message on the error channel. If you receive a
// message on that channel, you must stop the client.
//
// The caller must call Stop() to clean up the client.
func (c *Client) Start() (
<-chan irc.Message,
chan<- irc.Message,
<-chan error,
error,
) {
if err := c.connect(); err != nil {
return nil, nil, nil, fmt.Errorf("error connecting: %s", err)
}
if err := c.writeMessage(irc.Message{
Command: "NICK",
Params: []string{c.nick},
}); err != nil {
_ = c.conn.Close()
return nil, nil, nil, err
}
if err := c.writeMessage(irc.Message{
Command: "USER",
Params: []string{c.nick, "0", "*", c.nick},
}); err != nil {
_ = c.conn.Close()
return nil, nil, nil, err
}
c.recvChan = make(chan irc.Message, 512)
c.sendChan = make(chan irc.Message, 512)
c.errChan = make(chan error, 512)
c.doneChan = make(chan struct{})
c.wg = &sync.WaitGroup{}
c.wg.Add(1)
go c.reader(c.recvChan)
c.wg.Add(1)
go c.writer(c.sendChan)
return c.recvChan, c.sendChan, c.errChan, nil
}
// connect opens a new connection to the server.
func (c *Client) connect() error {
dialer := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
conn, err := dialer.Dial("tcp", fmt.Sprintf("%s:%d", c.serverHost,
c.serverPort))
if err != nil {
return fmt.Errorf("error dialing: %s", err)
}
c.conn = conn
c.rw = bufio.NewReadWriter(bufio.NewReader(c.conn), bufio.NewWriter(c.conn))
return nil
}
func (c Client) reader(recvChan chan<- irc.Message) {
defer c.wg.Done()
for {
select {
case <-c.doneChan:
close(recvChan)
return
default:
}
m, err := c.readMessage()
if err != nil {
// If we time out waiting for a read to succeed, just ignore it and try
// again. We want a short timeout on that so we frequently check whether
// we should end.
//
// There's no accessible error variable to compare with
if strings.Contains(err.Error(), "i/o timeout") {
continue
}
c.errChan <- fmt.Errorf("error reading message: %s", err)
close(recvChan)
return
}
if m.Command == "PING" {
if err := c.writeMessage(irc.Message{
Command: "PONG",
Params: []string{m.Params[0]},
}); err != nil {
c.errChan <- fmt.Errorf("error sending pong: %s", err)
close(recvChan)
return
}
}
if m.Command == "JOIN" {
if m.SourceNick() == c.nick {
c.mutex.Lock()
c.channels[m.Params[0]] = struct{}{}
c.mutex.Unlock()
}
}
recvChan <- m
}
}
func (c Client) writer(sendChan <-chan irc.Message) {
defer c.wg.Done()
LOOP:
for {
select {
case <-c.doneChan:
break LOOP
case m, ok := <-sendChan:
if !ok {
break
}
if err := c.writeMessage(m); err != nil {
c.errChan <- fmt.Errorf("error writing message: %s", err)
break LOOP
}
}
}
for range sendChan {
}
}
// writeMessage writes an IRC message to the connection.
func (c Client) writeMessage(m irc.Message) error {
buf, err := m.Encode()
if err != nil && err != irc.ErrTruncated {
return fmt.Errorf("unable to encode message: %s", err)
}
if err := c.conn.SetWriteDeadline(time.Now().Add(
c.writeTimeout)); err != nil {
return fmt.Errorf("unable to set deadline: %s", err)
}
sz, err := c.rw.WriteString(buf)
if err != nil {
return err
}
if sz != len(buf) {
return fmt.Errorf("short write")
}
if err := c.rw.Flush(); err != nil {
return fmt.Errorf("flush error: %s", err)
}
log.Printf("client %s: sent: %s", c.nick, strings.TrimRight(buf, "\r\n"))
return nil
}
// readMessage reads a line from the connection and parses it as an IRC message.
func (c Client) readMessage() (irc.Message, error) {
if err := c.conn.SetReadDeadline(time.Now().Add(c.readTimeout)); err != nil {
return irc.Message{}, fmt.Errorf("unable to set deadline: %s", err)
}
line, err := c.rw.ReadString('\n')
if err != nil {
return irc.Message{}, err
}
log.Printf("client %s: read: %s", c.nick, strings.TrimRight(line, "\r\n"))
m, err := irc.ParseMessage(line)
if err != nil && err != irc.ErrTruncated {
return irc.Message{}, fmt.Errorf("unable to parse message: %s: %s", line,
err)
}
return m, nil
}
// Stop shuts down the client and cleans up.
//
// You must not send any messages on the send channel after calling this
// function.
func (c *Client) Stop() {
// Tell reader and writer to end.
close(c.doneChan)
// We won't be sending anything further to writer. Let it clean up.
close(c.sendChan)
// Wait for reader and writer to end.
c.wg.Wait()
// We know the reader and writer won't be sending on the error channel any
// more.
close(c.errChan)
_ = c.conn.Close()
for range c.recvChan {
}
for range c.errChan {
}
}
// GetNick retrieves the client's nick.
func (c Client) GetNick() string { return c.nick }
// GetReceiveChannel retrieves the receive channel.
func (c Client) GetReceiveChannel() <-chan irc.Message { return c.recvChan }
// GetSendChannel retrieves the send channel.
func (c Client) GetSendChannel() chan<- irc.Message { return c.sendChan }
// GetErrorChannel retrieves the error channel.
func (c Client) GetErrorChannel() <-chan error { return c.errChan }
// GetChannels retrieves the IRC channels the client is on.
func (c Client) GetChannels() []string {
var channels []string
c.mutex.Lock()
for k := range c.channels {
channels = append(channels, k)
}
c.mutex.Unlock()
return channels
}

80
tests/message_test.go Normal file
View File

@@ -0,0 +1,80 @@
package tests
import (
"fmt"
"log"
"testing"
"time"
"github.com/horgh/irc"
)
// Test one client sending a message to another client.
func TestPRIVMSG(t *testing.T) {
catbox, err := harnessCatbox("irc.example.org", "000")
if err != nil {
t.Fatalf("error harnessing catbox: %s", err)
}
defer catbox.stop()
client1 := NewClient("client1", "127.0.0.1", catbox.Port)
recvChan1, sendChan1, _, err := client1.Start()
if err != nil {
t.Fatalf("error starting client: %s", err)
}
defer client1.Stop()
client2 := NewClient("client2", "127.0.0.1", catbox.Port)
recvChan2, _, _, err := client2.Start()
if err != nil {
t.Fatalf("error starting client: %s", err)
}
defer client2.Stop()
if waitForMessage(t, recvChan1, irc.Message{Command: irc.ReplyWelcome},
"welcome from %s", client1.GetNick()) == nil {
t.Fatalf("client1 did not get welcome")
}
if waitForMessage(t, recvChan2, irc.Message{Command: irc.ReplyWelcome},
"welcome from %s", client2.GetNick()) == nil {
t.Fatalf("client2 did not get welcome")
}
sendChan1 <- irc.Message{
Command: "PRIVMSG",
Params: []string{client2.GetNick(), "hi there"},
}
if waitForMessage(
t,
recvChan2,
irc.Message{
Command: "PRIVMSG",
Params: []string{client2.GetNick(), "hi there"},
},
"%s received PRIVMSG from %s", client1.GetNick(), client2.GetNick(),
) == nil {
t.Fatalf("client1 did not receive message from client2")
}
}
func waitForMessage(
t *testing.T,
ch <-chan irc.Message,
want irc.Message,
format string,
a ...interface{},
) *irc.Message {
for {
select {
case <-time.After(10 * time.Second):
t.Logf("timeout waiting for message: %s", want)
return nil
case got := <-ch:
if got.Command == want.Command {
log.Printf("got command: %s", fmt.Sprintf(format, a...))
return &got
}
}
}
}

165
tests/mode_test.go Normal file
View File

@@ -0,0 +1,165 @@
package tests
import (
"regexp"
"strconv"
"testing"
"time"
"github.com/horgh/irc"
)
// Test that clients get TS when running MODE on a channel they are on.
//
// Also test that the TS gets propagated between servers and a client on
// another server gets the same TS
func TestMODETS(t *testing.T) {
catbox1, err := harnessCatbox("irc1.example.org", "001")
if err != nil {
t.Fatalf("error harnessing catbox: %s", err)
}
defer catbox1.stop()
catbox2, err := harnessCatbox("irc2.example.org", "002")
if err != nil {
t.Fatalf("error harnessing catbox: %s", err)
}
defer catbox2.stop()
if err := catbox1.linkServer(catbox2); err != nil {
t.Fatalf("error linking catbox1 to catbox2: %s", err)
}
if err := catbox2.linkServer(catbox1); err != nil {
t.Fatalf("error linking catbox2 to catbox1: %s", err)
}
linkRE := regexp.MustCompile(`Established link to irc2\.`)
if !waitForLog(catbox1.LogChan, linkRE) {
t.Fatalf("failed to see servers link")
}
client1 := NewClient("client1", "127.0.0.1", catbox1.Port)
recvChan1, sendChan1, _, err := client1.Start()
if err != nil {
t.Fatalf("error starting client: %s", err)
}
defer client1.Stop()
if waitForMessage(t, recvChan1, irc.Message{Command: irc.ReplyWelcome},
"welcome from %s", client1.GetNick()) == nil {
t.Fatalf("client1 did not get welcome")
}
sendChan1 <- irc.Message{
Command: "JOIN",
Params: []string{"#test"},
}
if waitForMessage(
t,
recvChan1,
irc.Message{
Command: "JOIN",
Params: []string{"#test"},
},
"%s received JOIN #test", client1.GetNick(),
) == nil {
t.Fatalf("client1 did not receive JOIN message")
}
sendChan1 <- irc.Message{
Command: "MODE",
Params: []string{"#test"},
}
creationTimeMessage := waitForMessage(
t,
recvChan1,
irc.Message{
Command: "329",
},
"%s received 329 response after MODE command", client1.GetNick(),
)
if creationTimeMessage == nil {
t.Fatalf("client1 did not receive 329 response")
}
creationTimeString := ""
creationTime := time.Time{}
if len(creationTimeMessage.Params) >= 3 {
ct, err := strconv.ParseInt(creationTimeMessage.Params[2], 10, 64)
if err != nil {
t.Fatalf("error parsing 329 response unixtime: %s", err)
}
creationTimeString = creationTimeMessage.Params[2]
creationTime = time.Unix(ct, 0)
}
messageIsEqual(
t,
creationTimeMessage,
&irc.Message{
Prefix: catbox1.Name,
Command: "329",
Params: []string{client1.GetNick(), "#test", creationTimeString},
},
)
if time.Since(creationTime) > 30*time.Second {
t.Fatalf("channel creation time is too far in the past: %s", creationTime)
}
// Try a client on the other server and ensure they get the same time.
client2 := NewClient("client2", "127.0.0.1", catbox2.Port)
recvChan2, sendChan2, _, err := client2.Start()
if err != nil {
t.Fatalf("error starting client: %s", err)
}
defer client2.Stop()
if waitForMessage(t, recvChan2, irc.Message{Command: irc.ReplyWelcome},
"welcome from %s", client2.GetNick()) == nil {
t.Fatalf("client2 did not get welcome")
}
sendChan2 <- irc.Message{
Command: "JOIN",
Params: []string{"#test"},
}
if waitForMessage(
t,
recvChan2,
irc.Message{
Command: "JOIN",
Params: []string{"#test"},
},
"%s received JOIN #test", client2.GetNick(),
) == nil {
t.Fatalf("client2 did not receive JOIN message")
}
sendChan2 <- irc.Message{
Command: "MODE",
Params: []string{"#test"},
}
creationTimeMessage2 := waitForMessage(
t,
recvChan2,
irc.Message{
Command: "329",
},
"%s received 329 response after MODE command", client2.GetNick(),
)
if creationTimeMessage == nil {
t.Fatalf("client2 did not receive 329 response")
}
messageIsEqual(
t,
creationTimeMessage2,
&irc.Message{
Prefix: catbox2.Name,
Command: "329",
Params: []string{client2.GetNick(), "#test", creationTimeString},
},
)
}

32
tests/util_test.go Normal file
View File

@@ -0,0 +1,32 @@
package tests
import (
"testing"
"github.com/horgh/irc"
)
func messageIsEqual(t *testing.T, got, wanted *irc.Message) {
if got == nil {
t.Fatalf("received nil message")
}
if got.Prefix != wanted.Prefix {
t.Fatalf("message prefix = %s, wanted %s", got.Prefix, wanted.Prefix)
}
if got.Command != wanted.Command {
t.Fatalf("message command = %s, wanted %s", got.Command, wanted.Command)
}
if len(got.Params) != len(wanted.Params) {
t.Fatalf("message number of params = %d, wanted %d", len(got.Params),
len(wanted.Params))
}
for i := range wanted.Params {
if got.Params[i] != wanted.Params[i] {
t.Fatalf("param %d = %s, wanted %s", i, got.Params[i], wanted.Params[i])
}
}
}

View File

@@ -67,10 +67,6 @@ func (u *User) nickUhost() string {
return fmt.Sprintf("%s!%s@%s", u.DisplayNick, u.Username, u.Hostname)
}
func (u *User) userHost() string {
return fmt.Sprintf("%s@%s", u.Username, u.Hostname)
}
func (u *User) isOperator() bool {
_, exists := u.Modes['o']
return exists

View File

@@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

View File

@@ -1 +0,0 @@
This is a Go package which helps with reading configuration files.

View File

@@ -1,196 +0,0 @@
// Package config is a config file parser.
//
// A note on usage: Due to the fact that we use the reflect package, you must
// pass in the struct for which you want to parse config keys using all
// exported fields, or this config package cannot set those fields.
//
// Key names are case insensitive.
//
// For an example of using this package, see the test(s).
//
// For the types that we support parsing out of the struct, refer to the
// populateConfig() function.
package config
import (
"bufio"
"fmt"
"log"
"os"
"reflect"
"strconv"
"strings"
)
// ReadStringMap a config file and returns the keys and values in a map where
// keys and values are strings.
//
// The config file syntax is:
// key = value
//
// Lines may be commented if they begin with a '#' with only whitespace or no
// whitespace in front of the '#' character. Lines currently MAY NOT have
// trailing '#' to be treated as comments.
func ReadStringMap(path string) (map[string]string, error) {
if len(path) == 0 {
return nil, fmt.Errorf("invalid path. Path may not be blank")
}
fi, err := os.Open(path)
if err != nil {
return nil, err
}
defer func() {
if err := fi.Close(); err != nil {
log.Printf("error closing %s: %s", path, err)
}
}()
config := make(map[string]string)
scanner := bufio.NewScanner(fi)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "#") {
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
continue
}
key := strings.ToLower(strings.TrimSpace(parts[0]))
value := strings.TrimSpace(parts[1])
if len(key) == 0 {
return nil, fmt.Errorf("key length is 0")
}
_, exists := config[key]
if exists {
return nil, fmt.Errorf("config key defined twice: %s", key)
}
// Permit value to be blank.
config[key] = value
}
err = scanner.Err()
if err != nil {
return nil, fmt.Errorf("error reading from file: %s", err)
}
return config, nil
}
// PopulateStruct takes values read from a config as a string map, and uses them
// to populate a struct. The values will be converted to the struct's types as
// necessary.
//
// To understand the use of reflect in this function, refer to the article Laws
// of Reflection, or the documentation of the reflect package.
func PopulateStruct(config interface{}, rawValues map[string]string) error {
// Make a reflect.Value from the interface.
v := reflect.ValueOf(config)
// Access the value that the interface contains.
elem := v.Elem()
// Make a reflect.Type. This describes the Go type. We can use it to get
// struct field names.
elemType := elem.Type()
// Iterate over every field of the struct.
for i := 0; i < elem.NumField(); i++ {
// Access the field.
f := elem.Field(i)
// Determine the field name.
fieldName := elemType.Field(i).Name
// We require this field was in the config file.
rawValue, ok := rawValues[strings.ToLower(fieldName)]
if !ok {
return fmt.Errorf("field %s not found in config file", fieldName)
}
// Convert each value string, if necessary, to the necessary Go type.
// We support a subset of types ('kinds' in reflect) currently.
if f.Kind() == reflect.Int32 {
converted, err := strconv.ParseInt(rawValue, 10, 32)
if err != nil {
return fmt.Errorf("unable to convert field %s value %s to int32: %s",
fieldName, rawValue, err)
}
f.SetInt(converted)
continue
}
if f.Kind() == reflect.Int64 {
converted, err := strconv.ParseInt(rawValue, 10, 64)
if err != nil {
return fmt.Errorf("unable to convert field %s value %s to int64: %s",
fieldName, rawValue, err)
}
f.SetInt(converted)
continue
}
if f.Kind() == reflect.Uint64 {
converted, err := strconv.ParseUint(rawValue, 10, 64)
if err != nil {
return fmt.Errorf("unable to convert field %s value %s to uint64: %s",
fieldName, rawValue, err)
}
f.SetUint(converted)
continue
}
if f.Kind() == reflect.String {
f.SetString(rawValue)
continue
}
return fmt.Errorf("field %s: Value: %s: Field kind not yet supported: %s",
fieldName, rawValue, f.Kind().String())
}
return nil
}
// GetConfig reads a config file and populates a struct with what is read.
//
// We use the reflect package to populate the struct from the config.
//
// Currently every member of the struct must have had a value set in the
// config. That is, every config option is required.
func GetConfig(path string, config interface{}) error {
// We don't need to parameter check path or keys. Why? Because path will get
// checked when we read the config.
// We do not need to check anything with the config as it is up to the caller
// to ensure that they gave us a struct with members they want parsed out of
// a config.
// First read in the config. Every key will be associated with a value which
// is a string.
rawValues, err := ReadStringMap(path)
if err != nil {
return fmt.Errorf("unable to read config: %s: %s", err, path)
}
// Fill the struct with the values read from the config.
err = PopulateStruct(config, rawValues)
if err != nil {
return fmt.Errorf("unable to populate config: %s", err)
}
return nil
}

View File

@@ -1,36 +0,0 @@
package config
import (
"testing"
)
// TestPopulateConfig is to test the conversion of types.
func TestPopulateConfig(t *testing.T) {
type MyType struct {
Str string
Abc int64
}
var rawValues = map[string]string{
"str": "Hi there",
"abc": "123",
}
var myT MyType
err := PopulateStruct(&myT, rawValues)
if err != nil {
t.Errorf("Failed to populate: %s", err.Error())
return
}
if myT.Str != "Hi there" {
t.Errorf("Failed to parse string")
return
}
if myT.Abc != 123 {
t.Errorf("Failed to parse int")
return
}
}

View File

@@ -1,3 +0,0 @@
[submodule "irc-parser-tests"]
path = irc-parser-tests
url = https://github.com/DanielOaks/irc-parser-tests

View File

@@ -1,3 +0,0 @@
language: go
go:
- 1.9.x

661
vendor/github.com/horgh/irc/COPYING generated vendored
View File

@@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

View File

@@ -1,33 +0,0 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
branch = "master"
name = "github.com/DanielOaks/girc-go"
packages = ["ircmatch","ircmsg","ircutils"]
revision = "3a2b80af9bb858b7512f896a5b00804d574e80e0"
[[projects]]
name = "github.com/docopt/docopt-go"
packages = ["."]
revision = "784ddc588536785e7299f7272f39101f7faccc3f"
version = "0.6.2"
[[projects]]
branch = "master"
name = "github.com/goshuirc/e-nfa"
packages = ["."]
revision = "7071788e394065e6456458a5e9cb503cad545154"
[[projects]]
branch = "v2"
name = "gopkg.in/yaml.v2"
packages = ["."]
revision = "eb3733d160e74a9c7e442f435eb3bea458e1d19f"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "fd7fb29d85c0a78d4b7c3d5bb2c08cde5827d51922b9c4fba19936532a7ea5fa"
solver-name = "gps-cdcl"
solver-version = 1

View File

@@ -1,26 +0,0 @@
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
[[constraint]]
branch = "master"
name = "github.com/DanielOaks/irc-parser-tests"

View File

@@ -1,27 +0,0 @@
# IRC
[![Build
Status](https://travis-ci.org/horgh/irc.svg)](https://travis-ci.org/horgh/irc)
[![GoDoc](https://godoc.org/github.com/horgh/irc?status.svg)](https://godoc.org/github.com/horgh/irc)
[![Go Report
Card](https://goreportcard.com/badge/github.com/horgh/irc)](https://goreportcard.com/report/github.com/horgh/irc)
This package provides functionality for working with the IRC protocol.
Specifically, it provides decoding and encoding of IRC messages.
It is useful for writing IRC servers and bots.
[catbox](https://github.com/horgh/catbox) uses it, as does
[godrop](https://github.com/horgh/godrop).
In general it follows [RFC 1459](https://tools.ietf.org/html/rfc1459). RFC
1459 is mostly compatible with at the message format level with [RFC
2812](https://tools.ietf.org/html/rfc2812). Where there is a difference,
this package favours RFC 1459.
Due to the vagaries of IRC servers and clients in the wild, this package is
lenient and will decode messages even if they are not fully RFC compliant.
For example:
* It silently ignores trailing spaces in messages in certain cases (in
locations where they should be considered invalid).
* It allows messages to end with bare LF rather than the required CRLF.

350
vendor/github.com/horgh/irc/decode.go generated vendored
View File

@@ -1,350 +0,0 @@
// Package irc provides encoding and decoding of IRC protocol messages. It is
// useful for implementing clients and servers.
package irc
import (
"fmt"
"strings"
)
// ParseMessage parses a protocol message from the client/server. The message
// should include the trailing CRLF.
//
// See RFC 1459/2812 section 2.3.1.
func ParseMessage(line string) (Message, error) {
line, err := fixLineEnding(line)
if err != nil {
return Message{}, fmt.Errorf("line does not have a valid ending: %s", line)
}
truncated := false
if len(line) > MaxLineLength {
truncated = true
line = line[0:MaxLineLength-2] + "\r\n"
}
message := Message{}
index := 0
// It is optional to have a prefix.
if line[0] == ':' {
prefix, prefixIndex, err := parsePrefix(line)
if err != nil {
return Message{}, fmt.Errorf("problem parsing prefix: %s", err)
}
index = prefixIndex
message.Prefix = prefix
if index >= len(line) {
return Message{}, fmt.Errorf("malformed message. Prefix only")
}
}
// We've either parsed a prefix out or have no prefix.
command, index, err := parseCommand(line, index)
if err != nil {
return Message{}, fmt.Errorf("problem parsing command: %s", err)
}
message.Command = command
// May have params.
params, index, err := parseParams(line, index)
if err != nil {
return Message{}, fmt.Errorf("problem parsing params: %s", err)
}
if len(params) > 15 {
return Message{}, fmt.Errorf("too many parameters")
}
message.Params = params
// We should now have CRLF.
//
// index should be pointing at the CR after parsing params.
if index != len(line)-2 || line[index] != '\r' || line[index+1] != '\n' {
return Message{}, fmt.Errorf("malformed message. No CRLF found. Looking for end at position %d", index)
}
if truncated {
return message, ErrTruncated
}
return message, nil
}
// fixLineEnding tries to ensure the line ends with CRLF.
//
// If it ends with only LF, add a CR.
func fixLineEnding(line string) (string, error) {
if len(line) == 0 {
return "", fmt.Errorf("line is blank")
}
if len(line) == 1 {
if line[0] == '\n' {
return "\r\n", nil
}
return "", fmt.Errorf("line does not end with LF")
}
lastIndex := len(line) - 1
secondLastIndex := lastIndex - 1
if line[secondLastIndex] == '\r' && line[lastIndex] == '\n' {
return line, nil
}
if line[lastIndex] == '\n' {
return line[:lastIndex] + "\r\n", nil
}
return "", fmt.Errorf("line has no ending CRLF or LF")
}
// parsePrefix parses out the prefix portion of a string.
//
// line begins with : and ends with \n.
//
// If there is no error we return the prefix and the position after
// the SPACE.
// This means the index points to the first character of the command (in a well
// formed message). We do not confirm there actually is a character.
//
// We are parsing this:
// message = [ ":" prefix SPACE ] command [ params ] crlf
// prefix = servername / ( nickname [ [ "!" user ] "@" host ] )
//
// TODO: Enforce length limits
// TODO: Enforce character / format more strictly.
// Right now I don't do much other than ensure there is no space.
func parsePrefix(line string) (string, int, error) {
pos := 0
if line[pos] != ':' {
return "", -1, fmt.Errorf("line does not start with ':'")
}
for pos < len(line) {
// Prefix ends with a space.
if line[pos] == ' ' {
break
}
// Basic character check.
// I'm being very lenient here right now. Servername and hosts should only
// allow [a-zA-Z0-9]. Nickname can have any except NUL, CR, LF, " ". I
// choose to accept anything nicks can.
if line[pos] == '\x00' || line[pos] == '\n' || line[pos] == '\r' {
return "", -1, fmt.Errorf("invalid character found: %q", line[pos])
}
pos++
}
// We didn't find a space.
if pos == len(line) {
return "", -1, fmt.Errorf("no space found")
}
// Ensure we have at least one character in the prefix.
if pos == 1 {
return "", -1, fmt.Errorf("prefix is zero length")
}
// Return the prefix without the space.
// New index is after the space.
return line[1:pos], pos + 1, nil
}
// parseCommand parses the command portion of a message from the server.
//
// We start parsing at the given index in the string.
//
// We return the command portion and the index just after the command.
//
// ABNF:
// message = [ ":" prefix SPACE ] command [ params ] crlf
// command = 1*letter / 3digit
// params = *14( SPACE middle ) [ SPACE ":" trailing ]
// =/ 14( SPACE middle ) [ SPACE [ ":" ] trailing ]
func parseCommand(line string, index int) (string, int, error) {
newIndex := index
// Parse until we hit a non-letter or non-digit.
for newIndex < len(line) {
// Digit
if line[newIndex] >= 48 && line[newIndex] <= 57 {
newIndex++
continue
}
// Letter
if line[newIndex] >= 65 && line[newIndex] <= 122 {
newIndex++
continue
}
// Must be a space or CR.
if line[newIndex] != ' ' &&
line[newIndex] != '\r' {
return "", -1, fmt.Errorf("unexpected character after command: %q",
line[newIndex])
}
break
}
// 0 length command is not valid.
if newIndex == index {
return "", -1, fmt.Errorf("0 length command found")
}
// TODO: Enforce that we either have 3 digits or all letters.
// Return command string without space or CR.
// New index is at the CR or space.
return strings.ToUpper(line[index:newIndex]), newIndex, nil
}
// parseParams parses the params part of a message.
//
// The given index points to the first character in the params.
//
// It is valid for there to be no params.
//
// We return each param (stripped of : in the case of 'trailing') and the index
// after the params end.
//
// Note there may be a blank parameter since trailing may be empty.
//
// See <params> in grammar.
func parseParams(line string, index int) ([]string, int, error) {
newIndex := index
var params []string
for newIndex < len(line) {
if line[newIndex] != ' ' {
return params, newIndex, nil
}
// In theory we could treat the 15th parameter differently to account for
// ":" being optional in RFC 2812. This is a difference from 1459 and I
// suspect not seen in the wild, so I don't.
param, paramIndex, err := parseParam(line, newIndex)
if err != nil {
// We should always have at least one character. However it is common in
// the wild (ratbox, quassel) for there to be trailing space characters
// before the CRLF. Permit this despite it arguably being invalid.
//
// We return the index pointing after the problem spaces as though we
// consumed them. We will be pointing at the CR.
if err == errEmptyParam {
crIndex := isTrailingSpace(line, newIndex)
if crIndex != -1 {
return params, crIndex, nil
}
}
return nil, -1, fmt.Errorf("problem parsing parameter: %s", err)
}
newIndex = paramIndex
params = append(params, param)
}
return nil, -1, fmt.Errorf("malformed params. Not terminated properly")
}
// parseParam parses out a single parameter term.
//
// index points to a space.
//
// We return the parameter (stripped of : in the case of trailing) and the
// index after the parameter ends.
func parseParam(line string, index int) (string, int, error) {
newIndex := index
if line[newIndex] != ' ' {
return "", -1, fmt.Errorf("malformed param. No leading space")
}
newIndex++
if len(line) == newIndex {
return "", -1, fmt.Errorf("malformed parameter. End of string after space")
}
// SPACE ":" trailing
if line[newIndex] == ':' {
newIndex++
if len(line) == newIndex {
return "", -1, fmt.Errorf("malformed parameter. End of string after ':'")
}
// It is valid for there to be no characters. Because: trailing = *( ":"
// / " " / nospcrlfcl )
paramIndexStart := newIndex
for newIndex < len(line) {
if line[newIndex] == '\x00' || line[newIndex] == '\r' ||
line[newIndex] == '\n' {
break
}
newIndex++
}
return line[paramIndexStart:newIndex], newIndex, nil
}
// We know we are parsing a <middle> and that we've dealt with :. This means
// we accept any character except NUL, CR, or LF. A space means we're at the
// end of the param.
// paramIndexStart points at the character after the space.
paramIndexStart := newIndex
for newIndex < len(line) {
if line[newIndex] == '\x00' || line[newIndex] == '\r' ||
line[newIndex] == '\n' || line[newIndex] == ' ' {
break
}
newIndex++
}
// Must have at least one character in this case. See grammar for 'middle'.
if paramIndexStart == newIndex {
return "", -1, errEmptyParam
}
return line[paramIndexStart:newIndex], newIndex, nil
}
// If the string from the given position to the end contains nothing but spaces
// until we reach CRLF, return the position of CR.
//
// This is so we can recognize stray trailing spaces and discard them. They are
// arguably invalid, but we want to be liberal in what we accept.
func isTrailingSpace(line string, index int) int {
for i := index; i < len(line); i++ {
if line[i] == ' ' {
continue
}
if line[i] == '\r' {
return i
}
return -1
}
// We didn't hit \r. Line was all spaces.
return -1
}

View File

@@ -1,95 +0,0 @@
package irc
import (
"fmt"
"strings"
)
// Encode encodes the Message into a raw protocol message string.
//
// The resulting string will have a trailing CRLF.
//
// If encoding the message would exceed the allowed maximum length (more than
// MaxLineLength bytes), we truncate and return as much as we can and return
// ErrTruncated. This truncated message may still be usable.
//
// It does not enforce command specific semantics.
func (m Message) Encode() (string, error) {
s := ""
if len(m.Prefix) > 0 {
s += ":" + m.Prefix + " "
}
s += m.Command
if len(s)+2 > MaxLineLength {
return "", fmt.Errorf("message with only prefix/command is too long")
}
truncated := false
// Both RFC 1459 and RFC 2812 limit us to 15 parameters.
if len(m.Params) > 15 {
return "", fmt.Errorf("too many parameters")
}
for i, param := range m.Params {
// We need to prefix the parameter with a colon in a few cases:
//
// 1) When there is a space in the parameter
//
// 2) When the first character is a colon
//
// 3) When this is the last parameter and it is empty. We do this to ensure
// it is visible. This is important e.g. in a TOPIC unset command (TS6
// server protocol). Also, RFC 1459/2812's grammar permits this.
//
// RFC 2812 differs from RFC 1459 by saying that ":" is optional for the
// 15th parameter, but we ignore that.
if idx := strings.IndexAny(param, " "); idx != -1 ||
(param != "" && param[0] == ':') ||
param == "" {
param = ":" + param
// This must be the last parameter. There can only be one <trailing>.
if i+1 != len(m.Params) {
return "", fmt.Errorf(
"parameter problem: ':' or ' ' outside last parameter")
}
}
// If we add the parameter as is, do we exceed the maximum length?
if len(s)+1+len(param)+2 > MaxLineLength {
// Either we can truncate the parameter and include a portion of it, or
// the parameter is too short to include at all. If it is too short to
// include, then don't add the space separator either.
// Claim the space separator (1) and CRLF (2) as used. Then we can tell
// how many bytes are available for the parameter as it is.
lengthUsed := len(s) + 1 + 2
lengthAvailable := MaxLineLength - lengthUsed
// If we prefixed the parameter with : then it's possible we include
// only the : here (if length available is 1). This is perhaps a little
// odd but I don't think problematic.
if lengthAvailable > 0 {
s += " " + param[0:lengthAvailable]
}
truncated = true
break
}
s += " " + param
}
s += "\r\n"
if truncated {
return s, ErrTruncated
}
return s, nil
}

54
vendor/github.com/horgh/irc/irc.go generated vendored
View File

@@ -1,54 +0,0 @@
package irc
import (
"errors"
"fmt"
"strings"
)
const (
// MaxLineLength is the maximum protocol message line length. It includes
// CRLF.
MaxLineLength = 512
// ReplyWelcome is the RPL_WELCOME response numeric.
ReplyWelcome = "001"
// ReplyYoureOper is the RPL_YOUREOPER response numeric.
ReplyYoureOper = "381"
)
// ErrTruncated is the error returned by Encode if the message gets truncated
// due to encoding to more than MaxLineLength bytes.
var ErrTruncated = errors.New("message truncated")
// It is not always valid for there to be a parameter with zero characters. If
// there is one, it should have a ':' prefix.
var errEmptyParam = errors.New("parameter with zero characters")
// Message holds a protocol message. See section 2.3.1 in RFC 1459/2812.
type Message struct {
// Prefix may be blank. It's optional.
Prefix string
// Command is the IRC command. For example, PRIVMSG. It may be a numeric.
Command string
// There are at most 15 parameters.
Params []string
}
func (m Message) String() string {
return fmt.Sprintf("Prefix [%s] Command [%s] Params%q", m.Prefix, m.Command,
m.Params)
}
// SourceNick retrieves the nickname portion of the prefix. It is valid for
// this to be blank as not all messages have prefixes.
func (m Message) SourceNick() string {
idx := strings.Index(m.Prefix, "!")
if idx == -1 {
return ""
}
return m.Prefix[:idx]
}

View File

@@ -1,700 +0,0 @@
package irc
import "testing"
func TestSourceNick(t *testing.T) {
tests := []struct {
input Message
output string
}{
{Message{}, ""},
{Message{Prefix: "blah"}, ""},
{Message{Prefix: "!"}, ""},
{Message{Prefix: "hi!"}, "hi"},
{Message{Prefix: "hi!~hello@hey"}, "hi"},
}
for _, test := range tests {
got := test.input.SourceNick()
if got != test.output {
t.Errorf("%+v.SourceNick() = %s, wanted %s", test.input, got, test.output)
}
}
}
func TestParseMessage(t *testing.T) {
tests := []struct {
input string
prefix string
command string
params []string
success bool
}{
{":irc PRIVMSG\r\n", "irc", "PRIVMSG", []string{}, true},
// No CRLF
{":irc PRIVMSG", "", "", []string{}, false},
// No CRLF
{":irc PRIVMSG one", "", "", []string{}, false},
// No command.
{":irc \r\n", "", "", []string{}, false},
{"PRIVMSG\r\n", "", "PRIVMSG", []string{}, true},
{"PRIVMSG :hi there\r\n", "", "PRIVMSG", []string{"hi there"}, true},
// Empty prefix.
{": PRIVMSG \r\n", "", "", []string{}, false},
// Stray \r.
{"ir\rc\r\n", "", "", []string{}, false},
{":irc PRIVMSG blah\r\n", "irc", "PRIVMSG", []string{"blah"}, true},
{":irc 001 :Welcome\r\n", "irc", "001", []string{"Welcome"}, true},
{":irc 001\r\n", "irc", "001", []string{}, true},
// This is technically invalid per grammar as there is a trailing space.
// However I permit it as we see trailing space in the wild frequently.
{":irc PRIVMSG \r\n", "irc", "PRIVMSG", []string{}, true},
// Invalid command.
{":irc @01\r\n", "", "", []string{}, false},
// No command.
{":irc \r\n", "", "", []string{}, false},
// Space before command.
{":irc PRIVMSG\r\n", "", "", []string{}, false},
{":irc 000 hi\r\n", "irc", "000", []string{"hi"}, true},
// It is valid to have no parameters.
{":irc 000\r\n", "irc", "000", []string{}, true},
// Test last param having no :
{":irc 000 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5\r\n", "irc", "000", []string{"1",
"2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "5"},
true},
// Test last param having no : nor characters. If we went by RFC 2812 then
// this would give us an empty 15th parametr. But we go by RFC 1459 and so
// treat it as invalid trailing space and ignore it.
{":irc 000 1 2 3 4 5 6 7 8 9 0 1 2 3 4 \r\n", "irc", "000",
[]string{"1", "2",
"3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4"}, true},
// Test last param having : but no characters
{":irc 000 1 2 3 4 5 6 7 8 9 0 1 2 3 4 :\r\n", "irc", "000",
[]string{"1", "2",
"3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", ""}, true},
{":irc 000 1 2 3 4 5 6 7 8 9 0 1 2 3 4 :hi there\r\n", "irc", "000",
[]string{"1", "2",
"3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "hi there"},
true},
// If we went by RFC 2812 then we get "hi there" as the 15th parameter
// since : is optional by that RFC. But we favour RFC 1459 and so see too
// many parameters.
{":irc 000 1 2 3 4 5 6 7 8 9 0 1 2 3 4 hi there\r\n", "", "",
[]string{}, false},
// Malformed because \r should not appear there.
{":irc 000 \r\r\n", "", "", []string{}, false},
// Param must not be blank unless last param.
// While this violates the grammar, I permit it now anyway.
{":irc 000 \r\n", "irc", "000", []string{}, true},
{":irc 000 0a 1b\r\n", "irc", "000", []string{"0a", "1b"}, true},
// If we have a space then there must be a parameter (unless it's the
// 15th).
// While this violates the grammar, I permit it now anyway.
{":irc 000 0 1 \r\n", "irc", "000", []string{"0", "1"}, true},
// NUL byte is invalid.
{":irc 000 a\x00 1 \r\n", "", "", []string{}, false},
// : inside a middle. Valid.
{":irc 000 a:bc\r\n", "irc", "000", []string{"a:bc"}, true},
{":irc 000 hi :there yes\r\n", "irc", "000", []string{"hi", "there yes"},
true},
// : inside a middle parameter. This is valid.
{":irc 000 hi:hi :no no\r\n", "irc", "000", []string{"hi:hi", "no no"},
true},
{":irc 000 hi:hi :no no :yes yes\r\n", "irc", "000", []string{"hi:hi", "no no :yes yes"},
true},
{":irc 000 hi:hi :no no :yes yes\n", "irc", "000", []string{"hi:hi", "no no :yes yes"},
true},
// Trailing whitespace is not valid here. Ratbox currently does send
// messages like this however.
{":irc MODE #test +o user \r\n", "irc", "MODE",
[]string{"#test", "+o", "user"}, true},
// Blank topic parameter is used to unset the topic.
{":nick!user@host TOPIC #test :\r\n", "nick!user@host", "TOPIC", []string{"#test", ""},
true},
{":nick!user@host MODE #test +o :blah\r\n", "nick!user@host", "MODE",
[]string{"#test", "+o", "blah"}, true},
{":nick!user@host MODE #test +o blah1 :blah\r\n", "nick!user@host", "MODE",
[]string{"#test", "+o", "blah1", "blah"}, true},
{":nick!user@host MODE #test +o :blah1 blah\r\n", "nick!user@host", "MODE",
[]string{"#test", "+o", "blah1 blah"}, true},
{":nick!user@host PRIVMSG #test \r\n", "nick!user@host", "PRIVMSG",
[]string{"#test"}, true},
{":nick!user@host PRIVMSG #test :\r\n", "nick!user@host", "PRIVMSG",
[]string{"#test", ""}, true},
// Message is too long. Truncate it.
{
":nick PRIVMSG0 #test aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n",
"nick",
"PRIVMSG0",
[]string{"#test", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
false,
},
// Message is too long. Truncate. This time we truncate in such a way that
// we risk leaving a trailing space that separated parameters.
{
// bb is where \r\n should be. Entire string is 514 bytes.
":nick PRIVMSG1 #test aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bb\r\n",
"nick",
"PRIVMSG1",
[]string{"#test", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
false,
},
// Message is too long. Truncate. This time we truncate in such a way that
// we leave only : that was prefixing a parameter.
{
// b is where \r should be. Entire string is 513 bytes.
":nick PRIVMSG2 #test aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :b\r\n",
"nick",
"PRIVMSG2",
[]string{"#test", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", ""},
false,
},
// Trailing whitespace is not valid. However we accept it as we see it in
// the wild. This tests having lots of it.
{":irc MODE #test +o user \r\n", "irc", "MODE",
[]string{"#test", "+o", "user"}, true},
// Test that inline : isn't a problem.
{":irc MODE #test +o u:ser\r\n", "irc", "MODE",
[]string{"#test", "+o", "u:ser"}, true},
}
for _, test := range tests {
msg, err := ParseMessage(test.input)
if err != nil {
if test.success {
t.Errorf("ParseMessage(%q) = %s", test.input, err)
continue
}
if err == ErrTruncated {
if msg.Prefix != test.prefix {
t.Errorf("truncated. ParseMessage(%q) got prefix %v, wanted %v",
test.input, msg.Prefix, test.prefix)
continue
}
if msg.Command != test.command {
t.Errorf("truncated. ParseMessage(%q) got command %v, wanted %v",
test.input, msg.Command, test.command)
continue
}
if !paramsEqual(msg.Params, test.params) {
t.Errorf("truncated. ParseMessage(%q) got params %q, wanted %q",
test.input, msg.Params, test.params)
continue
}
}
continue
}
if !test.success {
t.Errorf("ParseMessage(%q) should have failed, but did not.", test.input)
continue
}
if msg.Prefix != test.prefix {
t.Errorf("ParseMessage(%q) got prefix %v, wanted %v", test.input,
msg.Prefix, test.prefix)
continue
}
if msg.Command != test.command {
t.Errorf("ParseMessage(%q) got command %v, wanted %v", test.input,
msg.Command, test.command)
continue
}
if !paramsEqual(msg.Params, test.params) {
t.Errorf("ParseMessage(%q) got params %q, wanted %q", test.input,
msg.Params, test.params)
continue
}
}
}
func TestFixLineEnding(t *testing.T) {
tests := []struct {
input string
output string
success bool
}{
{"hi", "", false},
{"hi\n", "hi\r\n", true},
{"hi\r\n", "hi\r\n", true},
{"\n", "\r\n", true},
{"\r\n", "\r\n", true},
}
for _, test := range tests {
out, err := fixLineEnding(test.input)
if err != nil {
if !test.success {
continue
}
t.Errorf("fixLineEnding(%s) failed %s, wanted %s", test.input, err,
test.output)
continue
}
if !test.success {
t.Errorf("fixLineEnding(%s) succeeded, wanted failure", test.input)
continue
}
if out != test.output {
t.Errorf("fixLineEnding(%s) = %s, wanted %s", test.input, out,
test.output)
}
}
}
func TestParsePrefix(t *testing.T) {
var tests = []struct {
input string
prefix string
index int
}{
{":irc.example.com PRIVMSG", "irc.example.com", 17},
{":irc.example.com ", "irc.example.com", 17},
{":irc PRIVMSG ", "irc", 5},
{"irc.example.com", "", -1},
{": PRIVMSG ", "", -1},
{"irc\rexample.com", "", -1},
}
for _, test := range tests {
prefix, index, err := parsePrefix(test.input)
if err != nil {
if test.index != -1 {
t.Errorf("parsePrefix(%q) = error %s", test.input, err.Error())
}
continue
}
if test.index == -1 {
t.Errorf("parsePrefix(%q) should have failed, but did not", test.input)
continue
}
if prefix != test.prefix {
t.Errorf("parsePrefix(%q) = %v, want %v", test.input, prefix,
test.prefix)
continue
}
if index != test.index {
t.Errorf("parsePrefix(%q) = %v, want %v", test.input, index,
test.index)
continue
}
}
}
func TestParseCommand(t *testing.T) {
var tests = []struct {
input string
command string
startIndex int
newIndex int
}{
{":irc PRIVMSG blah\r\n", "PRIVMSG", 5, 12},
{":irc 001 :Welcome\r\n", "001", 5, 8},
{":irc 001\r\n", "001", 5, 8},
{":irc PRIVMSG ", "PRIVMSG", 5, 12},
{":irc @01\r\n", "", 5, -1},
{":irc \r\n", "", 5, -1},
{":irc PRIVMSG\r\n", "", 5, -1},
}
for _, test := range tests {
command, newIndex, err := parseCommand(test.input, test.startIndex)
if err != nil {
if test.newIndex != -1 {
t.Errorf("parseCommand(%q) = error %s", test.input, err.Error())
}
continue
}
if test.newIndex == -1 {
t.Errorf("parseCommand(%q) should have failed, but did not", test.input)
continue
}
if command != test.command {
t.Errorf("parseCommand(%q) = %v, want %v", test.input, command,
test.command)
continue
}
if newIndex != test.newIndex {
t.Errorf("parseCommand(%q) = %v, want %v", test.input, newIndex,
test.newIndex)
continue
}
}
}
func TestParseParams(t *testing.T) {
tests := []struct {
input string
index int
params []string
newIndex int
}{
{":irc 000 hi\r\n", 8, []string{"hi"}, 11},
// It is valid to have no parameters.
{":irc 000\r\n", 8, nil, 8},
// Test last param having no :
{":irc 000 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5\r\n", 8, []string{"1", "2",
"3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "5"}, 38},
// Test last param having no : nor characters. Going by RFC 2812 this would
// give us an empty parameter as the : is optional there. But we favour RFC
// 1459 and due to our ignoring trailing whitespace, though invalid, we get
// only 14 parameters.
{":irc 000 1 2 3 4 5 6 7 8 9 0 1 2 3 4 \r\n", 8, []string{"1", "2",
"3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4"}, 37},
// Test last param having : but no characters
{":irc 000 1 2 3 4 5 6 7 8 9 0 1 2 3 4 :\r\n", 8, []string{"1", "2",
"3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", ""}, 38},
// Malformed because \r should not appear there. However, parameter parsing
// accepts this message (as having no parameters), and stops at the first
// \r. Full message parsing will catch this as invalid.
{":irc 000 \r\r\n", 8, []string{}, 9},
// Must not be blank unless last param.
// While this violates the grammar, I permit it because we see it in the
// wild.
{":irc 000 \r\n", 8, []string{}, 9},
{":irc 000 0a 1b\r\n", 8, []string{"0a", "1b"}, 14},
// If we have a space then there must be a parameter (unless it's the
// 15th). While this violates the grammar, I permit it as we see it
// frequently in the wild.
{":irc 000 0 1 \r\n", 8, []string{"0", "1"}, 13},
// This is a malformed message (NUL byte) but the parameter parsing won't
// catch it because we stop at the NUL byte. Full message parsing catches
// it.
{":irc 000 a\x00 1 \r\n", 8, []string{"a"}, 10},
// This parameter is valid as : is not the first character.
{":irc 000 a:bc\r\n", 8, []string{"a:bc"}, 13},
}
for _, test := range tests {
params, newIndex, err := parseParams(test.input, test.index)
if err != nil {
if test.newIndex != -1 {
t.Errorf("parseParams(%q) = %v, want %v", test.input, err, test.params)
}
continue
}
if test.newIndex == -1 {
t.Errorf("parseParams(%q) should have failed, but did not", test.input)
continue
}
if !paramsEqual(params, test.params) {
t.Errorf("parseParams(%q) = %v, wanted %v", test.input, params,
test.params)
continue
}
if newIndex != test.newIndex {
t.Errorf("parseParams(%q) index = %v, wanted %v", test.input, newIndex,
test.newIndex)
continue
}
}
}
func paramsEqual(params1, params2 []string) bool {
if len(params1) != len(params2) {
return false
}
for i, v := range params1 {
if params2[i] != v {
return false
}
}
return true
}
func TestEncodeMessage(t *testing.T) {
tests := []struct {
input Message
output string
success bool
}{
{
Message{
Command: "PRIVMSG",
Prefix: "nick",
Params: []string{"nick2", "hi there"},
},
":nick PRIVMSG nick2 :hi there\r\n",
true,
},
{
Message{
Command: "PRIVMSG",
Prefix: "nick",
Params: []string{"nick2", " hi there"},
},
":nick PRIVMSG nick2 : hi there\r\n",
true,
},
{
Message{
Command: "TOPIC",
Prefix: "nick",
Params: []string{"#test", "hi there"},
},
":nick TOPIC #test :hi there\r\n",
true,
},
// We can have zero length TOPIC in TS6 protocol - for when the topic is
// to be unset.
{
Message{
Command: "TOPIC",
Prefix: "nick",
Params: []string{"#test", ""},
},
":nick TOPIC #test :\r\n",
true,
},
{
Message{
Command: "TOPIC",
Prefix: "nick",
Params: []string{"#test", ":"},
},
":nick TOPIC #test ::\r\n",
true,
},
// A message that encodes to longer than MaxLineLength (512) bytes
// The encoded length of this message would be
// 1+7+1 + 4+1 + 5+1 + 530 + 2 (crlf) = 552 bytes
// Truncates to 512.
{
Message{
Command: "PRIVMSG",
Prefix: "nick",
// Second parameter is 530 bytes
Params: []string{"#test", "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz"},
},
":nick PRIVMSG #test abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuv\r\n",
false,
},
// Another message that is too long to encode as is. Truncates.
//
// This time the final parameter is 2 bytes long and has no prefix, and
// there is no space to include either of them. This is to test what
// happens when we truncate in the situation where we drop the entire last
// parameter.
{
Message{
Command: "PRIVMSG",
Prefix: "nick",
Params: []string{"#test", "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstz", "wx"},
},
// Length becomes 511 bytes. Not 512 because we do not include the space
// that would separate the parameter which we cannot include at all.
":nick PRIVMSG #test abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstz\r\n",
false,
},
// Message is too long to encode.
//
// In this case the last parameter is 1 byte, and it has a prefix. Again
// there is no space to include any of it. This is again to test behaviour
// when we drop the whole last parameter.
{
Message{
Command: "PRIVMSG",
Prefix: "nick",
Params: []string{"#test", "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstz", ":"},
},
// Length becomes 511 bytes. Not 512 because we do not include the space
// that would separate the parameter which we cannot include at all.
":nick PRIVMSG #test abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstz\r\n",
false,
},
// Message is too long to encode.
//
// In this case the last parameter is 1 byte, and it has a prefix. The
// difference in this case is we can include just the prefix.
{
Message{
Command: "PRIVMSG",
Prefix: "nick",
Params: []string{"#test", "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrst", ":"},
},
":nick PRIVMSG #test abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrst :\r\n",
false,
},
// A message that is too long to encode where only the prefix and the
// command are alone enough to exceed the length. In this case it does
// not make sense to truncate. Error out.
{
Message{
Command: "PRIVMSG",
// Prefix is 530 bytes
Prefix: "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz",
Params: []string{},
},
"",
false,
},
// Too many parameters.
{
Message{
Command: "PRIVMSG",
Prefix: "hi",
Params: []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12", "13", "14", "15", "16"},
},
"",
false,
},
// 15 parameters is ok.
{
Message{
Command: "PRIVMSG",
Prefix: "hi",
Params: []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12", "13", "14", "15"},
},
":hi PRIVMSG 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\r\n",
true,
},
// Inline : does not get escaped.
{
Message{
Command: "PRIVMSG",
Prefix: "hi",
Params: []string{"one:two", "hi there"},
},
":hi PRIVMSG one:two :hi there\r\n",
true,
},
// Param starting with : does get escaped.
{
Message{
Command: "PRIVMSG",
Prefix: "hi",
Params: []string{":one:two"},
},
":hi PRIVMSG ::one:two\r\n",
true,
},
// Need to escape first parameter, but it's not the last.
{
Message{
Command: "PRIVMSG",
Prefix: "hi",
Params: []string{":one:two", "hi"},
},
"",
false,
},
}
for _, test := range tests {
buf, err := test.input.Encode()
if err != nil {
if test.success {
t.Errorf("Encode(%s) failed but should succeed: %s", test.input, err)
continue
}
// When we truncate, check we received what we expected.
if err == ErrTruncated {
if buf != test.output {
t.Errorf("Encode(%s) truncated to %s, wanted %s", test.input, buf,
test.output)
continue
}
}
continue
}
if !test.success {
t.Errorf("Encode(%s) succeeded but should fail", test.input)
continue
}
if buf != test.output {
t.Errorf("Encode(%s) = %s, wanted %s", test.input, buf, test.output)
continue
}
}
}

View File

@@ -1,142 +0,0 @@
package irc
import (
"io/ioutil"
"path/filepath"
"strings"
"testing"
yaml "gopkg.in/yaml.v2"
)
// msg-split tests from irc-parser-tests
func TestIRCParserTestsMsgSplit(t *testing.T) {
testFile := filepath.Join("irc-parser-tests", "tests", "msg-split.yaml")
data, err := ioutil.ReadFile(testFile)
if err != nil {
t.Fatalf("error opening file: %s: %s", testFile, err)
}
type MsgSplitTests struct {
Tests []struct {
Input string
Atoms struct {
Source *string
Verb string
Params []string
Tags map[string]interface{}
}
}
}
var tests *MsgSplitTests
if err := yaml.Unmarshal(data, &tests); err != nil {
t.Fatalf("error unmarshaling %s: %s", testFile, err)
}
for _, test := range tests.Tests {
if test.Atoms.Tags != nil {
// We don't support tags right now.
continue
}
if test.Input ==
":gravel.mozilla.org 432 #momo :Erroneous Nickname: Illegal characters" {
// This is an invalid message. I'm not inclined to support it.
continue
}
input := test.Input + "\r\n"
msg, err := ParseMessage(input)
if err != nil {
t.Fatalf("error parsing message: %s: %s", test.Input, err)
}
wantCommand := strings.ToUpper(test.Atoms.Verb)
if msg.Command != wantCommand {
t.Errorf("%s: got command %s, wanted %s", test.Input, msg.Command,
wantCommand)
continue
}
if len(msg.Params) != len(test.Atoms.Params) {
t.Errorf("%s: got %d params, wanted %d", test.Input, len(msg.Params),
len(test.Atoms.Params))
continue
}
for i, data := range test.Atoms.Params {
if msg.Params[i] != data {
t.Errorf("%s: param %d is %s, wanted %s", test.Input, i,
msg.Params[i], data)
continue
}
}
prefix := ""
if test.Atoms.Source != nil {
prefix = *test.Atoms.Source
}
if msg.Prefix != prefix {
t.Errorf("%s: prefix is %s, wanted %s", test.Input, msg.Prefix, prefix)
continue
}
}
}
// msg-join tests from irc-parser-tests
func TestIRCParserTestsMsgJoin(t *testing.T) {
testFile := filepath.Join("irc-parser-tests", "tests", "msg-join.yaml")
data, err := ioutil.ReadFile(testFile)
if err != nil {
t.Fatalf("error opening file: %s: %s", testFile, err)
}
type MsgJoinTests struct {
Tests []struct {
Desc string
Atoms struct {
Source string
Verb string
Params []string
Tags map[string]interface{}
}
Matches []string
}
}
var tests *MsgJoinTests
if err := yaml.Unmarshal(data, &tests); err != nil {
t.Fatalf("error unmarshaling: %s: %s", testFile, err)
}
for _, test := range tests.Tests {
if test.Atoms.Tags != nil {
// We don't support tags currently.
continue
}
msg := Message{
Prefix: test.Atoms.Source,
Command: test.Atoms.Verb,
Params: test.Atoms.Params,
}
buf, err := msg.Encode()
if err != nil {
t.Fatalf("failed to encode message for test %s: %s", test.Desc, err)
}
matched := false
for _, match := range test.Matches {
if buf == match+"\r\n" {
matched = true
}
}
if !matched {
t.Errorf("no match: %s: got %s, wanted %v", test.Desc, buf,
test.Matches)
}
}
}

View File

@@ -2,7 +2,7 @@ package main
// CreatedDate is the date we're built. This would be nice to generate
// dynamically, but I don't want to complicate the build.
const CreatedDate = "2018-07-28"
const CreatedDate = "2019-01-01"
// Version is our version.
const Version = "catbox-1.9.0"
const Version = "catbox-1.11.0"