]> git.gir.st - ircpipe.git/blob - ircpipe.c
simplify sasl handling
[ircpipe.git] / ircpipe.c
1 #define _POSIX_C_SOURCE 200809L /* getopt(>=2), dprintf(>=200809L), strtok_r(*), getaddrinfo(>=200112L) */
2 #include <netdb.h>
3 #include <poll.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <sys/types.h>
9 #include <sys/socket.h>
10 #include <netdb.h>
11
12 #include <tls.h>
13
14 #define DEFAULT_PING 60000 /*ms*/
15 #define DEFAULT_TIMEOUT 2000 /*ms*/
16 #define DEFAULT_TLS NO_TLS
17 #define DEFAULT_PORT_TCP "6667"
18 #define DEFAULT_PORT_TLS "6697"
19
20 #define POLL_TIMEOUT 100
21
22 #define STR_(x) #x
23 #define STR(x) STR_(x)
24 #define OR_DIE < 0 && (perror(__FILE__ ":" STR(__LINE__)), exit(1), 0)
25 #define OR_DIE_gai(err) if (err) {fprintf(stderr, __FILE__ ":" STR(__LINE__) ": %s\n", gai_strerror(err));exit(1);}
26 #define OR_DIE_tls(ctx) < 0 && (exit((fprintf(stderr, __FILE__ ":" STR(__LINE__) ": %s\n", tls_error(ctx)), 1)), 0)
27
28 enum pass_type_e {
29 NO_PASSWD,
30 SERVER_PASSWD,
31 SASL_PLAIN_PASSWD
32 };
33
34 enum tls_use_e {
35 NO_TLS,
36 USE_TLS,
37 INSECURE_TLS
38 };
39
40 typedef struct {
41 int fd; /* always contains the underlying file descriptor */
42 struct tls *tls; /* tls context, or NULL with plain socket */
43 } sock_t;
44 #define _IMPLFN(fn, sock, buf, sz) ( \
45 sock.tls \
46 ? tls_ ## fn(sock.tls, buf, sz) \
47 : fn(sock.fd, buf, sz) \
48 )
49 #define READ(sock, buf, sz) _IMPLFN(read, sock, buf, sz)
50 #define WRITE(sock, buf, sz) _IMPLFN(write, sock, buf, sz)
51
52 void irc_help(const char *exe, const int code) {
53 fprintf(stderr, "Usage: %s [-pP] [-sSk] [-n NICK] [-j CHAN] HOST [PORT]\n", exe);
54 exit(code);
55 }
56
57 sock_t irc_connect(const char *host, const char *port, const int tls, const char *ca_file) {
58 sock_t sock;
59 struct addrinfo *results, *r;
60
61 int err = getaddrinfo(host, port, NULL, &results); OR_DIE_gai(err); /*unable to resolve*/
62
63 for (r = results; r != NULL; r = r->ai_next) {
64 sock.fd = socket(r->ai_family, SOCK_STREAM, 0);
65 if (sock.fd < 0) continue; /* try next; todo: should check errno */
66
67 if (connect(sock.fd, r->ai_addr, r->ai_addrlen) == 0)
68 break; /* successfully connected */
69
70 close(sock.fd); /* failed, try next addr */
71 }
72
73 if (r == NULL) {
74 /* all failed; abort. */
75 sock.fd = -1;
76 } else {
77 /* connection established. */
78 if (tls != NO_TLS) {
79 struct tls *ctx = tls_client();
80 struct tls_config *cfg = tls_config_new();
81
82 if (tls == INSECURE_TLS) {
83 tls_config_insecure_noverifycert(cfg);
84 tls_config_insecure_noverifyname(cfg);
85 tls_config_insecure_noverifytime(cfg);
86 tls_config_set_ciphers(cfg, "legacy"); /* even more: 'insecure' */
87 }
88 tls_config_set_dheparams(cfg, "auto") OR_DIE_tls(ctx);
89 if (ca_file) tls_config_set_ca_file(cfg, ca_file) OR_DIE_tls(ctx);
90 /* todo: if ca_file ends in /, call tls_config_set_ca_path() instead */
91 /* todo: otherwise, set to tls_default_ca_cert_file() iff libtls (not libretls) */
92
93 tls_configure(ctx, cfg) OR_DIE_tls(ctx);
94 tls_config_free(cfg);
95 tls_connect_socket(ctx, sock.fd, host) OR_DIE_tls(ctx);
96 tls_handshake(ctx) OR_DIE_tls(ctx);
97
98 sock.tls = ctx;
99 } else sock.tls = NULL;
100 /* connect timeout here */
101 }
102
103 freeaddrinfo(results);
104 return sock;
105 }
106
107 enum { /* requested command: */
108 NO_CMD = 0,
109 NICK = 1<<0,
110 JOIN = 1<<1,
111 PING = 1<<2,
112 ERRS = 1<<3
113 };
114 int irc_answer(const sock_t sock, char *buf, const unsigned int command) {
115 unsigned int seen = 0;
116 char *saveptr;
117 char *line = strtok_r(buf, "\r\n", &saveptr);
118 /*TODO: it often happens that we take multiple calls to read() all the available lines (e.g. large motd, NAMES message). when this happens, one call to read() will return an incomplete line, and the next will start in the middle of a line. this can't be parsed properly! we need to check if the last line ends with a newline. that's hard because we use strtok which removes newlines. on the second read we should either skip over the first partial line or better, defer parsing the last line of the first read until we have the complete line.*/
119 do {
120 /* skip over prefix (servername): */
121 if (line[0] == ':')
122 while (*line && *line++ != ' ');
123
124 /* look for command responses or error numerics, if required: */
125 switch (command) {
126 case PING: seen |= PING * (strncmp(line, "PONG ", 5)==0); break;
127 case JOIN: seen |= JOIN * (strncmp(line, "JOIN ", 5)==0);
128 seen |= ERRS * (strncmp(line, "403 ", 4)==0);
129 seen |= ERRS * (strncmp(line, "405 ", 4)==0);
130 seen |= ERRS * (strncmp(line, "471 ", 4)==0);
131 seen |= ERRS * (strncmp(line, "473 ", 4)==0);
132 seen |= ERRS * (strncmp(line, "474 ", 4)==0);
133 seen |= ERRS * (strncmp(line, "475 ", 4)==0);
134 seen |= ERRS * (strncmp(line, "476 ", 4)==0);
135 seen |= ERRS * (strncmp(line, "477 ", 4)==0); break;
136 case NICK: seen |= NICK * (strncmp(line, "001 ", 4)==0);
137 seen |= ERRS * (strncmp(line, "432 ", 4)==0);
138 seen |= ERRS * (strncmp(line, "433 ", 4)==0);
139 seen |= ERRS * (strncmp(line, "436 ", 4)==0);
140 seen |= ERRS * (strncmp(line, "464 ", 4)==0);
141 seen |= ERRS * (strncmp(line, "902 ", 4)==0);
142 seen |= ERRS * (strncmp(line, "904 ", 4)==0); break;
143 }
144 /* look for common error numerics if any command was given */
145 if (command & (NICK|JOIN)) {
146 seen |= ERRS * (strncmp(line, "400 ", 4)==0);
147 seen |= ERRS * (strncmp(line, "421 ", 4)==0);
148 seen |= ERRS * (strncmp(line, "465 ", 4)==0);
149 }
150 /* always look for a fatal error */
151 if (strncmp(line, "ERROR ", 6)==0) seen |= ERRS;
152
153 if (seen & ERRS) {
154 fprintf(stderr, __FILE__ ":%d: %s\n", __LINE__, line);
155 exit(1);
156 }
157
158 /* reply to pings: */
159 if (strncmp(line, "PING ", 5) == 0) {
160 line[1] = 'O'; /* PING :foo -> PONG :foo */
161 WRITE(sock, line, strlen(line));
162 WRITE(sock, "\r\n", 2);
163 }
164 } while ((line = strtok_r(NULL, "\r\n", &saveptr)));
165
166 return seen;
167 }
168
169 int irc_base64(char *buf, int n) {
170 const char *b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
171 int i, o, v, l = ((n+(3-n%3)%3)/3)*4;
172 buf[n+1] = buf[n+2] = buf[l] = '\0';
173 for (i=(n+(3-n%3)%3)-3, o=l-4; i>=0 && o>=0; i-=3, o-=4) {
174 v = buf[i+0]<<16 | buf[i+1]<<8 | buf[i+2]<<0;
175 buf[o+0] = b[v>>18 & 0x3f];
176 buf[o+1] = b[v>>12 & 0x3f];
177 buf[o+2] = (i+1<n)? b[v>>06 & 0x3f]:'=';
178 buf[o+3] = (i+2<n)? b[v>>00 & 0x3f]:'=';
179 }
180 return l;
181 }
182
183 int irc_setup(const sock_t sock, const int outfd, const char *nick, const char *pass, int pass_type, const char *chan) {
184 char buf[BUFSIZ];
185 int n;
186 struct pollfd fds[1];
187 fds[0].fd = sock.fd;
188 fds[0].events = POLLIN;
189
190 if (pass_type == SASL_PLAIN_PASSWD) {
191 n = snprintf(buf, BUFSIZ, "CAP REQ :sasl\r\n");
192 WRITE(sock, buf, n);
193 } else if (pass_type == SERVER_PASSWD) {
194 n = snprintf(buf, BUFSIZ, "PASS %s\r\n", pass);
195 WRITE(sock, buf, n);
196 }
197
198 n = snprintf(buf, BUFSIZ, "NICK %s\r\n", nick);
199 WRITE(sock, buf, n);
200 n = snprintf(buf, BUFSIZ, "USER %s 0 * :%s\r\n", nick, nick);
201 WRITE(sock, buf, n);
202
203 if (pass_type == SASL_PLAIN_PASSWD) {
204 /* TODO: assert strlen(pass) < 300 or abort */
205 /* should wait for 'CAP <nick|*> ACK :<...>' */
206 WRITE(sock, "AUTHENTICATE PLAIN\r\n", 20);
207 /* server sends 'AUTHENTICATE +' */
208 /* split base64-output into 400 byte chunks; if last is exactly
209 400 bytes, send empty msg ('+') afterwards */
210 n = snprintf(buf, BUFSIZ, "AUTHENTICATE %s%c%s%c%s", nick, 0, nick, 0, pass);
211 n = irc_base64(buf+13, n-13)+13; /*13==strlen("AUTHENTICATE ")*/
212 n += snprintf(buf+n, BUFSIZ-n, "\r\n");
213 WRITE(sock, buf, n);
214 /* wait for response 900+903 (ok) or 902/904 (err) */
215 WRITE(sock, "CAP END\r\n", 9);
216 }
217
218 /* block until we get a RPL_WELCOME or an error: */
219 for (;;) {
220 if (poll(fds, 1, POLL_TIMEOUT)) {
221 n = READ(sock, buf, BUFSIZ); buf[n] = '\0';
222 write(outfd, buf, n);
223 n = irc_answer(sock, buf, NICK);
224 if (n & NICK) break;
225 else if (n & ERRS) return -1;
226 }
227 }
228
229 if (chan) {
230 n = snprintf(buf, BUFSIZ, "JOIN %s\r\n", chan);
231 WRITE(sock, buf, n);
232
233 /* block until we get a JOIN response or an error: */
234 /* todo: dedup this block with NICK/RPL_WELCOME */
235 for (;;) {
236 if (poll(fds, 1, POLL_TIMEOUT)) {
237 n = READ(sock, buf, BUFSIZ); buf[n] = '\0';
238 write(outfd, buf, n);
239 n = irc_answer(sock, buf, JOIN);
240 if (n & JOIN) break;
241 else if (n & ERRS) return -1;
242 }
243 }
244 }
245
246 return 0;
247 }
248
249 int irc_poll(const sock_t sock, const int infd, const int outfd) {
250 int n;
251 char buf[BUFSIZ];
252 enum { IRC, CLI };
253 struct pollfd fds[2];
254 fds[IRC].fd = sock.fd;
255 fds[IRC].events = POLLIN;
256 fds[CLI].fd = infd;
257 fds[CLI].events = POLLIN;
258
259 for (;;) {
260 poll(fds, 2, POLL_TIMEOUT) OR_DIE;
261
262 /* XXX: long responses don't get fully processed until user input */
263 /* XXX: must handle TLS_WANT_POLLIN and TLS_WANT_POLLOUT for READ and WRITE! */
264 if (fds[IRC].revents & POLLIN) {
265 n = READ(sock, buf, BUFSIZ); buf[n] = '\0';
266 if (n == 0) return -1; /* server closed connection */
267 fds[IRC].events = POLLIN | (n==TLS_WANT_POLLOUT?POLLOUT:0);
268 write(outfd, buf, n);
269 irc_answer(sock, buf, NO_CMD);
270 /* update last-msg-rcvd here */
271 }
272 if (fds[CLI].revents & POLLIN) {
273 n = read(infd, buf, BUFSIZ); buf[n] = '\0';
274 if (n == 0) return 0; /* we closed connection */
275 n = WRITE(sock, buf, n);
276 fds[IRC].events = POLLIN | (n==TLS_WANT_POLLOUT?POLLOUT:0);
277 }
278 if (fds[IRC].revents & POLLOUT) { /* needed for TLS only */
279 n = WRITE(sock, buf, n);
280 fds[IRC].events = POLLIN | (n==TLS_WANT_POLLOUT?POLLOUT:0);
281 }
282 /* TODO: if read/write on either irc or cli returns -1 and errno is EAGAIN or EINTR, retry. otherwise, return with error */
283
284 /* send ping here */
285 /*
286 dprintf(sockfd, "PING\r\n");
287 // poll-read
288 if (irc_answer(sockfd, buf, NICK) & NICK) break;
289 */
290 }
291 }
292
293 void irc_cleanup(const sock_t sock) {
294 WRITE(sock, "QUIT :ircpipe\r\n", 15);
295 if (sock.tls) tls_close(sock.tls);
296 shutdown(sock.fd, SHUT_RDWR);
297 close(sock.fd);
298 }
299
300 int main(int argc, char **argv) {
301 char *host = NULL;
302 char *port = NULL;
303 char *nick = NULL;
304 char *pass = NULL;
305 char *chan = NULL;
306 size_t ping_iv = DEFAULT_PING; /* interval between outgoing pings */
307 size_t resp_to = DEFAULT_TIMEOUT; /* how long to wait for command response (connect, ping, auth, ...) */
308 int tls = DEFAULT_TLS;
309 char *ca_file = NULL;
310 int pass_type = NO_PASSWD;
311
312 sock_t sock;
313 int rv;
314
315 int opt; opterr = 0;
316
317 pass = getenv("IRC_PASSWD");
318 ca_file = getenv("IRC_CAFILE");
319
320 while ((opt = getopt(argc, argv, "n:j:pPsSkh")) != -1) {
321 switch (opt) {
322 case 'n': nick = optarg; break;
323 case 'p': pass_type = SERVER_PASSWD; break;
324 case 'P': pass_type = SASL_PLAIN_PASSWD; break;
325 case 's': tls = USE_TLS; break;
326 case 'S': tls = NO_TLS; break;
327 case 'k': tls = INSECURE_TLS; break;
328 case 'j': chan = optarg; break;
329 default: irc_help(argv[0], opt != 'h');
330 }
331 }
332
333 if (optind < argc) {
334 host = argv[optind++];
335 } else {
336 /* too few positional arguments */
337 fprintf(stderr, "missing HOST\n");
338 irc_help(argv[0], 1);
339 }
340 if (optind < argc) {
341 port = argv[optind++];
342 } else {
343 port = (tls == NO_TLS)
344 ? DEFAULT_PORT_TCP
345 : DEFAULT_PORT_TLS;
346 }
347 if (optind < argc) {
348 /* too many positional arguments */
349 fprintf(stderr, "too many args\n");
350 irc_help(argv[0], 1);
351 }
352
353 if (pass_type != NO_PASSWD && pass == NULL) {
354 fprintf(stderr, "must set IRC_PASSWD envvar to use -p/-P\n");
355 exit(1);
356 }
357
358 sock = irc_connect(host, port, tls, ca_file); sock.fd OR_DIE;
359 irc_setup(sock, 1, nick, pass, pass_type, chan);
360 rv = irc_poll(sock, 0, 1);
361 irc_cleanup(sock);
362
363 return (rv < 0);
364 }
Imprint / Impressum