summaryrefslogtreecommitdiff
path: root/xN/xN.go
blob: bdec3dd2cc4bcd9eaae68c49f973eeafbd743b48 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//
// Copyright (c) 2024, Přemysl Eric Janouch <p@janouch.name>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//

// xN is a simple IRC notifier.
package main

import (
	"bufio"
	"bytes"
	"crypto/tls"
	"errors"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"net/url"
	"os"
	"os/user"
	"strconv"
	"strings"
)

const projectName = "xN"

var projectVersion = "?"

var debugMode = false

type parameters struct {
	conn      net.Conn // underlying network connection
	username  string   // nickname + username + realname
	password  string   // server password
	target    string   // where to send text
	isuser    bool     // the target is a user rather than a channel
	chankey   string   // channel key
	skipjoin  bool     // whether to send external messages to channels
	usenotice bool     // whether to use NOTICE rather than PRIVMSG
	message   []string // lines of the message to send
}

func (p *parameters) send(command string, args ...string) error {
	var buf bytes.Buffer
	buf.WriteString(command)
	for i, arg := range args {
		buf.WriteRune(' ')
		if i+1 == len(args) {
			buf.WriteRune(':')
		}
		buf.WriteString(arg)
	}
	buf.WriteString("\r\n")
	_, err := p.conn.Write(buf.Bytes())
	return err
}

const (
	rplWELCOME       = "001"
	errNICKNAMEINUSE = "433"
)

func notify(p *parameters) error {
	// The intro should comfortably fit in the TCP send buffer whole.
	if p.password != "" {
		p.send("PASS", p.password)
	}
	p.send("USER", p.username, "0", "*", p.username)
	p.send("NICK", p.username)

	scanner, nickCounter, issue := bufio.NewScanner(p.conn), 1, ""
	for scanner.Scan() {
		if debugMode {
			log.Println(scanner.Text())
		}

		m := ircParseMessage(scanner.Text())
		switch m.command {
		case "PING":
			p.send("PONG", m.params...)
		case rplWELCOME:
			if !p.isuser && !p.skipjoin {
				if p.chankey != "" {
					p.send("JOIN", p.target, p.chankey)
				} else {
					p.send("JOIN", p.target)
				}
			}
			for _, line := range p.message {
				if p.usenotice {
					p.send("NOTICE", p.target, line)
				} else {
					p.send("PRIVMSG", p.target, line)
				}
			}
			p.send("QUIT")
		case errNICKNAMEINUSE:
			p.send("NICK", fmt.Sprintf("%s%d", p.username, nickCounter))
			nickCounter++
		default:
			// Prevent hanging on unsuccessful registrations.
			numeric, _ := strconv.Atoi(m.command)
			if numeric >= 400 && numeric <= 599 {
				if len(m.params) > 1 {
					issue = strings.Join(m.params[1:], " ")
				} else {
					issue = strings.Join(m.params, " ")
				}
				p.send("QUIT")
			}
		}
	}
	if err := scanner.Err(); err != nil {
		return err
	}
	if issue != "" {
		return errors.New(issue)
	}
	return nil
}

func parse(rawURL string, text []byte) (
	p parameters, connect func() (net.Conn, error), err error) {
	u, err := url.Parse(rawURL)
	if err != nil {
		return p, nil, err
	} else if !u.IsAbs() || u.Opaque != "" {
		return p, nil, errors.New("need an absolute URL")
	} else if u.Path == "/" && u.Fragment != "" {
		// Try to handle the common but degenerate case.
		fragment := "%23" + u.Fragment
		u.Fragment, u.RawFragment = "", ""
		if u, err = url.Parse(u.String() + fragment); err != nil {
			return p, nil, err
		}
	}

	// Figure out registration details.
	p.username = projectName
	if u, _ := user.Current(); u != nil {
		p.username = u.Username
	}
	if u.User.Username() != "" {
		p.username = u.User.Username()
	}

	p.password, _ = u.User.Password()

	// Figure out the target, which for our intents must accept messages.
	path, _ := strings.CutPrefix(u.Path, "/")
	elements := strings.Split(path, ",")
	if path == "" || elements[0] == "" {
		return p, nil, errors.New("unspecified entity")
	}

	// The last entity type wins.
	p.target, p.isuser = elements[0], false
	for _, typ := range elements[1:] {
		switch typ {
		case "isuser":
			p.isuser = true
		case "ischannel":
			p.isuser = false
		case "isserver":
			// We do not support network names, and this is the default.
		default:
			return p, nil, errors.New("unsupported type: " + typ)
		}
	}
	if p.isuser {
		if i := strings.IndexAny(p.target, "!@"); i != -1 {
			p.target = p.target[:i]
		}
	} else if !strings.HasPrefix(p.target, "#") {
		// TODO(p): We should consult RPL_ISUPPORT rather than guess,
		// though other prefixes are rare.
		p.target = "#" + p.target
	}

	// Note that the draft RFC wants these to be case-insensitive.
	p.chankey = u.Query().Get("key")
	// Being able to skip channel join is our own requirement and invention,
	// as are notices (names taken from Travis CI configuration).
	p.skipjoin = u.Query().Has("skipjoin")
	p.usenotice = u.Query().Has("usenotice")

	// Ensure valid LF-separated UTF-8, and split it at lines.
	sanitized := strings.ReplaceAll(string([]rune(string(text))), "\r", "\n")
	for _, line := range strings.Split(sanitized, "\n") {
		if line != "" {
			p.message = append(p.message, line)
		}
	}

	hostname, port := u.Hostname(), u.Port()
	switch u.Scheme {
	case "irc":
		if port == "" {
			port = "6667"
		}
		connect = func() (net.Conn, error) {
			return net.Dial("tcp", net.JoinHostPort(hostname, port))
		}
	case "ircs":
		if port == "" {
			port = "6697"
		}
		connect = func() (net.Conn, error) {
			return tls.Dial("tcp", net.JoinHostPort(hostname, port), nil)
		}
	default:
		err = errors.New("unsupported scheme: " + u.Scheme)
	}
	return
}

// notifyByURL sends the given text to the IRC server specified by a URL.
// See draft-butcher-irc-url-04.txt for the URL scheme specification
// this function loosely follows.
func notifyByURL(rawURL string, text []byte) error {
	p, connect, err := parse(rawURL, text)
	if p.conn, err = connect(); err != nil {
		return err
	}
	defer p.conn.Close()
	return notify(&p)
}

func main() {
	flag.BoolVar(&debugMode, "debug", false, "run in verbose debug mode")
	version := flag.Bool("version", false, "show version and exit")

	flag.Usage = func() {
		f := flag.CommandLine.Output()
		fmt.Fprintf(f, "Usage: %s [OPTION]... URL...\n", os.Args[0])
		flag.PrintDefaults()
	}
	flag.Parse()
	if flag.NArg() < 1 {
		flag.Usage()
		os.Exit(2)
	}

	if *version {
		fmt.Printf("%s %s\n", projectName, projectVersion)
		return
	}

	text, err := io.ReadAll(os.Stdin)
	if err != nil {
		log.Fatalln(err)
	}

	status := 0
	for _, rawURL := range flag.Args() {
		if err := notifyByURL(rawURL, text); err != nil {
			status = 1

			var ue *url.Error
			if errors.As(err, &ue) {
				log.Println(err)
			} else {
				log.Printf("notify %q: %s\n", rawURL, err)
			}
		}
	}
	os.Exit(status)
}