46 Commits

Author SHA1 Message Date
Will Storey
0cad70c364 Allow setting SID by command line argument 2019-07-01 17:55:59 -07:00
Will Storey
1afbd99bc7 Log server name when starting up 2019-07-01 14:59:19 -07:00
Will Storey
c2182d5a74 Allow specifying server-name via command line argument 2019-07-01 14:49:57 -07:00
Will Storey
ea0e612d3e Start client writer immediately
This lets us actually send messages to clients as they're ready during
setup.
2019-07-01 14:13:42 -07:00
Will Storey
6c093ca0b0 Send notices during connect immediately
This was confusing to clients if the DNS lookup was not instant.
2019-07-01 12:05:09 -07:00
Will Storey
242479c791 Update dependencies 2019-04-19 11:57:58 -07:00
Will Storey
e99b37e322 tests: Retry linking due to flakey build 2019-04-19 11:57:41 -07:00
Will Storey
19dfea1dc0 Convert some tests to testify 2019-04-19 11:06:23 -07:00
Will Storey
23084c52ca Update dependencies 2019-04-19 10:56:39 -07:00
Will Storey
b25e3fcb12 doc: Clarify release instructions 2019-01-01 12:57:12 -08:00
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
42 changed files with 355 additions and 5075 deletions

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,9 +1,5 @@
language: go
go:
- "1.10.x"
before_install:
- go get -u gopkg.in/alecthomas/gometalinter.v2
- gometalinter.v2 --install
- "1.x"
script:
- go test -v ./...
- gometalinter.v2 ./...

View File

@@ -1,4 +1,28 @@
# 1.9.0
# 1.12.0
* Send messages during connect immediately rather than only after we've
performed our reverse DNS lookup.
* Allow setting server name via command line argument.
* Log server name when starting up.
* Allow setting SID via command line argument.
# 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

View File

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

View File

@@ -5,66 +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)
catbox is an IRC daemon. I run a small network using it.
# 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).
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.
* TLS.
* 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.
If you want to listen on a TLS port, you must have a certificate and key
available.
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
A setup for a network might look like this:
* 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.
Clients connect to the network hostname and verify against it. Servers
connect to each other by server hostname and verify against it.
# 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

21
args.go
View File

@@ -11,12 +11,27 @@ import (
type Args struct {
ConfigFile string
ListenFD int
ServerName string
SID string
}
func getArgs() *Args {
configFile := flag.String("conf", "", "Configuration file.")
fd := flag.Int("listen-fd", -1,
"File descriptor with listening port to use (optional).")
fd := flag.Int(
"listen-fd",
-1,
"File descriptor with listening port to use (optional).",
)
serverName := flag.String(
"server-name",
"",
"Server name. Overrides server-name from config.",
)
sid := flag.String(
"sid",
"",
"SID. Overrides ts6-sid from config.",
)
flag.Parse()
@@ -35,6 +50,8 @@ func getArgs() *Args {
return &Args{
ConfigFile: configPath,
ListenFD: *fd,
ServerName: *serverName,
SID: *sid,
}
}

View File

@@ -78,7 +78,11 @@ type UserConfig struct {
// We parse some values into alternate representations.
//
// This function populates both the server.Config and server.Opers fields.
func checkAndParseConfig(file string) (*Config, error) {
func checkAndParseConfig(
file,
serverName,
sid string,
) (*Config, error) {
m, err := config.ReadStringMap(file)
if err != nil {
return nil, err
@@ -113,6 +117,9 @@ func checkAndParseConfig(file string) (*Config, error) {
if m["server-name"] != "" {
c.ServerName = m["server-name"]
}
if serverName != "" {
c.ServerName = serverName
}
c.ServerInfo = "IRC"
if m["server-info"] != "" {
@@ -216,6 +223,9 @@ func checkAndParseConfig(file string) (*Config, error) {
}
c.TS6SID = TS6SID(m["ts6-sid"])
}
if sid != "" {
c.TS6SID = TS6SID(sid)
}
c.AdminEmail = m["admin-email"]

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

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

View File

@@ -1,8 +1,9 @@
# TODO
## Higher priority
* Valid certs.
* Set up goreleaser.
* 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
@@ -14,21 +15,21 @@
* 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.
@@ -49,7 +50,7 @@
## RFC
* Channel modes: +v/+b/+i/+k/etc
* Channel modes: +v/+b/+k/etc
* KICK
@@ -68,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)
@@ -87,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.

9
go.mod Normal file
View File

@@ -0,0 +1,9 @@
module github.com/horgh/catbox
require (
github.com/horgh/config v0.0.0-20190101204049-770bc48a3bdf
github.com/horgh/irc v0.0.0-20190101204118-d089b0b5b5c5
github.com/pkg/errors v0.8.1
github.com/stretchr/objx v0.2.0 // indirect
github.com/stretchr/testify v1.3.0
)

28
go.sum Normal file
View File

@@ -0,0 +1,28 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
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/config v0.0.0-20190101204049-770bc48a3bdf h1:/jDikK0Oteboi7/Z6uzan5aQhiqwMwKTIA+5ZooDclk=
github.com/horgh/config v0.0.0-20190101204049-770bc48a3bdf/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/horgh/irc v0.0.0-20190101204118-d089b0b5b5c5 h1:wndND79llNLTZZW/Xcg9oKMk/NuGMo+pAX+LKg1mZF8=
github.com/horgh/irc v0.0.0-20190101204118-d089b0b5b5c5/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=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
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=

137
main.go
View File

@@ -15,12 +15,15 @@ import (
"time"
"github.com/horgh/irc"
"github.com/pkg/errors"
)
// Catbox holds the state for this local server.
// I put everything global to a server in an instance of struct rather than
// have global variables.
type Catbox struct {
Args *Args
// ConfigFile is the path to the config file.
ConfigFile string
@@ -85,7 +88,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
@@ -209,7 +214,7 @@ func main() {
os.Args[0], err)
}
cb, err := newCatbox(args.ConfigFile)
cb, err := newCatbox(args)
if err != nil {
log.Fatal(err)
}
@@ -239,9 +244,10 @@ func main() {
log.Printf("Server shutdown cleanly.")
}
func newCatbox(configFile string) (*Catbox, error) {
func newCatbox(args *Args) (*Catbox, error) {
cb := Catbox{
ConfigFile: configFile,
Args: args,
ConfigFile: args.ConfigFile,
LocalClients: make(map[uint64]*LocalClient),
LocalUsers: make(map[uint64]*LocalUser),
LocalServers: make(map[uint64]*LocalServer),
@@ -259,7 +265,11 @@ func newCatbox(configFile string) (*Catbox, error) {
ToServerChan: make(chan Event),
}
cfg, err := checkAndParseConfig(configFile)
cfg, err := checkAndParseConfig(
args.ConfigFile,
args.ServerName,
args.SID,
)
if err != nil {
return nil, fmt.Errorf("configuration problem: %s", err)
}
@@ -267,34 +277,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, // nolint: gosec,gas
// 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
@@ -385,7 +420,7 @@ func (cb *Catbox) start(listenFD int) error {
}
}()
log.Printf("catbox started")
log.Printf("catbox started (%s)", cb.Config.ServerName)
cb.eventLoop()
// We don't need to drain any channels. None close that will have any
@@ -605,16 +640,19 @@ func (cb *Catbox) introduceClient(conn net.Conn) {
client := NewLocalClient(cb, id, conn)
msgs := []string{
fmt.Sprintf("*** Processing your connection to %s",
cb.Config.ServerName),
}
cb.WG.Add(1)
go client.writeLoop()
sendAuthNotice(
client,
"*** Processing your connection to "+cb.Config.ServerName,
)
if client.isTLS() {
tlsVersion, tlsCipherSuite, err := client.getTLSState()
if err != nil {
log.Printf("Client %s: %s", client, err)
_ = conn.Close() // nolint: gosec
close(client.WriteChan)
return
}
@@ -628,48 +666,44 @@ func (cb *Catbox) introduceClient(conn net.Conn) {
"Your SSL/TLS version is %s. This server requires at least TLS 1.2. Contact %s if this is a problem.",
tlsVersion, cb.Config.AdminEmail)})
close(client.WriteChan)
cb.WG.Add(1)
go client.writeLoop()
return
}
msgs = append(msgs, fmt.Sprintf("*** Connected with %s (%s)", tlsVersion,
tlsCipherSuite))
sendAuthNotice(
client,
fmt.Sprintf("*** Connected with %s (%s)", tlsVersion, tlsCipherSuite),
)
}
msgs = append(msgs, "*** Looking up your hostname...")
sendAuthNotice(client, "*** Looking up your hostname...")
hostname := lookupHostname(context.TODO(), client.Conn.IP)
if len(hostname) > 0 {
msgs = append(msgs, "*** Found your hostname")
sendAuthNotice(client, "*** Found your hostname")
client.Hostname = hostname
} else {
msgs = append(msgs, "*** Couldn't look up your hostname")
}
for _, msg := range msgs {
client.WriteChan <- irc.Message{
Command: "NOTICE",
Params: []string{"AUTH", msg},
}
sendAuthNotice(client, "*** Couldn't look up your hostname")
}
// Inform the main server goroutine about the client.
//
// Do this after sending any messages to the client's channel as it is
// possible the channel will be closed by the server (such as during
// shutdown).
cb.newEvent(Event{Type: NewClientEvent, Client: client})
// Start read goroutine (endlessly read messages from the client) and write
// goroutine (endlessly write messages to the client).
cb.WG.Add(1)
go client.readLoop()
cb.WG.Add(1)
go client.writeLoop()
}()
}
func sendAuthNotice(c *LocalClient, m string) {
c.WriteChan <- irc.Message{
Command: "NOTICE",
Params: []string{"AUTH", m},
}
}
// Return true if the server is shutting down.
func (cb *Catbox) isShuttingDown() bool {
// No messages get sent to this channel, so if we receive a message on it,
@@ -1458,7 +1492,11 @@ func (cb *Catbox) quitRemoteUser(u *User, message string) {
//
// We could close listeners and open new ones. But nah.
func (cb *Catbox) rehash(byUser *User) {
cfg, err := checkAndParseConfig(cb.ConfigFile)
cfg, err := checkAndParseConfig(
cb.ConfigFile,
cb.Args.ServerName,
cb.Args.SID,
)
if err != nil {
cb.noticeOpers(fmt.Sprintf("Rehash: Configuration problem: %s", err))
return
@@ -1468,8 +1506,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:

View File

@@ -16,6 +16,8 @@ import (
"sync"
"syscall"
"time"
"github.com/pkg/errors"
)
// Catbox holds information about a harnessed catbox.
@@ -31,8 +33,7 @@ type Catbox struct {
LogChan <-chan string
}
var catboxDir = filepath.Join(os.Getenv("GOPATH"), "src", "github.com", "horgh",
"catbox")
const catboxDir = ".."
func harnessCatbox(
name,
@@ -250,9 +251,8 @@ func logReader(
}
}
if err := scanner.Err(); err != nil {
log.Fatalf("error scanning: %s", err)
}
// 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() {
@@ -283,11 +283,14 @@ func (c *Catbox) linkServer(other *Catbox) error {
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 c.rehash()
}
return nil
func (c *Catbox) rehash() error {
return errors.Wrap(
c.Command.Process.Signal(syscall.SIGHUP),
"error sending SIGHUP",
)
}
func waitForLog(ch <-chan string, re *regexp.Regexp) bool {

View File

@@ -7,6 +7,7 @@ import (
"time"
"github.com/horgh/irc"
"github.com/stretchr/testify/require"
)
// Test that clients get TS when running MODE on a channel they are on.
@@ -15,56 +16,72 @@ import (
// 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)
}
require.NoError(t, err, "harness catbox")
defer catbox1.stop()
catbox2, err := harnessCatbox("irc2.example.org", "002")
if err != nil {
t.Fatalf("error harnessing catbox: %s", err)
}
require.NoError(t, err, "harness catbox")
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)
}
err = catbox1.linkServer(catbox2)
require.NoError(t, err, "link catbox1 to catbox2")
err = catbox2.linkServer(catbox1)
require.NoError(t, err, "link catbox2 to catbox1")
// Wait until we link.
//
// Retry rehashing as I observed a failing build where the second server did
// not receive the SIGHUP, yet didn't exit. I'm not sure how that can happen
// other than perhaps a race in signal.Notify() such that the signal handler
// is registered so the HUP gets received but not delivered to the channel.
linkRE := regexp.MustCompile(`Established link to irc2\.`)
if !waitForLog(catbox1.LogChan, linkRE) {
t.Fatalf("failed to see servers link")
var attempts int
for {
if waitForLog(catbox1.LogChan, linkRE) {
break
}
attempts++
if attempts >= 5 {
require.Fail(t, "failed to link")
}
require.NoError(t, err, catbox1.rehash(), "rehash catbox1")
require.NoError(t, err, catbox2.rehash(), "rehash catbox2")
}
client1 := NewClient("client1", "127.0.0.1", catbox1.Port)
recvChan1, sendChan1, _, err := client1.Start()
if err != nil {
t.Fatalf("error starting client: %s", err)
}
require.NoError(t, err, "start client")
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")
}
require.NotNil(
t,
waitForMessage(
t,
recvChan1,
irc.Message{Command: irc.ReplyWelcome},
"welcome from %s",
client1.GetNick(),
),
"client gets welcome",
)
sendChan1 <- irc.Message{
Command: "JOIN",
Params: []string{"#test"},
}
if waitForMessage(
require.NotNil(
t,
recvChan1,
irc.Message{
Command: "JOIN",
Params: []string{"#test"},
},
"%s received JOIN #test", client1.GetNick(),
) == nil {
t.Fatalf("client1 did not receive JOIN message")
}
waitForMessage(
t,
recvChan1,
irc.Message{
Command: "JOIN",
Params: []string{"#test"},
},
"%s received JOIN #test", client1.GetNick(),
),
"client gets JOIN message",
)
sendChan1 <- irc.Message{
Command: "MODE",
@@ -78,17 +95,13 @@ func TestMODETS(t *testing.T) {
},
"%s received 329 response after MODE command", client1.GetNick(),
)
if creationTimeMessage == nil {
t.Fatalf("client1 did not receive 329 response")
}
require.NotNil(t, creationTimeMessage, "client receives 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)
}
require.NoError(t, err, "parse 329 response unixtime")
creationTimeString = creationTimeMessage.Params[2]
creationTime = time.Unix(ct, 0)
}
@@ -103,39 +116,49 @@ func TestMODETS(t *testing.T) {
},
)
if time.Since(creationTime) > 30*time.Second {
t.Fatalf("channel creation time is too far in the past: %s", creationTime)
}
require.True(
t,
time.Since(creationTime) <= 30*time.Second,
"channel creation time is new enough",
)
// 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)
}
require.NoError(t, err, "start client 2")
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")
}
require.NotNil(
t,
waitForMessage(
t,
recvChan2,
irc.Message{Command: irc.ReplyWelcome},
"welcome from %s",
client2.GetNick(),
),
"client 2 gets welcome",
)
sendChan2 <- irc.Message{
Command: "JOIN",
Params: []string{"#test"},
}
if waitForMessage(
require.NotNil(
t,
recvChan2,
irc.Message{
Command: "JOIN",
Params: []string{"#test"},
},
"%s received JOIN #test", client2.GetNick(),
) == nil {
t.Fatalf("client2 did not receive JOIN message")
}
waitForMessage(
t,
recvChan2,
irc.Message{
Command: "JOIN",
Params: []string{"#test"},
},
"%s received JOIN #test",
client2.GetNick(),
),
"client 2 gets JOIN message",
)
sendChan2 <- irc.Message{
Command: "MODE",
@@ -149,9 +172,7 @@ func TestMODETS(t *testing.T) {
},
"%s received 329 response after MODE command", client2.GetNick(),
)
if creationTimeMessage == nil {
t.Fatalf("client2 did not receive 329 response")
}
require.NotNil(t, creationTimeMessage, "client 2 receives 329 response")
messageIsEqual(
t,

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

@@ -1,24 +0,0 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof

View File

@@ -1,11 +0,0 @@
language: go
go_import_path: github.com/pkg/errors
go:
- 1.4.3
- 1.5.4
- 1.6.2
- 1.7.1
- tip
script:
- go test -v ./...

23
vendor/github.com/pkg/errors/LICENSE generated vendored
View File

@@ -1,23 +0,0 @@
Copyright (c) 2015, Dave Cheney <dave@cheney.net>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -1,52 +0,0 @@
# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors)
Package errors provides simple error handling primitives.
`go get github.com/pkg/errors`
The traditional error handling idiom in Go is roughly akin to
```go
if err != nil {
return err
}
```
which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error.
## Adding context to an error
The errors.Wrap function returns a new error that adds context to the original error. For example
```go
_, err := ioutil.ReadAll(r)
if err != nil {
return errors.Wrap(err, "read failed")
}
```
## Retrieving the cause of an error
Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`.
```go
type causer interface {
Cause() error
}
```
`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example:
```go
switch err := errors.Cause(err).(type) {
case *MyError:
// handle specifically
default:
// unknown error
}
```
[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors).
## Contributing
We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high.
Before proposing a change, please discuss your change by raising an issue.
## Licence
BSD-2-Clause

View File

@@ -1,32 +0,0 @@
version: build-{build}.{branch}
clone_folder: C:\gopath\src\github.com\pkg\errors
shallow_clone: true # for startup speed
environment:
GOPATH: C:\gopath
platform:
- x64
# http://www.appveyor.com/docs/installed-software
install:
# some helpful output for debugging builds
- go version
- go env
# pre-installed MinGW at C:\MinGW is 32bit only
# but MSYS2 at C:\msys64 has mingw64
- set PATH=C:\msys64\mingw64\bin;%PATH%
- gcc --version
- g++ --version
build_script:
- go install -v ./...
test_script:
- set PATH=C:\gopath\bin;%PATH%
- go test -v ./...
#artifacts:
# - path: '%GOPATH%\bin\*.exe'
deploy: off

View File

@@ -1,59 +0,0 @@
// +build go1.7
package errors
import (
"fmt"
"testing"
stderrors "errors"
)
func noErrors(at, depth int) error {
if at >= depth {
return stderrors.New("no error")
}
return noErrors(at+1, depth)
}
func yesErrors(at, depth int) error {
if at >= depth {
return New("ye error")
}
return yesErrors(at+1, depth)
}
func BenchmarkErrors(b *testing.B) {
var toperr error
type run struct {
stack int
std bool
}
runs := []run{
{10, false},
{10, true},
{100, false},
{100, true},
{1000, false},
{1000, true},
}
for _, r := range runs {
part := "pkg/errors"
if r.std {
part = "errors"
}
name := fmt.Sprintf("%s-stack-%d", part, r.stack)
b.Run(name, func(b *testing.B) {
var err error
f := yesErrors
if r.std {
f = noErrors
}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
err = f(0, r.stack)
}
b.StopTimer()
toperr = err
})
}
}

View File

@@ -1,269 +0,0 @@
// Package errors provides simple error handling primitives.
//
// The traditional error handling idiom in Go is roughly akin to
//
// if err != nil {
// return err
// }
//
// which applied recursively up the call stack results in error reports
// without context or debugging information. The errors package allows
// programmers to add context to the failure path in their code in a way
// that does not destroy the original value of the error.
//
// Adding context to an error
//
// The errors.Wrap function returns a new error that adds context to the
// original error by recording a stack trace at the point Wrap is called,
// and the supplied message. For example
//
// _, err := ioutil.ReadAll(r)
// if err != nil {
// return errors.Wrap(err, "read failed")
// }
//
// If additional control is required the errors.WithStack and errors.WithMessage
// functions destructure errors.Wrap into its component operations of annotating
// an error with a stack trace and an a message, respectively.
//
// Retrieving the cause of an error
//
// Using errors.Wrap constructs a stack of errors, adding context to the
// preceding error. Depending on the nature of the error it may be necessary
// to reverse the operation of errors.Wrap to retrieve the original error
// for inspection. Any error value which implements this interface
//
// type causer interface {
// Cause() error
// }
//
// can be inspected by errors.Cause. errors.Cause will recursively retrieve
// the topmost error which does not implement causer, which is assumed to be
// the original cause. For example:
//
// switch err := errors.Cause(err).(type) {
// case *MyError:
// // handle specifically
// default:
// // unknown error
// }
//
// causer interface is not exported by this package, but is considered a part
// of stable public API.
//
// Formatted printing of errors
//
// All error values returned from this package implement fmt.Formatter and can
// be formatted by the fmt package. The following verbs are supported
//
// %s print the error. If the error has a Cause it will be
// printed recursively
// %v see %s
// %+v extended format. Each Frame of the error's StackTrace will
// be printed in detail.
//
// Retrieving the stack trace of an error or wrapper
//
// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
// invoked. This information can be retrieved with the following interface.
//
// type stackTracer interface {
// StackTrace() errors.StackTrace
// }
//
// Where errors.StackTrace is defined as
//
// type StackTrace []Frame
//
// The Frame type represents a call site in the stack trace. Frame supports
// the fmt.Formatter interface that can be used for printing information about
// the stack trace of this error. For example:
//
// if err, ok := err.(stackTracer); ok {
// for _, f := range err.StackTrace() {
// fmt.Printf("%+s:%d", f)
// }
// }
//
// stackTracer interface is not exported by this package, but is considered a part
// of stable public API.
//
// See the documentation for Frame.Format for more details.
package errors
import (
"fmt"
"io"
)
// New returns an error with the supplied message.
// New also records the stack trace at the point it was called.
func New(message string) error {
return &fundamental{
msg: message,
stack: callers(),
}
}
// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
// Errorf also records the stack trace at the point it was called.
func Errorf(format string, args ...interface{}) error {
return &fundamental{
msg: fmt.Sprintf(format, args...),
stack: callers(),
}
}
// fundamental is an error that has a message and a stack, but no caller.
type fundamental struct {
msg string
*stack
}
func (f *fundamental) Error() string { return f.msg }
func (f *fundamental) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
io.WriteString(s, f.msg)
f.stack.Format(s, verb)
return
}
fallthrough
case 's':
io.WriteString(s, f.msg)
case 'q':
fmt.Fprintf(s, "%q", f.msg)
}
}
// WithStack annotates err with a stack trace at the point WithStack was called.
// If err is nil, WithStack returns nil.
func WithStack(err error) error {
if err == nil {
return nil
}
return &withStack{
err,
callers(),
}
}
type withStack struct {
error
*stack
}
func (w *withStack) Cause() error { return w.error }
func (w *withStack) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
fmt.Fprintf(s, "%+v", w.Cause())
w.stack.Format(s, verb)
return
}
fallthrough
case 's':
io.WriteString(s, w.Error())
case 'q':
fmt.Fprintf(s, "%q", w.Error())
}
}
// Wrap returns an error annotating err with a stack trace
// at the point Wrap is called, and the supplied message.
// If err is nil, Wrap returns nil.
func Wrap(err error, message string) error {
if err == nil {
return nil
}
err = &withMessage{
cause: err,
msg: message,
}
return &withStack{
err,
callers(),
}
}
// Wrapf returns an error annotating err with a stack trace
// at the point Wrapf is call, and the format specifier.
// If err is nil, Wrapf returns nil.
func Wrapf(err error, format string, args ...interface{}) error {
if err == nil {
return nil
}
err = &withMessage{
cause: err,
msg: fmt.Sprintf(format, args...),
}
return &withStack{
err,
callers(),
}
}
// WithMessage annotates err with a new message.
// If err is nil, WithMessage returns nil.
func WithMessage(err error, message string) error {
if err == nil {
return nil
}
return &withMessage{
cause: err,
msg: message,
}
}
type withMessage struct {
cause error
msg string
}
func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
func (w *withMessage) Cause() error { return w.cause }
func (w *withMessage) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
fmt.Fprintf(s, "%+v\n", w.Cause())
io.WriteString(s, w.msg)
return
}
fallthrough
case 's', 'q':
io.WriteString(s, w.Error())
}
}
// Cause returns the underlying cause of the error, if possible.
// An error value has a cause if it implements the following
// interface:
//
// type causer interface {
// Cause() error
// }
//
// If the error does not implement Cause, the original error will
// be returned. If the error is nil, nil will be returned without further
// investigation.
func Cause(err error) error {
type causer interface {
Cause() error
}
for err != nil {
cause, ok := err.(causer)
if !ok {
break
}
err = cause.Cause()
}
return err
}

View File

@@ -1,226 +0,0 @@
package errors
import (
"errors"
"fmt"
"io"
"reflect"
"testing"
)
func TestNew(t *testing.T) {
tests := []struct {
err string
want error
}{
{"", fmt.Errorf("")},
{"foo", fmt.Errorf("foo")},
{"foo", New("foo")},
{"string with format specifiers: %v", errors.New("string with format specifiers: %v")},
}
for _, tt := range tests {
got := New(tt.err)
if got.Error() != tt.want.Error() {
t.Errorf("New.Error(): got: %q, want %q", got, tt.want)
}
}
}
func TestWrapNil(t *testing.T) {
got := Wrap(nil, "no error")
if got != nil {
t.Errorf("Wrap(nil, \"no error\"): got %#v, expected nil", got)
}
}
func TestWrap(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{Wrap(io.EOF, "read error"), "client error", "client error: read error: EOF"},
}
for _, tt := range tests {
got := Wrap(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("Wrap(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want)
}
}
}
type nilError struct{}
func (nilError) Error() string { return "nil error" }
func TestCause(t *testing.T) {
x := New("error")
tests := []struct {
err error
want error
}{{
// nil error is nil
err: nil,
want: nil,
}, {
// explicit nil error is nil
err: (error)(nil),
want: nil,
}, {
// typed nil is nil
err: (*nilError)(nil),
want: (*nilError)(nil),
}, {
// uncaused error is unaffected
err: io.EOF,
want: io.EOF,
}, {
// caused error returns cause
err: Wrap(io.EOF, "ignored"),
want: io.EOF,
}, {
err: x, // return from errors.New
want: x,
}, {
WithMessage(nil, "whoops"),
nil,
}, {
WithMessage(io.EOF, "whoops"),
io.EOF,
}, {
WithStack(nil),
nil,
}, {
WithStack(io.EOF),
io.EOF,
}}
for i, tt := range tests {
got := Cause(tt.err)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want)
}
}
}
func TestWrapfNil(t *testing.T) {
got := Wrapf(nil, "no error")
if got != nil {
t.Errorf("Wrapf(nil, \"no error\"): got %#v, expected nil", got)
}
}
func TestWrapf(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"},
{Wrapf(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"},
}
for _, tt := range tests {
got := Wrapf(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want)
}
}
}
func TestErrorf(t *testing.T) {
tests := []struct {
err error
want string
}{
{Errorf("read error without format specifiers"), "read error without format specifiers"},
{Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"},
}
for _, tt := range tests {
got := tt.err.Error()
if got != tt.want {
t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want)
}
}
}
func TestWithStackNil(t *testing.T) {
got := WithStack(nil)
if got != nil {
t.Errorf("WithStack(nil): got %#v, expected nil", got)
}
}
func TestWithStack(t *testing.T) {
tests := []struct {
err error
want string
}{
{io.EOF, "EOF"},
{WithStack(io.EOF), "EOF"},
}
for _, tt := range tests {
got := WithStack(tt.err).Error()
if got != tt.want {
t.Errorf("WithStack(%v): got: %v, want %v", tt.err, got, tt.want)
}
}
}
func TestWithMessageNil(t *testing.T) {
got := WithMessage(nil, "no error")
if got != nil {
t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got)
}
}
func TestWithMessage(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{WithMessage(io.EOF, "read error"), "client error", "client error: read error: EOF"},
}
for _, tt := range tests {
got := WithMessage(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want)
}
}
}
// errors.New, etc values are not expected to be compared by value
// but the change in errors#27 made them incomparable. Assert that
// various kinds of errors have a functional equality operator, even
// if the result of that equality is always false.
func TestErrorEquality(t *testing.T) {
vals := []error{
nil,
io.EOF,
errors.New("EOF"),
New("EOF"),
Errorf("EOF"),
Wrap(io.EOF, "EOF"),
Wrapf(io.EOF, "EOF%d", 2),
WithMessage(nil, "whoops"),
WithMessage(io.EOF, "whoops"),
WithStack(io.EOF),
WithStack(nil),
}
for i := range vals {
for j := range vals {
_ = vals[i] == vals[j] // mustn't panic
}
}
}

View File

@@ -1,205 +0,0 @@
package errors_test
import (
"fmt"
"github.com/pkg/errors"
)
func ExampleNew() {
err := errors.New("whoops")
fmt.Println(err)
// Output: whoops
}
func ExampleNew_printf() {
err := errors.New("whoops")
fmt.Printf("%+v", err)
// Example output:
// whoops
// github.com/pkg/errors_test.ExampleNew_printf
// /home/dfc/src/github.com/pkg/errors/example_test.go:17
// testing.runExample
// /home/dfc/go/src/testing/example.go:114
// testing.RunExamples
// /home/dfc/go/src/testing/example.go:38
// testing.(*M).Run
// /home/dfc/go/src/testing/testing.go:744
// main.main
// /github.com/pkg/errors/_test/_testmain.go:106
// runtime.main
// /home/dfc/go/src/runtime/proc.go:183
// runtime.goexit
// /home/dfc/go/src/runtime/asm_amd64.s:2059
}
func ExampleWithMessage() {
cause := errors.New("whoops")
err := errors.WithMessage(cause, "oh noes")
fmt.Println(err)
// Output: oh noes: whoops
}
func ExampleWithStack() {
cause := errors.New("whoops")
err := errors.WithStack(cause)
fmt.Println(err)
// Output: whoops
}
func ExampleWithStack_printf() {
cause := errors.New("whoops")
err := errors.WithStack(cause)
fmt.Printf("%+v", err)
// Example Output:
// whoops
// github.com/pkg/errors_test.ExampleWithStack_printf
// /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55
// testing.runExample
// /usr/lib/go/src/testing/example.go:114
// testing.RunExamples
// /usr/lib/go/src/testing/example.go:38
// testing.(*M).Run
// /usr/lib/go/src/testing/testing.go:744
// main.main
// github.com/pkg/errors/_test/_testmain.go:106
// runtime.main
// /usr/lib/go/src/runtime/proc.go:183
// runtime.goexit
// /usr/lib/go/src/runtime/asm_amd64.s:2086
// github.com/pkg/errors_test.ExampleWithStack_printf
// /home/fabstu/go/src/github.com/pkg/errors/example_test.go:56
// testing.runExample
// /usr/lib/go/src/testing/example.go:114
// testing.RunExamples
// /usr/lib/go/src/testing/example.go:38
// testing.(*M).Run
// /usr/lib/go/src/testing/testing.go:744
// main.main
// github.com/pkg/errors/_test/_testmain.go:106
// runtime.main
// /usr/lib/go/src/runtime/proc.go:183
// runtime.goexit
// /usr/lib/go/src/runtime/asm_amd64.s:2086
}
func ExampleWrap() {
cause := errors.New("whoops")
err := errors.Wrap(cause, "oh noes")
fmt.Println(err)
// Output: oh noes: whoops
}
func fn() error {
e1 := errors.New("error")
e2 := errors.Wrap(e1, "inner")
e3 := errors.Wrap(e2, "middle")
return errors.Wrap(e3, "outer")
}
func ExampleCause() {
err := fn()
fmt.Println(err)
fmt.Println(errors.Cause(err))
// Output: outer: middle: inner: error
// error
}
func ExampleWrap_extended() {
err := fn()
fmt.Printf("%+v\n", err)
// Example output:
// error
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:47
// github.com/pkg/errors_test.ExampleCause_printf
// /home/dfc/src/github.com/pkg/errors/example_test.go:63
// testing.runExample
// /home/dfc/go/src/testing/example.go:114
// testing.RunExamples
// /home/dfc/go/src/testing/example.go:38
// testing.(*M).Run
// /home/dfc/go/src/testing/testing.go:744
// main.main
// /github.com/pkg/errors/_test/_testmain.go:104
// runtime.main
// /home/dfc/go/src/runtime/proc.go:183
// runtime.goexit
// /home/dfc/go/src/runtime/asm_amd64.s:2059
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer
}
func ExampleWrapf() {
cause := errors.New("whoops")
err := errors.Wrapf(cause, "oh noes #%d", 2)
fmt.Println(err)
// Output: oh noes #2: whoops
}
func ExampleErrorf_extended() {
err := errors.Errorf("whoops: %s", "foo")
fmt.Printf("%+v", err)
// Example output:
// whoops: foo
// github.com/pkg/errors_test.ExampleErrorf
// /home/dfc/src/github.com/pkg/errors/example_test.go:101
// testing.runExample
// /home/dfc/go/src/testing/example.go:114
// testing.RunExamples
// /home/dfc/go/src/testing/example.go:38
// testing.(*M).Run
// /home/dfc/go/src/testing/testing.go:744
// main.main
// /github.com/pkg/errors/_test/_testmain.go:102
// runtime.main
// /home/dfc/go/src/runtime/proc.go:183
// runtime.goexit
// /home/dfc/go/src/runtime/asm_amd64.s:2059
}
func Example_stackTrace() {
type stackTracer interface {
StackTrace() errors.StackTrace
}
err, ok := errors.Cause(fn()).(stackTracer)
if !ok {
panic("oops, err does not implement stackTracer")
}
st := err.StackTrace()
fmt.Printf("%+v", st[0:2]) // top two frames
// Example output:
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:47
// github.com/pkg/errors_test.Example_stackTrace
// /home/dfc/src/github.com/pkg/errors/example_test.go:127
}
func ExampleCause_printf() {
err := errors.Wrap(func() error {
return func() error {
return errors.Errorf("hello %s", fmt.Sprintf("world"))
}()
}(), "failed")
fmt.Printf("%v", err)
// Output: failed: hello world
}

View File

@@ -1,535 +0,0 @@
package errors
import (
"errors"
"fmt"
"io"
"regexp"
"strings"
"testing"
)
func TestFormatNew(t *testing.T) {
tests := []struct {
error
format string
want string
}{{
New("error"),
"%s",
"error",
}, {
New("error"),
"%v",
"error",
}, {
New("error"),
"%+v",
"error\n" +
"github.com/pkg/errors.TestFormatNew\n" +
"\t.+/github.com/pkg/errors/format_test.go:26",
}, {
New("error"),
"%q",
`"error"`,
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
}
}
func TestFormatErrorf(t *testing.T) {
tests := []struct {
error
format string
want string
}{{
Errorf("%s", "error"),
"%s",
"error",
}, {
Errorf("%s", "error"),
"%v",
"error",
}, {
Errorf("%s", "error"),
"%+v",
"error\n" +
"github.com/pkg/errors.TestFormatErrorf\n" +
"\t.+/github.com/pkg/errors/format_test.go:56",
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
}
}
func TestFormatWrap(t *testing.T) {
tests := []struct {
error
format string
want string
}{{
Wrap(New("error"), "error2"),
"%s",
"error2: error",
}, {
Wrap(New("error"), "error2"),
"%v",
"error2: error",
}, {
Wrap(New("error"), "error2"),
"%+v",
"error\n" +
"github.com/pkg/errors.TestFormatWrap\n" +
"\t.+/github.com/pkg/errors/format_test.go:82",
}, {
Wrap(io.EOF, "error"),
"%s",
"error: EOF",
}, {
Wrap(io.EOF, "error"),
"%v",
"error: EOF",
}, {
Wrap(io.EOF, "error"),
"%+v",
"EOF\n" +
"error\n" +
"github.com/pkg/errors.TestFormatWrap\n" +
"\t.+/github.com/pkg/errors/format_test.go:96",
}, {
Wrap(Wrap(io.EOF, "error1"), "error2"),
"%+v",
"EOF\n" +
"error1\n" +
"github.com/pkg/errors.TestFormatWrap\n" +
"\t.+/github.com/pkg/errors/format_test.go:103\n",
}, {
Wrap(New("error with space"), "context"),
"%q",
`"context: error with space"`,
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
}
}
func TestFormatWrapf(t *testing.T) {
tests := []struct {
error
format string
want string
}{{
Wrapf(io.EOF, "error%d", 2),
"%s",
"error2: EOF",
}, {
Wrapf(io.EOF, "error%d", 2),
"%v",
"error2: EOF",
}, {
Wrapf(io.EOF, "error%d", 2),
"%+v",
"EOF\n" +
"error2\n" +
"github.com/pkg/errors.TestFormatWrapf\n" +
"\t.+/github.com/pkg/errors/format_test.go:134",
}, {
Wrapf(New("error"), "error%d", 2),
"%s",
"error2: error",
}, {
Wrapf(New("error"), "error%d", 2),
"%v",
"error2: error",
}, {
Wrapf(New("error"), "error%d", 2),
"%+v",
"error\n" +
"github.com/pkg/errors.TestFormatWrapf\n" +
"\t.+/github.com/pkg/errors/format_test.go:149",
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
}
}
func TestFormatWithStack(t *testing.T) {
tests := []struct {
error
format string
want []string
}{{
WithStack(io.EOF),
"%s",
[]string{"EOF"},
}, {
WithStack(io.EOF),
"%v",
[]string{"EOF"},
}, {
WithStack(io.EOF),
"%+v",
[]string{"EOF",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:175"},
}, {
WithStack(New("error")),
"%s",
[]string{"error"},
}, {
WithStack(New("error")),
"%v",
[]string{"error"},
}, {
WithStack(New("error")),
"%+v",
[]string{"error",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:189",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:189"},
}, {
WithStack(WithStack(io.EOF)),
"%+v",
[]string{"EOF",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:197",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:197"},
}, {
WithStack(WithStack(Wrapf(io.EOF, "message"))),
"%+v",
[]string{"EOF",
"message",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:205",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:205",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:205"},
}, {
WithStack(Errorf("error%d", 1)),
"%+v",
[]string{"error1",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:216",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:216"},
}}
for i, tt := range tests {
testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true)
}
}
func TestFormatWithMessage(t *testing.T) {
tests := []struct {
error
format string
want []string
}{{
WithMessage(New("error"), "error2"),
"%s",
[]string{"error2: error"},
}, {
WithMessage(New("error"), "error2"),
"%v",
[]string{"error2: error"},
}, {
WithMessage(New("error"), "error2"),
"%+v",
[]string{
"error",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:244",
"error2"},
}, {
WithMessage(io.EOF, "addition1"),
"%s",
[]string{"addition1: EOF"},
}, {
WithMessage(io.EOF, "addition1"),
"%v",
[]string{"addition1: EOF"},
}, {
WithMessage(io.EOF, "addition1"),
"%+v",
[]string{"EOF", "addition1"},
}, {
WithMessage(WithMessage(io.EOF, "addition1"), "addition2"),
"%v",
[]string{"addition2: addition1: EOF"},
}, {
WithMessage(WithMessage(io.EOF, "addition1"), "addition2"),
"%+v",
[]string{"EOF", "addition1", "addition2"},
}, {
Wrap(WithMessage(io.EOF, "error1"), "error2"),
"%+v",
[]string{"EOF", "error1", "error2",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:272"},
}, {
WithMessage(Errorf("error%d", 1), "error2"),
"%+v",
[]string{"error1",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:278",
"error2"},
}, {
WithMessage(WithStack(io.EOF), "error"),
"%+v",
[]string{
"EOF",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:285",
"error"},
}, {
WithMessage(Wrap(WithStack(io.EOF), "inside-error"), "outside-error"),
"%+v",
[]string{
"EOF",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:293",
"inside-error",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:293",
"outside-error"},
}}
for i, tt := range tests {
testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true)
}
}
func TestFormatGeneric(t *testing.T) {
starts := []struct {
err error
want []string
}{
{New("new-error"), []string{
"new-error",
"github.com/pkg/errors.TestFormatGeneric\n" +
"\t.+/github.com/pkg/errors/format_test.go:315"},
}, {Errorf("errorf-error"), []string{
"errorf-error",
"github.com/pkg/errors.TestFormatGeneric\n" +
"\t.+/github.com/pkg/errors/format_test.go:319"},
}, {errors.New("errors-new-error"), []string{
"errors-new-error"},
},
}
wrappers := []wrapper{
{
func(err error) error { return WithMessage(err, "with-message") },
[]string{"with-message"},
}, {
func(err error) error { return WithStack(err) },
[]string{
"github.com/pkg/errors.(func·002|TestFormatGeneric.func2)\n\t" +
".+/github.com/pkg/errors/format_test.go:333",
},
}, {
func(err error) error { return Wrap(err, "wrap-error") },
[]string{
"wrap-error",
"github.com/pkg/errors.(func·003|TestFormatGeneric.func3)\n\t" +
".+/github.com/pkg/errors/format_test.go:339",
},
}, {
func(err error) error { return Wrapf(err, "wrapf-error%d", 1) },
[]string{
"wrapf-error1",
"github.com/pkg/errors.(func·004|TestFormatGeneric.func4)\n\t" +
".+/github.com/pkg/errors/format_test.go:346",
},
},
}
for s := range starts {
err := starts[s].err
want := starts[s].want
testFormatCompleteCompare(t, s, err, "%+v", want, false)
testGenericRecursive(t, err, want, wrappers, 3)
}
}
func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) {
got := fmt.Sprintf(format, arg)
gotLines := strings.SplitN(got, "\n", -1)
wantLines := strings.SplitN(want, "\n", -1)
if len(wantLines) > len(gotLines) {
t.Errorf("test %d: wantLines(%d) > gotLines(%d):\n got: %q\nwant: %q", n+1, len(wantLines), len(gotLines), got, want)
return
}
for i, w := range wantLines {
match, err := regexp.MatchString(w, gotLines[i])
if err != nil {
t.Fatal(err)
}
if !match {
t.Errorf("test %d: line %d: fmt.Sprintf(%q, err):\n got: %q\nwant: %q", n+1, i+1, format, got, want)
}
}
}
var stackLineR = regexp.MustCompile(`\.`)
// parseBlocks parses input into a slice, where:
// - incase entry contains a newline, its a stacktrace
// - incase entry contains no newline, its a solo line.
//
// Detecting stack boundaries only works incase the WithStack-calls are
// to be found on the same line, thats why it is optionally here.
//
// Example use:
//
// for _, e := range blocks {
// if strings.ContainsAny(e, "\n") {
// // Match as stack
// } else {
// // Match as line
// }
// }
//
func parseBlocks(input string, detectStackboundaries bool) ([]string, error) {
var blocks []string
stack := ""
wasStack := false
lines := map[string]bool{} // already found lines
for _, l := range strings.Split(input, "\n") {
isStackLine := stackLineR.MatchString(l)
switch {
case !isStackLine && wasStack:
blocks = append(blocks, stack, l)
stack = ""
lines = map[string]bool{}
case isStackLine:
if wasStack {
// Detecting two stacks after another, possible cause lines match in
// our tests due to WithStack(WithStack(io.EOF)) on same line.
if detectStackboundaries {
if lines[l] {
if len(stack) == 0 {
return nil, errors.New("len of block must not be zero here")
}
blocks = append(blocks, stack)
stack = l
lines = map[string]bool{l: true}
continue
}
}
stack = stack + "\n" + l
} else {
stack = l
}
lines[l] = true
case !isStackLine && !wasStack:
blocks = append(blocks, l)
default:
return nil, errors.New("must not happen")
}
wasStack = isStackLine
}
// Use up stack
if stack != "" {
blocks = append(blocks, stack)
}
return blocks, nil
}
func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format string, want []string, detectStackBoundaries bool) {
gotStr := fmt.Sprintf(format, arg)
got, err := parseBlocks(gotStr, detectStackBoundaries)
if err != nil {
t.Fatal(err)
}
if len(got) != len(want) {
t.Fatalf("test %d: fmt.Sprintf(%s, err) -> wrong number of blocks: got(%d) want(%d)\n got: %s\nwant: %s\ngotStr: %q",
n+1, format, len(got), len(want), prettyBlocks(got), prettyBlocks(want), gotStr)
}
for i := range got {
if strings.ContainsAny(want[i], "\n") {
// Match as stack
match, err := regexp.MatchString(want[i], got[i])
if err != nil {
t.Fatal(err)
}
if !match {
t.Fatalf("test %d: block %d: fmt.Sprintf(%q, err):\ngot:\n%q\nwant:\n%q\nall-got:\n%s\nall-want:\n%s\n",
n+1, i+1, format, got[i], want[i], prettyBlocks(got), prettyBlocks(want))
}
} else {
// Match as message
if got[i] != want[i] {
t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i])
}
}
}
}
type wrapper struct {
wrap func(err error) error
want []string
}
func prettyBlocks(blocks []string, prefix ...string) string {
var out []string
for _, b := range blocks {
out = append(out, fmt.Sprintf("%v", b))
}
return " " + strings.Join(out, "\n ")
}
func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, list []wrapper, maxDepth int) {
if len(beforeWant) == 0 {
panic("beforeWant must not be empty")
}
for _, w := range list {
if len(w.want) == 0 {
panic("want must not be empty")
}
err := w.wrap(beforeErr)
// Copy required cause append(beforeWant, ..) modified beforeWant subtly.
beforeCopy := make([]string, len(beforeWant))
copy(beforeCopy, beforeWant)
beforeWant := beforeCopy
last := len(beforeWant) - 1
var want []string
// Merge two stacks behind each other.
if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") {
want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...)
} else {
want = append(beforeWant, w.want...)
}
testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false)
if maxDepth > 0 {
testGenericRecursive(t, err, want, list, maxDepth-1)
}
}
}

178
vendor/github.com/pkg/errors/stack.go generated vendored
View File

@@ -1,178 +0,0 @@
package errors
import (
"fmt"
"io"
"path"
"runtime"
"strings"
)
// Frame represents a program counter inside a stack frame.
type Frame uintptr
// pc returns the program counter for this frame;
// multiple frames may have the same PC value.
func (f Frame) pc() uintptr { return uintptr(f) - 1 }
// file returns the full path to the file that contains the
// function for this Frame's pc.
func (f Frame) file() string {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return "unknown"
}
file, _ := fn.FileLine(f.pc())
return file
}
// line returns the line number of source code of the
// function for this Frame's pc.
func (f Frame) line() int {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return 0
}
_, line := fn.FileLine(f.pc())
return line
}
// Format formats the frame according to the fmt.Formatter interface.
//
// %s source file
// %d source line
// %n function name
// %v equivalent to %s:%d
//
// Format accepts flags that alter the printing of some verbs, as follows:
//
// %+s path of source file relative to the compile time GOPATH
// %+v equivalent to %+s:%d
func (f Frame) Format(s fmt.State, verb rune) {
switch verb {
case 's':
switch {
case s.Flag('+'):
pc := f.pc()
fn := runtime.FuncForPC(pc)
if fn == nil {
io.WriteString(s, "unknown")
} else {
file, _ := fn.FileLine(pc)
fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file)
}
default:
io.WriteString(s, path.Base(f.file()))
}
case 'd':
fmt.Fprintf(s, "%d", f.line())
case 'n':
name := runtime.FuncForPC(f.pc()).Name()
io.WriteString(s, funcname(name))
case 'v':
f.Format(s, 's')
io.WriteString(s, ":")
f.Format(s, 'd')
}
}
// StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
type StackTrace []Frame
func (st StackTrace) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
switch {
case s.Flag('+'):
for _, f := range st {
fmt.Fprintf(s, "\n%+v", f)
}
case s.Flag('#'):
fmt.Fprintf(s, "%#v", []Frame(st))
default:
fmt.Fprintf(s, "%v", []Frame(st))
}
case 's':
fmt.Fprintf(s, "%s", []Frame(st))
}
}
// stack represents a stack of program counters.
type stack []uintptr
func (s *stack) Format(st fmt.State, verb rune) {
switch verb {
case 'v':
switch {
case st.Flag('+'):
for _, pc := range *s {
f := Frame(pc)
fmt.Fprintf(st, "\n%+v", f)
}
}
}
}
func (s *stack) StackTrace() StackTrace {
f := make([]Frame, len(*s))
for i := 0; i < len(f); i++ {
f[i] = Frame((*s)[i])
}
return f
}
func callers() *stack {
const depth = 32
var pcs [depth]uintptr
n := runtime.Callers(3, pcs[:])
var st stack = pcs[0:n]
return &st
}
// funcname removes the path prefix component of a function's name reported by func.Name().
func funcname(name string) string {
i := strings.LastIndex(name, "/")
name = name[i+1:]
i = strings.Index(name, ".")
return name[i+1:]
}
func trimGOPATH(name, file string) string {
// Here we want to get the source file path relative to the compile time
// GOPATH. As of Go 1.6.x there is no direct way to know the compiled
// GOPATH at runtime, but we can infer the number of path segments in the
// GOPATH. We note that fn.Name() returns the function name qualified by
// the import path, which does not include the GOPATH. Thus we can trim
// segments from the beginning of the file path until the number of path
// separators remaining is one more than the number of path separators in
// the function name. For example, given:
//
// GOPATH /home/user
// file /home/user/src/pkg/sub/file.go
// fn.Name() pkg/sub.Type.Method
//
// We want to produce:
//
// pkg/sub/file.go
//
// From this we can easily see that fn.Name() has one less path separator
// than our desired output. We count separators from the end of the file
// path until it finds two more than in the function name and then move
// one character forward to preserve the initial path segment without a
// leading separator.
const sep = "/"
goal := strings.Count(name, sep) + 2
i := len(file)
for n := 0; n < goal; n++ {
i = strings.LastIndex(file[:i], sep)
if i == -1 {
// not enough separators found, set i so that the slice expression
// below leaves file unmodified
i = -len(sep)
break
}
}
// get back to 0 or trim the leading separator
file = file[i+len(sep):]
return file
}

View File

@@ -1,292 +0,0 @@
package errors
import (
"fmt"
"runtime"
"testing"
)
var initpc, _, _, _ = runtime.Caller(0)
func TestFrameLine(t *testing.T) {
var tests = []struct {
Frame
want int
}{{
Frame(initpc),
9,
}, {
func() Frame {
var pc, _, _, _ = runtime.Caller(0)
return Frame(pc)
}(),
20,
}, {
func() Frame {
var pc, _, _, _ = runtime.Caller(1)
return Frame(pc)
}(),
28,
}, {
Frame(0), // invalid PC
0,
}}
for _, tt := range tests {
got := tt.Frame.line()
want := tt.want
if want != got {
t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got)
}
}
}
type X struct{}
func (x X) val() Frame {
var pc, _, _, _ = runtime.Caller(0)
return Frame(pc)
}
func (x *X) ptr() Frame {
var pc, _, _, _ = runtime.Caller(0)
return Frame(pc)
}
func TestFrameFormat(t *testing.T) {
var tests = []struct {
Frame
format string
want string
}{{
Frame(initpc),
"%s",
"stack_test.go",
}, {
Frame(initpc),
"%+s",
"github.com/pkg/errors.init\n" +
"\t.+/github.com/pkg/errors/stack_test.go",
}, {
Frame(0),
"%s",
"unknown",
}, {
Frame(0),
"%+s",
"unknown",
}, {
Frame(initpc),
"%d",
"9",
}, {
Frame(0),
"%d",
"0",
}, {
Frame(initpc),
"%n",
"init",
}, {
func() Frame {
var x X
return x.ptr()
}(),
"%n",
`\(\*X\).ptr`,
}, {
func() Frame {
var x X
return x.val()
}(),
"%n",
"X.val",
}, {
Frame(0),
"%n",
"",
}, {
Frame(initpc),
"%v",
"stack_test.go:9",
}, {
Frame(initpc),
"%+v",
"github.com/pkg/errors.init\n" +
"\t.+/github.com/pkg/errors/stack_test.go:9",
}, {
Frame(0),
"%v",
"unknown:0",
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.Frame, tt.format, tt.want)
}
}
func TestFuncname(t *testing.T) {
tests := []struct {
name, want string
}{
{"", ""},
{"runtime.main", "main"},
{"github.com/pkg/errors.funcname", "funcname"},
{"funcname", "funcname"},
{"io.copyBuffer", "copyBuffer"},
{"main.(*R).Write", "(*R).Write"},
}
for _, tt := range tests {
got := funcname(tt.name)
want := tt.want
if got != want {
t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got)
}
}
}
func TestTrimGOPATH(t *testing.T) {
var tests = []struct {
Frame
want string
}{{
Frame(initpc),
"github.com/pkg/errors/stack_test.go",
}}
for i, tt := range tests {
pc := tt.Frame.pc()
fn := runtime.FuncForPC(pc)
file, _ := fn.FileLine(pc)
got := trimGOPATH(fn.Name(), file)
testFormatRegexp(t, i, got, "%s", tt.want)
}
}
func TestStackTrace(t *testing.T) {
tests := []struct {
err error
want []string
}{{
New("ooh"), []string{
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:172",
},
}, {
Wrap(New("ooh"), "ahh"), []string{
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:177", // this is the stack of Wrap, not New
},
}, {
Cause(Wrap(New("ooh"), "ahh")), []string{
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:182", // this is the stack of New
},
}, {
func() error { return New("ooh") }(), []string{
`github.com/pkg/errors.(func·009|TestStackTrace.func1)` +
"\n\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New's caller
},
}, {
Cause(func() error {
return func() error {
return Errorf("hello %s", fmt.Sprintf("world"))
}()
}()), []string{
`github.com/pkg/errors.(func·010|TestStackTrace.func2.1)` +
"\n\t.+/github.com/pkg/errors/stack_test.go:196", // this is the stack of Errorf
`github.com/pkg/errors.(func·011|TestStackTrace.func2)` +
"\n\t.+/github.com/pkg/errors/stack_test.go:197", // this is the stack of Errorf's caller
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:198", // this is the stack of Errorf's caller's caller
},
}}
for i, tt := range tests {
x, ok := tt.err.(interface {
StackTrace() StackTrace
})
if !ok {
t.Errorf("expected %#v to implement StackTrace() StackTrace", tt.err)
continue
}
st := x.StackTrace()
for j, want := range tt.want {
testFormatRegexp(t, i, st[j], "%+v", want)
}
}
}
func stackTrace() StackTrace {
const depth = 8
var pcs [depth]uintptr
n := runtime.Callers(1, pcs[:])
var st stack = pcs[0:n]
return st.StackTrace()
}
func TestStackTraceFormat(t *testing.T) {
tests := []struct {
StackTrace
format string
want string
}{{
nil,
"%s",
`\[\]`,
}, {
nil,
"%v",
`\[\]`,
}, {
nil,
"%+v",
"",
}, {
nil,
"%#v",
`\[\]errors.Frame\(nil\)`,
}, {
make(StackTrace, 0),
"%s",
`\[\]`,
}, {
make(StackTrace, 0),
"%v",
`\[\]`,
}, {
make(StackTrace, 0),
"%+v",
"",
}, {
make(StackTrace, 0),
"%#v",
`\[\]errors.Frame{}`,
}, {
stackTrace()[:2],
"%s",
`\[stack_test.go stack_test.go\]`,
}, {
stackTrace()[:2],
"%v",
`\[stack_test.go:225 stack_test.go:272\]`,
}, {
stackTrace()[:2],
"%+v",
"\n" +
"github.com/pkg/errors.stackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:225\n" +
"github.com/pkg/errors.TestStackTraceFormat\n" +
"\t.+/github.com/pkg/errors/stack_test.go:276",
}, {
stackTrace()[:2],
"%#v",
`\[\]errors.Frame{stack_test.go:225, stack_test.go:284}`,
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.StackTrace, tt.format, tt.want)
}
}

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"