Fixed a comment in query.sh to contain chanserv.
[iii.git] / ii.c
blob7de9e68b026cf2388ba3716ca329afb7025f6214
1 /* (C)opyright MMV-MMVI Anselm R. Garbe <garbeam at gmail dot com>
2 * (C)opyright MMV-MMXI Nico Golde <nico at ngolde dot de>
3 * See LICENSE file for license details. */
4 #include <errno.h>
5 #include <netdb.h>
6 #include <netinet/in.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <limits.h>
10 #include <fcntl.h>
11 #include <string.h>
12 #include <signal.h>
13 #include <sys/stat.h>
14 #include <sys/socket.h>
15 #include <ctype.h>
16 #include <time.h>
17 #include <unistd.h>
19 #ifndef PIPE_BUF /* FreeBSD don't know PIPE_BUF */
20 #define PIPE_BUF 4096
21 #endif
22 #define PING_TIMEOUT 300
23 #define SERVER_PORT 6667
24 enum { TOK_NICKSRV = 0, TOK_USER, TOK_CMD, TOK_CHAN, TOK_ARG, TOK_TEXT, TOK_LAST };
26 typedef struct Channel Channel;
27 struct Channel {
28 int fd;
29 char *name;
30 Channel *next;
33 static int irc;
34 static time_t last_response;
35 static Channel *channels = NULL;
36 static char *host = "irc.freenode.net";
37 static char nick[32] = "anonymous"; /* might change while running */
38 static char path[_POSIX_PATH_MAX];
39 static char message[PIPE_BUF]; /* message buf used for communication */
41 static void usage() {
42 fprintf(stderr, "%s",
43 "ii - irc it - " VERSION "\n"
44 "(C)opyright MMV-MMVI Anselm R. Garbe\n"
45 "(C)opyright MMV-MMXI Nico Golde\n"
46 "usage: ii [-i <irc dir>] [-s <host>] [-p <port>]\n"
47 " [-n <nick>] [-k <password>] [-f <fullname>]\n");
48 exit(EXIT_SUCCESS);
51 static char *striplower(char *s) {
52 char *p = NULL;
53 for(p = s; p && *p; p++) {
54 if(*p == '/') *p = '_';
55 *p = tolower(*p);
57 return s;
60 /* creates directories top-down, if necessary */
61 static void create_dirtree(const char *dir) {
62 char tmp[256];
63 char *p = NULL;
64 size_t len;
66 snprintf(tmp, sizeof(tmp),"%s",dir);
67 len = strlen(tmp);
68 if(tmp[len - 1] == '/')
69 tmp[len - 1] = 0;
70 for(p = tmp + 1; *p; p++)
71 if(*p == '/') {
72 *p = 0;
73 mkdir(tmp, S_IRWXU);
74 *p = '/';
76 mkdir(tmp, S_IRWXU);
79 static int get_filepath(char *filepath, size_t len, char *channel, char *file) {
80 if(channel) {
81 if(!snprintf(filepath, len, "%s/%s", path, channel))
82 return 0;
83 create_dirtree(filepath);
84 return snprintf(filepath, len, "%s/%s/%s", path, channel, file);
86 return snprintf(filepath, len, "%s/%s", path, file);
89 static void create_filepath(char *filepath, size_t len, char *channel, char *suffix) {
90 if(!get_filepath(filepath, len, striplower(channel), suffix)) {
91 fprintf(stderr, "%s", "ii: path to irc directory too long\n");
92 exit(EXIT_FAILURE);
96 static int open_channel(char *name) {
97 static char infile[256];
98 create_filepath(infile, sizeof(infile), name, "in");
99 if(access(infile, F_OK) == -1)
100 mkfifo(infile, S_IRWXU);
101 return open(infile, O_RDONLY | O_NONBLOCK, 0);
104 static void add_channel(char *cname) {
105 Channel *c;
106 int fd;
107 char *name = striplower(cname);
109 for(c = channels; c; c = c->next)
110 if(!strcmp(name, c->name))
111 return; /* already handled */
113 fd = open_channel(name);
114 if(fd == -1) {
115 printf("ii: exiting, cannot create in channel: %s\n", name);
116 exit(EXIT_FAILURE);
118 c = calloc(1, sizeof(Channel));
119 if(!c) {
120 perror("ii: cannot allocate memory");
121 exit(EXIT_FAILURE);
123 if(!channels) channels = c;
124 else {
125 c->next = channels;
126 channels = c;
128 c->fd = fd;
129 c->name = strdup(name);
132 static void rm_channel(Channel *c) {
133 Channel *p;
134 if(channels == c) channels = channels->next;
135 else {
136 for(p = channels; p && p->next != c; p = p->next);
137 if(p->next == c)
138 p->next = c->next;
140 free(c->name);
141 free(c);
144 static void login(char *key, char *fullname) {
145 if(key) snprintf(message, PIPE_BUF,
146 "PASS %s\r\nNICK %s\r\nUSER %s localhost * :%s\r\n", key,
147 nick, nick, fullname ? fullname : nick);
148 else snprintf(message, PIPE_BUF, "NICK %s\r\nUSER %s localhost * :%s\r\n",
149 nick, nick, fullname ? fullname : nick);
150 write(irc, message, strlen(message)); /* login */
153 static int tcpopen(unsigned short port) {
154 int fd;
155 struct sockaddr_in sin;
156 struct hostent *hp = gethostbyname(host);
158 memset(&sin, 0, sizeof(struct sockaddr_in));
159 if(!hp) {
160 perror("ii: cannot retrieve host information");
161 exit(EXIT_FAILURE);
163 sin.sin_family = AF_INET;
164 memcpy(&sin.sin_addr, hp->h_addr, hp->h_length);
165 sin.sin_port = htons(port);
166 if((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
167 perror("ii: cannot create socket");
168 exit(EXIT_FAILURE);
170 if(connect(fd, (const struct sockaddr *) &sin, sizeof(sin)) < 0) {
171 perror("ii: cannot connect to host");
172 exit(EXIT_FAILURE);
174 return fd;
177 static size_t tokenize(char **result, size_t reslen, char *str, char delim) {
178 char *p = NULL, *n = NULL;
179 size_t i;
181 if(!str)
182 return 0;
183 for(n = str; *n == ' '; n++);
184 p = n;
185 for(i = 0; *n != 0;) {
186 if(i == reslen)
187 return 0;
188 if(i > TOK_CHAN - TOK_CMD && strtol(result[0], NULL, 10) > 0) delim=':'; /* workaround non-RFC compliant messages */
189 if(*n == delim) {
190 *n = 0;
191 result[i++] = p;
192 p = ++n;
193 } else
194 n++;
196 if(i<reslen && p < n && strlen(p))
197 result[i++] = p;
198 return i; /* number of tokens */
201 static void print_out(char *channel, char *buf) {
202 static char outfile[256], server[256], buft[18];
203 FILE *out = NULL;
204 time_t t = time(0);
206 if(channel) snprintf(server, sizeof(server), "-!- %s", channel);
207 if(strstr(buf, server)) channel="";
208 create_filepath(outfile, sizeof(outfile), channel, "out");
209 if(!(out = fopen(outfile, "a"))) return;
210 if(channel && channel[0]) add_channel(channel);
212 strftime(buft, sizeof(buft), "%F %R", localtime(&t));
213 fprintf(out, "%s %s\n", buft, buf);
214 fclose(out);
217 static void proc_channels_privmsg(char *channel, char *buf) {
218 snprintf(message, PIPE_BUF, "<%s> %s", nick, buf);
219 print_out(channel, message);
220 snprintf(message, PIPE_BUF, "PRIVMSG %s :%s\r\n", channel, buf);
221 write(irc, message, strlen(message));
224 static void proc_channels_input(Channel *c, char *buf) {
225 char *p = NULL;
227 if(buf[0] != '/' && buf[0] != 0) {
228 proc_channels_privmsg(c->name, buf);
229 return;
231 message[0] = '\0';
232 if(buf[2] == ' ' || buf[2] == '\0') switch (buf[1]) {
233 case 'j':
234 p = strchr(&buf[3], ' ');
235 if(p) *p = 0;
236 if((buf[3]=='#')||(buf[3]=='&')||(buf[3]=='+')||(buf[3]=='!')){
237 if(p) snprintf(message, PIPE_BUF, "JOIN %s %s\r\n", &buf[3], p + 1); /* password protected channel */
238 else snprintf(message, PIPE_BUF, "JOIN %s\r\n", &buf[3]);
239 add_channel(&buf[3]);
241 else {
242 if(p){
243 add_channel(&buf[3]);
244 proc_channels_privmsg(&buf[3], p + 1);
245 return;
248 break;
249 case 't':
250 if(strlen(buf)>=3) snprintf(message, PIPE_BUF, "TOPIC %s :%s\r\n", c->name, &buf[3]);
251 break;
252 case 'a':
253 if(strlen(buf)>=3){
254 snprintf(message, PIPE_BUF, "-!- %s is away \"%s\"", nick, &buf[3]);
255 print_out(c->name, message);
257 if(buf[2] == 0 || strlen(buf)<3) /* or used to make else part safe */
258 snprintf(message, PIPE_BUF, "AWAY\r\n");
259 else
260 snprintf(message, PIPE_BUF, "AWAY :%s\r\n", &buf[3]);
261 break;
262 case 'n':
263 if(strlen(buf)>=3){
264 snprintf(nick, sizeof(nick),"%s", &buf[3]);
265 snprintf(message, PIPE_BUF, "NICK %s\r\n", &buf[3]);
267 break;
268 case 'l':
269 if(c->name[0] == 0)
270 return;
271 if(buf[2] == ' ' && strlen(buf)>=3)
272 snprintf(message, PIPE_BUF, "PART %s :%s\r\n", c->name, &buf[3]);
273 else
274 snprintf(message, PIPE_BUF,
275 "PART %s\r\n", c->name);
276 write(irc, message, strlen(message));
277 close(c->fd);
278 rm_channel(c);
279 return;
280 break;
281 default:
282 snprintf(message, PIPE_BUF, "%s\r\n", &buf[1]);
283 break;
284 } else
285 snprintf(message, PIPE_BUF, "%s\r\n", &buf[1]);
287 if (message[0] != '\0')
288 write(irc, message, strlen(message));
291 static void proc_server_cmd(char *buf) {
292 char *argv[TOK_LAST], *cmd = NULL, *p = NULL;
293 int i;
295 if(!buf || *buf=='\0')
296 return;
298 for(i = 0; i < TOK_LAST; i++)
299 argv[i] = NULL;
300 /* <message> ::= [':' <prefix> <SPACE> ] <command> <params> <crlf>
301 <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]
302 <command> ::= <letter> { <letter> } | <number> <number> <number>
303 <SPACE> ::= ' ' { ' ' }
304 <params> ::= <SPACE> [ ':' <trailing> | <middle> <params> ]
305 <middle> ::= <Any *non-empty* sequence of octets not including SPACE
306 or NUL or CR or LF, the first of which may not be ':'>
307 <trailing> ::= <Any, possibly *empty*, sequence of octets not including NUL or CR or LF>
308 <crlf> ::= CR LF */
310 if(buf[0] == ':') { /* check prefix */
311 if (!(p = strchr(buf, ' '))) return;
312 *p = 0;
313 for(++p; *p == ' '; p++);
314 cmd = p;
315 argv[TOK_NICKSRV] = &buf[1];
316 if((p = strchr(buf, '!'))) {
317 *p = 0;
318 argv[TOK_USER] = ++p;
320 } else
321 cmd = buf;
323 /* remove CRLFs */
324 for(p = cmd; p && *p != 0; p++)
325 if(*p == '\r' || *p == '\n')
326 *p = 0;
328 if((p = strchr(cmd, ':'))) {
329 *p = 0;
330 argv[TOK_TEXT] = ++p;
333 tokenize(&argv[TOK_CMD], TOK_LAST - TOK_CMD, cmd, ' ');
335 if(!argv[TOK_CMD] || !strncmp("PONG", argv[TOK_CMD], 5)) {
336 return;
337 } else if(!strncmp("PING", argv[TOK_CMD], 5)) {
338 snprintf(message, PIPE_BUF, "PONG %s\r\n", argv[TOK_TEXT]);
339 write(irc, message, strlen(message));
340 return;
341 } else if(!argv[TOK_NICKSRV] || !argv[TOK_USER]) { /* server command */
342 snprintf(message, PIPE_BUF, "%s%s", argv[TOK_ARG] ? argv[TOK_ARG] : "", argv[TOK_TEXT] ? argv[TOK_TEXT] : "");
343 print_out(0, message);
344 return;
345 } else if(!strncmp("ERROR", argv[TOK_CMD], 6))
346 snprintf(message, PIPE_BUF, "-!- error %s", argv[TOK_TEXT] ? argv[TOK_TEXT] : "unknown");
347 else if(!strncmp("JOIN", argv[TOK_CMD], 5)) {
348 if(argv[TOK_TEXT] != NULL){
349 p = strchr(argv[TOK_TEXT], ' ');
350 if(p)
351 *p = 0;
353 argv[TOK_CHAN] = argv[TOK_TEXT];
354 snprintf(message, PIPE_BUF, "-!- %s(%s) has joined %s", argv[TOK_NICKSRV], argv[TOK_USER], argv[TOK_TEXT]);
355 } else if(!strncmp("PART", argv[TOK_CMD], 5)) {
356 snprintf(message, PIPE_BUF, "-!- %s(%s) has left %s", argv[TOK_NICKSRV], argv[TOK_USER], argv[TOK_CHAN]);
357 } else if(!strncmp("MODE", argv[TOK_CMD], 5))
358 snprintf(message, PIPE_BUF, "-!- %s changed mode/%s -> %s %s", argv[TOK_NICKSRV], argv[TOK_CMD + 1] ? argv[TOK_CMD + 1] : "" , argv[TOK_CMD + 2]? argv[TOK_CMD + 2] : "", argv[TOK_CMD + 3] ? argv[TOK_CMD + 3] : "");
359 else if(!strncmp("QUIT", argv[TOK_CMD], 5))
360 snprintf(message, PIPE_BUF, "-!- %s(%s) has quit \"%s\"", argv[TOK_NICKSRV], argv[TOK_USER], argv[TOK_TEXT] ? argv[TOK_TEXT] : "");
361 else if(!strncmp("NICK", argv[TOK_CMD], 5))
362 snprintf(message, PIPE_BUF, "-!- %s changed nick to %s", argv[TOK_NICKSRV], argv[TOK_TEXT]);
363 else if(!strncmp("TOPIC", argv[TOK_CMD], 6))
364 snprintf(message, PIPE_BUF, "-!- %s changed topic to \"%s\"", argv[TOK_NICKSRV], argv[TOK_TEXT] ? argv[TOK_TEXT] : "");
365 else if(!strncmp("KICK", argv[TOK_CMD], 5))
366 snprintf(message, PIPE_BUF, "-!- %s kicked %s (\"%s\")", argv[TOK_NICKSRV], argv[TOK_ARG], argv[TOK_TEXT] ? argv[TOK_TEXT] : "");
367 else if(!strncmp("NOTICE", argv[TOK_CMD], 7))
368 snprintf(message, PIPE_BUF, "-!- \"%s\")", argv[TOK_TEXT] ? argv[TOK_TEXT] : "");
369 else if(!strncmp("PRIVMSG", argv[TOK_CMD], 8))
370 snprintf(message, PIPE_BUF, "<%s> %s", argv[TOK_NICKSRV], argv[TOK_TEXT] ? argv[TOK_TEXT] : "");
371 if(!argv[TOK_CHAN] || !strncmp(argv[TOK_CHAN], nick, strlen(nick)))
372 print_out(argv[TOK_NICKSRV], message);
373 else
374 print_out(argv[TOK_CHAN], message);
377 static int read_line(int fd, size_t res_len, char *buf) {
378 size_t i = 0;
379 char c = 0;
380 do {
381 if(read(fd, &c, sizeof(char)) != sizeof(char))
382 return -1;
383 buf[i++] = c;
385 while(c != '\n' && i < res_len);
386 buf[i - 1] = 0; /* eliminates '\n' */
387 return 0;
390 static void handle_channels_input(Channel *c) {
391 static char buf[PIPE_BUF];
392 if(read_line(c->fd, PIPE_BUF, buf) == -1) {
393 close(c->fd);
394 int fd = open_channel(c->name);
395 if(fd != -1)
396 c->fd = fd;
397 else
398 rm_channel(c);
399 return;
401 proc_channels_input(c, buf);
404 static void handle_server_output() {
405 static char buf[PIPE_BUF];
406 if(read_line(irc, PIPE_BUF, buf) == -1) {
407 perror("ii: remote host closed connection");
408 exit(EXIT_FAILURE);
410 proc_server_cmd(buf);
413 static void run() {
414 Channel *c;
415 int r, maxfd;
416 fd_set rd;
417 struct timeval tv;
418 char ping_msg[17] = "PING localhost\r\n";
420 for(;;) {
421 FD_ZERO(&rd);
422 maxfd = irc;
423 FD_SET(irc, &rd);
424 for(c = channels; c; c = c->next) {
425 if(maxfd < c->fd)
426 maxfd = c->fd;
427 FD_SET(c->fd, &rd);
430 tv.tv_sec = 120;
431 tv.tv_usec = 0;
432 r = select(maxfd + 1, &rd, 0, 0, &tv);
433 if(r < 0) {
434 if(errno == EINTR)
435 continue;
436 perror("ii: error on select()");
437 exit(EXIT_FAILURE);
438 } else if(r == 0) {
439 if(time(NULL) - last_response >= PING_TIMEOUT) {
440 print_out(NULL, "-!- ii shutting down: ping timeout");
441 exit(EXIT_FAILURE);
443 write(irc, ping_msg, strlen(ping_msg));
444 continue;
446 if(FD_ISSET(irc, &rd)) {
447 handle_server_output();
448 last_response = time(NULL);
450 for(c = channels; c; c = c->next)
451 if(FD_ISSET(c->fd, &rd))
452 handle_channels_input(c);
456 int main(int argc, char *argv[]) {
457 int i;
458 unsigned short port = SERVER_PORT;
459 char *key = NULL, *fullname = NULL, *dir = NULL;
460 char prefix[_POSIX_PATH_MAX] = "irc";
462 if (argc <= 1 || (argc == 2 && argv[1][0] == '-' && argv[1][1] == 'h')) usage();
464 for(i = 1; (i + 1 < argc) && (argv[i][0] == '-'); i++) {
465 switch (argv[i][1]) {
466 case 'i': snprintf(prefix,sizeof(prefix),"%s", argv[++i]); break;
467 case 's': host = argv[++i]; break;
468 case 'p': port = strtol(argv[++i], NULL, 10); break;
469 case 'n': snprintf(nick,sizeof(nick),"%s", argv[++i]); break;
470 case 'k': key = argv[++i]; break;
471 case 'f': fullname = argv[++i]; break;
472 case 'd': dir = argv[++i]; break;
473 default: usage(); break;
476 irc = tcpopen(port);
477 if(!snprintf(path, sizeof(path), "%s/%s", prefix, dir ? dir : host)) {
478 fprintf(stderr, "%s", "ii: path to irc directory too long\n");
479 exit(EXIT_FAILURE);
481 create_dirtree(path);
483 add_channel(""); /* master channel */
484 login(key, fullname);
485 run();
487 return 0;