74018e45f5bd048fb882948b851ce72ce985ce92
[citadel.git] / citadel / modules / nntp / serv_nntp.c
1 /*
2  * NNTP server module FIXME THIS IS NOT FINISHED
3  *
4  * Copyright (c) 2014 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 3.
8  *  
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <termios.h>
20 #include <fcntl.h>
21 #include <signal.h>
22 #include <pwd.h>
23 #include <errno.h>
24 #include <sys/types.h>
25 #include <syslog.h>
26
27 #if TIME_WITH_SYS_TIME
28 # include <sys/time.h>
29 # include <time.h>
30 #else
31 # if HAVE_SYS_TIME_H
32 #  include <sys/time.h>
33 # else
34 #  include <time.h>
35 # endif
36 #endif
37
38 #include <sys/wait.h>
39 #include <ctype.h>
40 #include <string.h>
41 #include <limits.h>
42 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45 #include <libcitadel.h>
46 #include "citadel.h"
47 #include "server.h"
48 #include "citserver.h"
49 #include "support.h"
50 #include "config.h"
51 #include "control.h"
52 #include "user_ops.h"
53 #include "room_ops.h"
54 #include "database.h"
55 #include "msgbase.h"
56 #include "internet_addressing.h"
57 #include "genstamp.h"
58 #include "domain.h"
59 #include "clientsocket.h"
60 #include "locate_host.h"
61 #include "citadel_dirs.h"
62 #include "ctdl_module.h"
63 #include "serv_nntp.h"
64
65 extern long timezone;
66
67 /****************** BEGIN UTILITY FUNCTIONS THAT COULD BE MOVED ELSEWHERE LATER **************/
68
69
70 /*
71  * Tests whether the supplied string is a valid newsgroup name
72  * Returns true (nonzero) or false (0)
73  */
74 int is_valid_newsgroup_name(char *name) {
75         char *ptr = name;
76         int has_a_letter = 0;
77
78         if (!ptr) return(0);
79         if (!strncasecmp(name, "ctdl.", 5)) return(0);
80
81         while (*ptr != 0) {
82
83                 if (isalpha(ptr[0])) {
84                         has_a_letter = 1;
85                 }
86
87                 if (    (isalnum(ptr[0]))
88                         || (ptr[0] == '.')
89                         || (ptr[0] == '+')
90                         || (ptr[0] == '-')
91                 ) {
92                         ++ptr;
93                 }
94                 else {
95                         return(0);
96                 }
97         }
98         return(has_a_letter);
99 }
100
101
102
103 /*
104  * Convert a Citadel room name to a valid newsgroup name
105  */
106 void room_to_newsgroup(char *target, char *source, size_t target_size) {
107
108         if (!target) return;
109         if (!source) return;
110
111         if (is_valid_newsgroup_name(source)) {
112                 strncpy(target, source, target_size);
113                 return;
114         }
115
116         strcpy(target, "ctdl.");
117         int len = 5;
118         char *ptr = source;
119         char ch;
120
121         while (ch=*ptr++, ch!=0) {
122                 if (len >= target_size) return;
123                 if (    (isalnum(ch))
124                         || (ch == '.')
125                         || (ch == '-')
126                 ) {
127                         target[len++] = ch;
128                         target[len] = 0;
129                 }
130                 else {
131                         target[len++] = '+' ;
132                         sprintf(&target[len], "%02x", ch);
133                         len += 2;
134                         target[len] = 0;
135                 }
136         }
137 }
138
139
140 /*
141  * Convert a newsgroup name to a Citadel room name.
142  * This function recognizes names converted with room_to_newsgroup() and restores them with full fidelity.
143  */
144 void newsgroup_to_room(char *target, char *source, size_t target_size) {
145
146         if (!target) return;
147         if (!source) return;
148
149         if (strncasecmp(source, "ctdl.", 5)) {                  // not a converted room name; pass through as-is
150                 strncpy(target, source, target_size);
151                 return;
152         }
153
154         target[0] = 0;
155         int len = 0;
156         char *ptr = &source[5];
157         char ch;
158
159         while (ch=*ptr++, ch!=0) {
160                 if (len >= target_size) return;
161                 if (ch == '+') {
162                         char hex[3];
163                         long digit;
164                         hex[0] = *ptr++;
165                         hex[1] = *ptr++;
166                         hex[2] = 0;
167                         digit = strtol(hex, NULL, 16);
168                         ch = (char)digit;
169                 }
170                 target[len++] = ch;
171                 target[len] = 0;
172         }
173 }
174
175
176 /******************  END  UTILITY FUNCTIONS THAT COULD BE MOVED ELSEWHERE LATER **************/
177
178
179
180 /*
181  * Here's where our NNTP session begins its happy day.
182  */
183 void nntp_greeting(void)
184 {
185         strcpy(CC->cs_clientname, "NNTP session");
186         CC->cs_flags |= CS_STEALTH;
187
188         /* CC->session_specific_data = malloc(sizeof(citnntp));
189         memset(NNTP, 0, sizeof(citnntp));
190         */
191
192         if (CC->nologin==1) {
193                 cprintf("451 Too many connections are already open; please try again later.\r\n");
194                 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
195                 return;
196         }
197
198         /* Note: the FQDN *must* appear as the first thing after the 220 code.
199          * Some clients (including citmail.c) depend on it being there.
200          */
201         cprintf("200 %s NNTP Citadel server is not finished yet\r\n", config.c_fqdn);
202 }
203
204
205 /*
206  * NNTPS is just like NNTP, except it goes crypto right away.
207  */
208 void nntps_greeting(void) {
209         CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
210 #ifdef HAVE_OPENSSL
211         if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO;          /* kill session if no crypto */
212 #endif
213         nntp_greeting();
214 }
215
216
217
218 /*
219  * implements the STARTTLS command
220  */
221 void nntp_starttls(void)
222 {
223         char ok_response[SIZ];
224         char nosup_response[SIZ];
225         char error_response[SIZ];
226
227         sprintf(ok_response, "382 Begin TLS negotiation now\r\n");
228         sprintf(nosup_response, "502 Can not initiate TLS negotiation\r\n");
229         sprintf(error_response, "580 Internal error\r\n");
230         CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
231 }
232
233
234 void nntp_noop(void)
235 {
236         cprintf("250 NOOP\r\n");
237 }
238
239
240 void nntp_capabilities(void)
241 {
242         cprintf("101 Capability list:\r\n");
243         cprintf("VERSION 2\r\n");
244         cprintf("READER\r\n");
245         cprintf("LIST ACTIVE NEWSGROUPS\r\n");
246         cprintf("IMPLEMENTATION Citadel v%d.%02d\r\n", (REV_LEVEL/100), (REV_LEVEL%100));
247 #ifdef HAVE_OPENSSL
248         cprintf("STARTTLS\r\n");
249 #endif
250         if (!CC->logged_in) {
251                 cprintf("AUTHINFO USER\r\n");
252         }
253         cprintf(".\r\n");
254 }
255
256
257 void nntp_quit(void)
258 {
259         cprintf("221 Goodbye...\r\n");
260         CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
261 }
262
263
264 void nntp_cleanup(void)
265 {
266         /* nothing here yet */
267 }
268
269
270
271 /*
272  * Implements the AUTHINFO USER command (RFC 4643)
273  */
274 void nntp_authinfo_user(const char *username)
275 {
276         int a = CtdlLoginExistingUser(NULL, username);
277         switch (a) {
278         case login_already_logged_in:
279                 cprintf("482 Already logged in\r\n");
280                 return;
281         case login_too_many_users:
282                 cprintf("481 Too many users are already online (maximum is %d)\r\n", config.c_maxsessions);
283                 return;
284         case login_ok:
285                 cprintf("381 Password required for %s\r\n", CC->curr_user);
286                 return;
287         case login_not_found:
288                 cprintf("481 %s not found\r\n", username);
289                 return;
290         default:
291                 cprintf("502 Internal error\r\n");
292         }
293 }
294
295
296 /*
297  * Implements the AUTHINFO PASS command (RFC 4643)
298  */
299 void nntp_authinfo_pass(const char *buf)
300 {
301         int a;
302
303         a = CtdlTryPassword(buf, strlen(buf));
304
305         switch (a) {
306         case pass_already_logged_in:
307                 cprintf("482 Already logged in\r\n");
308                 return;
309         case pass_no_user:
310                 cprintf("482 Authentication commands issued out of sequence\r\n");
311                 return;
312         case pass_wrong_password:
313                 cprintf("481 Authentication failed\r\n");
314                 return;
315         case pass_ok:
316                 cprintf("281 Authentication accepted\r\n");
317                 return;
318         }
319 }
320
321
322
323 /*
324  * Implements the AUTHINFO extension (RFC 4643) in USER/PASS mode
325  */
326 void nntp_authinfo(const char *cmd) {
327
328         if (!strncasecmp(cmd, "authinfo user ", 14)) {
329                 nntp_authinfo_user(&cmd[14]);
330         }
331
332         else if (!strncasecmp(cmd, "authinfo pass ", 14)) {
333                 nntp_authinfo_pass(&cmd[14]);
334         }
335
336         else {
337                 cprintf("502 command unavailable\r\n");
338         }
339 }
340
341
342 /*
343  * Utility function to fetch the current list of message numbers in a room
344  */
345 struct nntp_msglist nntp_fetch_msglist(struct ctdlroom *qrbuf) {
346         struct nntp_msglist nm;
347         struct cdbdata *cdbfr;
348
349         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf->QRnumber, sizeof(long));
350         if (cdbfr != NULL) {
351                 nm.msgnums = (long*)cdbfr->ptr;
352                 cdbfr->ptr = NULL;
353                 nm.num_msgs = cdbfr->len / sizeof(long);
354                 cdbfr->len = 0;
355                 cdb_free(cdbfr);
356         } else {
357                 nm.num_msgs = 0;
358                 nm.msgnums = NULL;
359         }
360         return(nm);
361 }
362
363
364
365 /*
366  * Various output formats for the LIST commands
367  */
368 enum {
369         NNTP_LIST_ACTIVE,
370         NNTP_LIST_ACTIVE_TIMES,
371         NNTP_LIST_DISTRIB_PATS,
372         NNTP_LIST_HEADERS,
373         NNTP_LIST_NEWSGROUPS,
374         NNTP_LIST_OVERVIEW_FMT
375 };
376
377
378 /*
379  * Output a room name (newsgroup name) in formats required for LIST and NEWGROUPS command
380  */
381 void output_roomname_in_list_format(struct ctdlroom *qrbuf, int which_format) {
382         char n_name[1024];
383         struct nntp_msglist nm;
384         long low_water_mark = 0;
385         long high_water_mark = 0;
386
387         room_to_newsgroup(n_name, qrbuf->QRname, sizeof n_name);
388         nm = nntp_fetch_msglist(qrbuf);
389         if ((nm.num_msgs > 0) && (nm.msgnums != NULL)) {
390                 low_water_mark = nm.msgnums[0];
391                 high_water_mark = nm.msgnums[nm.num_msgs - 1];
392         }
393
394         // Only the mandatory formats are supported
395         switch(which_format) {
396         case NNTP_LIST_ACTIVE:
397                 // FIXME we have hardcoded "n" for "no posting allowed" -- fix when we add posting
398                 cprintf("%s %ld %ld n\r\n", n_name, high_water_mark, low_water_mark);
399                 break;
400         case NNTP_LIST_NEWSGROUPS:
401                 cprintf("%s %s\r\n", n_name, qrbuf->QRname);
402                 break;
403         }
404
405         if (nm.msgnums != NULL) {
406                 free(nm.msgnums);
407         }
408 }
409
410
411
412 /*
413  * Called once per room by nntp_newgroups() to qualify and possibly output a single room
414  */
415 void nntp_newgroups_backend(struct ctdlroom *qrbuf, void *data)
416 {
417         int ra;
418         int view;
419         time_t thetime = *(time_t *)data;
420
421         CtdlRoomAccess(qrbuf, &CC->user, &ra, &view);
422
423         /*
424          * The "created after <date/time>" heuristics depend on the happy coincidence
425          * that for a very long time we have used a unix timestamp as the room record's
426          * generation number (QRgen).  When this module is merged into the master
427          * source tree we should rename QRgen to QR_create_time or something like that.
428          */
429
430         if (ra & UA_KNOWN) {
431                 if (qrbuf->QRgen >= thetime) {
432                         output_roomname_in_list_format(qrbuf, NNTP_LIST_ACTIVE);
433                 }
434         }
435 }
436
437
438 /*
439  * Implements the NEWGROUPS command
440  */
441 void nntp_newgroups(const char *cmd) {
442         /*
443          * HACK: this works because the 5XX series error codes from citadel
444          * protocol will also be considered error codes by an NNTP client
445          */
446         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
447
448
449         char stringy_date[16];
450         char stringy_time[16];
451         char stringy_gmt[16];
452         struct tm tm;
453         time_t thetime;
454
455         extract_token(stringy_date, cmd, 1, ' ', sizeof stringy_date);
456         extract_token(stringy_time, cmd, 2, ' ', sizeof stringy_time);
457         extract_token(stringy_gmt, cmd, 3, ' ', sizeof stringy_gmt);
458
459         memset(&tm, 0, sizeof tm);
460         if (strlen(stringy_date) == 6) {
461                 sscanf(stringy_date, "%2d%2d%2d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday);
462                 tm.tm_year += 100;
463         }
464         else {
465                 sscanf(stringy_date, "%4d%2d%2d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday);
466                 tm.tm_year -= 1900;
467         }
468         tm.tm_mon -= 1;         // tm_mon is zero based (0=January)
469         tm.tm_isdst = (-1);     // let the C library figure out whether DST is in effect
470         sscanf(stringy_time, "%2d%2d%2d", &tm.tm_hour, &tm.tm_min ,&tm.tm_sec);
471         thetime = mktime(&tm);
472         if (!strcasecmp(stringy_gmt, "GMT")) {
473                 tzset();
474                 thetime += timezone;
475         }
476
477
478         cprintf("231 list of new newsgroups follows\r\n");
479         CtdlGetUser(&CC->user, CC->curr_user);
480         CtdlForEachRoom(nntp_newgroups_backend, &thetime);
481         cprintf(".\r\n");
482 }
483
484
485 /*
486  * Called once per room by nntp_list() to qualify and possibly output a single room
487  */
488 void nntp_list_backend(struct ctdlroom *qrbuf, void *data)
489 {
490         int ra;
491         int view;
492         struct nntp_list_data *nld = (struct nntp_list_data *)data;
493
494         // FIXME do something with nld->wildmat, bitch
495
496         wildmat(NULL,NULL);     // linkage test
497
498         CtdlRoomAccess(qrbuf, &CC->user, &ra, &view);
499         if (ra & UA_KNOWN) {
500                 output_roomname_in_list_format(qrbuf, nld->list_format);
501         }
502 }
503
504
505 /*
506  * Implements the LIST commands
507  */
508 void nntp_list(const char *cmd) {
509         /*
510          * HACK: this works because the 5XX series error codes from citadel
511          * protocol will also be considered error codes by an NNTP client
512          */
513         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
514
515         char list_format[64];
516         char wildmat[1024];
517         struct nntp_list_data nld;
518
519         extract_token(list_format, cmd, 1, ' ', sizeof list_format);
520         extract_token(wildmat, cmd, 2, ' ', sizeof wildmat);
521
522         if (strlen(wildmat) > 0) {
523                 nld.wildmat = wildmat;
524         }
525         else {
526                 nld.wildmat = NULL;
527         }
528
529         if ( (strlen(cmd) < 6) || (!strcasecmp(list_format, "ACTIVE")) ) {
530                 nld.list_format = NNTP_LIST_ACTIVE;
531         }
532         else if (!strcasecmp(list_format, "NEWSGROUPS")) {
533                 nld.list_format = NNTP_LIST_NEWSGROUPS;
534         }
535         else {
536                 cprintf("501 syntax error , unsupported list format\r\n");
537                 return;
538         }
539         // FIXME do all of the other variants, bitch
540
541
542         cprintf("231 list of newsgroups follows\r\n");
543         CtdlGetUser(&CC->user, CC->curr_user);
544         CtdlForEachRoom(nntp_list_backend, &nld);
545         cprintf(".\r\n");
546 }
547
548
549 /* 
550  * Main command loop for NNTP server sessions.
551  */
552 void nntp_command_loop(void)
553 {
554         StrBuf *Cmd = NewStrBuf();
555         char cmdname[16];
556
557         time(&CC->lastcmd);
558         if (CtdlClientGetLine(Cmd) < 1) {
559                 syslog(LOG_CRIT, "NNTP: client disconnected: ending session.\n");
560                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
561                 FreeStrBuf(&Cmd);
562                 return;
563         }
564         syslog(LOG_DEBUG, "NNTP server: %s\n", ChrPtr(Cmd));
565         extract_token(cmdname, ChrPtr(Cmd), 0, ' ', sizeof cmdname);
566
567         /*
568          * Rumpelstiltskin lookups are awesome
569          */
570
571         if (!strcasecmp(cmdname, "quit")) {
572                 nntp_quit();
573         }
574
575         else if (!strcasecmp(cmdname, "capabilities")) {
576                 nntp_capabilities();
577         }
578
579         else if (!strcasecmp(cmdname, "starttls")) {
580                 nntp_starttls();
581         }
582
583         else if (!strcasecmp(cmdname, "noop")) {
584                 nntp_noop();
585         }
586
587         else if (!strcasecmp(cmdname, "authinfo")) {
588                 nntp_authinfo(ChrPtr(Cmd));
589         }
590
591         else if (!strcasecmp(cmdname, "newgroups")) {
592                 nntp_newgroups(ChrPtr(Cmd));
593         }
594
595         else if (!strcasecmp(cmdname, "list")) {
596                 nntp_list(ChrPtr(Cmd));
597         }
598
599         else {
600                 cprintf("500 I'm afraid I can't do that.\r\n");
601         }
602
603         FreeStrBuf(&Cmd);
604 }
605
606
607 /*****************************************************************************/
608 /*                    MODULE INITIALIZATION STUFF                         */
609 /*****************************************************************************/
610
611
612 /*
613  * This cleanup function blows away the temporary memory used by
614  * the NNTP server.
615  */
616 void nntp_cleanup_function(void)
617 {
618         /* Don't do this stuff if this is not an NNTP session! */
619         if (CC->h_command_function != nntp_command_loop) return;
620
621         syslog(LOG_DEBUG, "Performing NNTP cleanup hook\n");
622 }
623
624 const char *CitadelServiceNNTP="NNTP";
625
626 CTDL_MODULE_INIT(nntp)
627 {
628         if (!threading)
629         {
630                 CtdlRegisterServiceHook(119,                    // FIXME config.c_nntp_port,
631                                         NULL,
632                                         nntp_greeting,
633                                         nntp_command_loop,
634                                         NULL, 
635                                         CitadelServiceNNTP);
636
637 #ifdef HAVE_OPENSSL
638                 CtdlRegisterServiceHook(563,                    // FIXME config.c_nntps_port,
639                                         NULL,
640                                         nntps_greeting,
641                                         nntp_command_loop,
642                                         NULL,
643                                         CitadelServiceNNTP);
644 #endif
645
646                 CtdlRegisterCleanupHook(nntp_cleanup);
647                 CtdlRegisterSessionHook(nntp_cleanup_function, EVT_STOP, PRIO_STOP + 250);
648         }
649         
650         /* return our module name for the log */
651         return "nntp";
652 }
653