stable now but there are GIANT PIECES MISSING
[citadel.git] / citadel / modules / nntp / serv_nntp.c
1 //
2 // NNTP server module (RFC 3977)
3 //
4 // Copyright (c) 2014-2020 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 #include <time.h>
27 #include <sys/wait.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <limits.h>
31 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
34 #include <libcitadel.h>
35 #include "citadel.h"
36 #include "server.h"
37 #include "citserver.h"
38 #include "support.h"
39 #include "config.h"
40 #include "control.h"
41 #include "user_ops.h"
42 #include "room_ops.h"
43 #include "database.h"
44 #include "msgbase.h"
45 #include "internet_addressing.h"
46 #include "genstamp.h"
47 #include "domain.h"
48 #include "clientsocket.h"
49 #include "locate_host.h"
50 #include "citadel_dirs.h"
51 #include "ctdl_module.h"
52 #include "serv_nntp.h"
53
54 extern long timezone;
55
56 //
57 // Tests whether the supplied string is a valid newsgroup name
58 // Returns true (nonzero) or false (0)
59 //
60 int is_valid_newsgroup_name(char *name) {
61         char *ptr = name;
62         int has_a_letter = 0;
63         int num_dots = 0;
64
65         if (!ptr) return(0);
66         if (!strncasecmp(name, "ctdl.", 5)) return(0);
67
68         while (*ptr != 0) {
69
70                 if (isalpha(ptr[0])) {
71                         has_a_letter = 1;
72                 }
73
74                 if (ptr[0] == '.') {
75                         ++num_dots;
76                 }
77
78                 if (    (isalnum(ptr[0]))
79                         || (ptr[0] == '.')
80                         || (ptr[0] == '+')
81                         || (ptr[0] == '-')
82                 ) {
83                         ++ptr;
84                 }
85                 else {
86                         return(0);
87                 }
88         }
89         return( (has_a_letter) && (num_dots >= 1) ) ;
90 }
91
92
93 //
94 // Convert a Citadel room name to a valid newsgroup name
95 //
96 void room_to_newsgroup(char *target, char *source, size_t target_size) {
97
98         if (!target) return;
99         if (!source) return;
100
101         if (is_valid_newsgroup_name(source)) {
102                 strncpy(target, source, target_size);
103                 return;
104         }
105
106         strcpy(target, "ctdl.");
107         int len = 5;
108         char *ptr = source;
109         char ch;
110
111         while (ch=*ptr++, ch!=0) {
112                 if (len >= target_size) return;
113                 if (    (isalnum(ch))
114                         || (ch == '.')
115                         || (ch == '-')
116                 ) {
117                         target[len++] = tolower(ch);
118                         target[len] = 0;
119                 }
120                 else {
121                         target[len++] = '+' ;
122                         sprintf(&target[len], "%02x", ch);
123                         len += 2;
124                         target[len] = 0;
125                 }
126         }
127 }
128
129
130 //
131 // Convert a newsgroup name to a Citadel room name.
132 // This function recognizes names converted with room_to_newsgroup() and restores them with full fidelity.
133 //
134 void newsgroup_to_room(char *target, char *source, size_t target_size) {
135
136         if (!target) return;
137         if (!source) return;
138
139         if (strncasecmp(source, "ctdl.", 5)) {                  // not a converted room name; pass through as-is
140                 strncpy(target, source, target_size);
141                 return;
142         }
143
144         target[0] = 0;
145         int len = 0;
146         char *ptr = &source[5];
147         char ch;
148
149         while (ch=*ptr++, ch!=0) {
150                 if (len >= target_size) return;
151                 if (ch == '+') {
152                         char hex[3];
153                         long digit;
154                         hex[0] = *ptr++;
155                         hex[1] = *ptr++;
156                         hex[2] = 0;
157                         digit = strtol(hex, NULL, 16);
158                         ch = (char)digit;
159                 }
160                 target[len++] = ch;
161                 target[len] = 0;
162         }
163 }
164
165
166 //
167 // Here's where our NNTP session begins its happy day.
168 //
169 void nntp_greeting(void)
170 {
171         strcpy(CC->cs_clientname, "NNTP session");
172         CC->cs_flags |= CS_STEALTH;
173
174         CC->session_specific_data = malloc(sizeof(citnntp));
175         citnntp *nntpstate = (citnntp *) CC->session_specific_data;
176         memset(nntpstate, 0, sizeof(citnntp));
177
178         if (CC->nologin==1) {
179                 cprintf("451 Too many connections are already open; please try again later.\r\n");
180                 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
181                 return;
182         }
183
184         // Display the standard greeting
185         cprintf("200 %s NNTP Citadel server is not finished yet\r\n", CtdlGetConfigStr("c_fqdn"));
186 }
187
188
189 //
190 // NNTPS is just like NNTP, except it goes crypto right away.
191 //
192 void nntps_greeting(void) {
193         CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
194 #ifdef HAVE_OPENSSL
195         if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO;          /* kill session if no crypto */
196 #endif
197         nntp_greeting();
198 }
199
200
201 //
202 // implements the STARTTLS command
203 //
204 void nntp_starttls(void)
205 {
206         char ok_response[SIZ];
207         char nosup_response[SIZ];
208         char error_response[SIZ];
209
210         sprintf(ok_response, "382 Begin TLS negotiation now\r\n");
211         sprintf(nosup_response, "502 Can not initiate TLS negotiation\r\n");
212         sprintf(error_response, "580 Internal error\r\n");
213         CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
214 }
215
216
217 //
218 // Implements the CAPABILITY command
219 //
220 void nntp_capabilities(void)
221 {
222         cprintf("101 Capability list:\r\n");
223         cprintf("IMPLEMENTATION Citadel %d\r\n", REV_LEVEL);
224         cprintf("VERSION 2\r\n");
225         cprintf("READER\r\n");
226         cprintf("MODE-READER\r\n");
227         cprintf("LIST ACTIVE NEWSGROUPS\r\n");
228         cprintf("OVER\r\n");
229 #ifdef HAVE_OPENSSL
230         cprintf("STARTTLS\r\n");
231 #endif
232         if (!CC->logged_in) {
233                 cprintf("AUTHINFO USER\r\n");
234         }
235         cprintf(".\r\n");
236 }
237
238
239 // 
240 // Implements the QUIT command
241 //
242 void nntp_quit(void)
243 {
244         cprintf("221 Goodbye...\r\n");
245         CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
246 }
247
248
249 //
250 // Implements the AUTHINFO USER command (RFC 4643)
251 //
252 void nntp_authinfo_user(const char *username)
253 {
254         int a = CtdlLoginExistingUser(username);
255         switch (a) {
256         case login_already_logged_in:
257                 cprintf("482 Already logged in\r\n");
258                 return;
259         case login_too_many_users:
260                 cprintf("481 Too many users are already online (maximum is %d)\r\n", CtdlGetConfigInt("c_maxsessions"));
261                 return;
262         case login_ok:
263                 cprintf("381 Password required for %s\r\n", CC->curr_user);
264                 return;
265         case login_not_found:
266                 cprintf("481 %s not found\r\n", username);
267                 return;
268         default:
269                 cprintf("502 Internal error\r\n");
270         }
271 }
272
273
274 //
275 // Implements the AUTHINFO PASS command (RFC 4643)
276 //
277 void nntp_authinfo_pass(const char *buf)
278 {
279         int a;
280
281         a = CtdlTryPassword(buf, strlen(buf));
282
283         switch (a) {
284         case pass_already_logged_in:
285                 cprintf("482 Already logged in\r\n");
286                 return;
287         case pass_no_user:
288                 cprintf("482 Authentication commands issued out of sequence\r\n");
289                 return;
290         case pass_wrong_password:
291                 cprintf("481 Authentication failed\r\n");
292                 return;
293         case pass_ok:
294                 cprintf("281 Authentication accepted\r\n");
295                 return;
296         }
297 }
298
299
300 //
301 // Implements the AUTHINFO extension (RFC 4643) in USER/PASS mode
302 //
303 void nntp_authinfo(const char *cmd) {
304
305         if (!strncasecmp(cmd, "authinfo user ", 14)) {
306                 nntp_authinfo_user(&cmd[14]);
307         }
308
309         else if (!strncasecmp(cmd, "authinfo pass ", 14)) {
310                 nntp_authinfo_pass(&cmd[14]);
311         }
312
313         else {
314                 cprintf("502 command unavailable\r\n");
315         }
316 }
317
318
319 //
320 // Utility function to fetch the current list of message numbers in a room
321 //
322 struct nntp_msglist nntp_fetch_msglist(struct ctdlroom *qrbuf) {
323         struct nntp_msglist nm;
324         struct cdbdata *cdbfr;
325
326         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf->QRnumber, sizeof(long));
327         if (cdbfr != NULL) {
328                 nm.msgnums = (long*)cdbfr->ptr;
329                 cdbfr->ptr = NULL;
330                 nm.num_msgs = cdbfr->len / sizeof(long);
331                 cdbfr->len = 0;
332                 cdb_free(cdbfr);
333         } else {
334                 nm.num_msgs = 0;
335                 nm.msgnums = NULL;
336         }
337         return(nm);
338 }
339
340
341 //
342 // Output a room name (newsgroup name) in formats required for LIST and NEWGROUPS command
343 //
344 void output_roomname_in_list_format(struct ctdlroom *qrbuf, int which_format, char *wildmat_pattern) {
345         char n_name[1024];
346         struct nntp_msglist nm;
347         long low_water_mark = 0;
348         long high_water_mark = 0;
349
350         room_to_newsgroup(n_name, qrbuf->QRname, sizeof n_name);
351
352         if ((wildmat_pattern != NULL) && (!IsEmptyStr(wildmat_pattern))) {
353                 if (!wildmat(n_name, wildmat_pattern)) {
354                         return;
355                 }
356         }
357
358         nm = nntp_fetch_msglist(qrbuf);
359         if ((nm.num_msgs > 0) && (nm.msgnums != NULL)) {
360                 low_water_mark = nm.msgnums[0];
361                 high_water_mark = nm.msgnums[nm.num_msgs - 1];
362         }
363
364         // Only the mandatory formats are supported
365         switch(which_format) {
366         case NNTP_LIST_ACTIVE:
367                 // FIXME we have hardcoded "n" for "no posting allowed" -- fix when we add posting
368                 cprintf("%s %ld %ld n\r\n", n_name, high_water_mark, low_water_mark);
369                 break;
370         case NNTP_LIST_NEWSGROUPS:
371                 cprintf("%s %s\r\n", n_name, qrbuf->QRname);
372                 break;
373         }
374
375         if (nm.msgnums != NULL) {
376                 free(nm.msgnums);
377         }
378 }
379
380
381 //
382 // Called once per room by nntp_newgroups() to qualify and possibly output a single room
383 //
384 void nntp_newgroups_backend(struct ctdlroom *qrbuf, void *data)
385 {
386         int ra;
387         int view;
388         time_t thetime = *(time_t *)data;
389
390         CtdlRoomAccess(qrbuf, &CC->user, &ra, &view);
391
392         /*
393          * The "created after <date/time>" heuristics depend on the happy coincidence
394          * that for a very long time we have used a unix timestamp as the room record's
395          * generation number (QRgen).  When this module is merged into the master
396          * source tree we should rename QRgen to QR_create_time or something like that.
397          */
398
399         if (ra & UA_KNOWN) {
400                 if (qrbuf->QRgen >= thetime) {
401                         output_roomname_in_list_format(qrbuf, NNTP_LIST_ACTIVE, NULL);
402                 }
403         }
404 }
405
406
407 //
408 // Implements the NEWGROUPS command
409 //
410 void nntp_newgroups(const char *cmd) {
411         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
412
413         char stringy_date[16];
414         char stringy_time[16];
415         char stringy_gmt[16];
416         struct tm tm;
417         time_t thetime;
418
419         extract_token(stringy_date, cmd, 1, ' ', sizeof stringy_date);
420         extract_token(stringy_time, cmd, 2, ' ', sizeof stringy_time);
421         extract_token(stringy_gmt, cmd, 3, ' ', sizeof stringy_gmt);
422
423         memset(&tm, 0, sizeof tm);
424         if (strlen(stringy_date) == 6) {
425                 sscanf(stringy_date, "%2d%2d%2d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday);
426                 tm.tm_year += 100;
427         }
428         else {
429                 sscanf(stringy_date, "%4d%2d%2d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday);
430                 tm.tm_year -= 1900;
431         }
432         tm.tm_mon -= 1;         // tm_mon is zero based (0=January)
433         tm.tm_isdst = (-1);     // let the C library figure out whether DST is in effect
434         sscanf(stringy_time, "%2d%2d%2d", &tm.tm_hour, &tm.tm_min ,&tm.tm_sec);
435         thetime = mktime(&tm);
436         if (!strcasecmp(stringy_gmt, "GMT")) {
437                 tzset();
438                 thetime += timezone;
439         }
440
441
442         cprintf("231 list of new newsgroups follows\r\n");
443         CtdlGetUser(&CC->user, CC->curr_user);
444         CtdlForEachRoom(nntp_newgroups_backend, &thetime);
445         cprintf(".\r\n");
446 }
447
448
449 //
450 // Called once per room by nntp_list() to qualify and possibly output a single room
451 //
452 void nntp_list_backend(struct ctdlroom *qrbuf, void *data)
453 {
454         int ra;
455         int view;
456         struct nntp_list_data *nld = (struct nntp_list_data *)data;
457
458         CtdlRoomAccess(qrbuf, &CC->user, &ra, &view);
459         if (ra & UA_KNOWN) {
460                 output_roomname_in_list_format(qrbuf, nld->list_format, nld->wildmat_pattern);
461         }
462 }
463
464
465 //
466 // Implements the LIST commands
467 //
468 void nntp_list(const char *cmd) {
469         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
470
471         char list_format[64];
472         char wildmat_pattern[1024];
473         struct nntp_list_data nld;
474
475         extract_token(list_format, cmd, 1, ' ', sizeof list_format);
476         extract_token(wildmat_pattern, cmd, 2, ' ', sizeof wildmat_pattern);
477
478         if (strlen(wildmat_pattern) > 0) {
479                 nld.wildmat_pattern = wildmat_pattern;
480         }
481         else {
482                 nld.wildmat_pattern = NULL;
483         }
484
485         if ( (strlen(cmd) < 6) || (!strcasecmp(list_format, "ACTIVE")) ) {
486                 nld.list_format = NNTP_LIST_ACTIVE;
487         }
488         else if (!strcasecmp(list_format, "NEWSGROUPS")) {
489                 nld.list_format = NNTP_LIST_NEWSGROUPS;
490         }
491         else if (!strcasecmp(list_format, "OVERVIEW.FMT")) {
492                 nld.list_format = NNTP_LIST_OVERVIEW_FMT;
493         }
494         else {
495                 cprintf("501 syntax error , unsupported list format\r\n");
496                 return;
497         }
498
499         // OVERVIEW.FMT delivers a completely different type of data than all of the
500         // other LIST commands.  It's a stupid place to put it.  But that's how it's
501         // written into RFC3977, so we have to handle it here.
502         if (nld.list_format == NNTP_LIST_OVERVIEW_FMT) {
503                 cprintf("215 Order of fields in overview database.\r\n");
504                 cprintf("Subject:\r\n");
505                 cprintf("From:\r\n");
506                 cprintf("Date:\r\n");
507                 cprintf("Message-ID:\r\n");
508                 cprintf("References:\r\n");
509                 cprintf("Bytes:\r\n");
510                 cprintf("Lines:\r\n");
511                 cprintf(".\r\n");
512                 return;
513         }
514
515         cprintf("215 list of newsgroups follows\r\n");
516         CtdlGetUser(&CC->user, CC->curr_user);
517         CtdlForEachRoom(nntp_list_backend, &nld);
518         cprintf(".\r\n");
519 }
520
521
522 //
523 // Implement HELP command.
524 //
525 void nntp_help(void) {
526         cprintf("100 This is the Citadel NNTP service.\r\n");
527         cprintf("RTFM http://www.ietf.org/rfc/rfc3977.txt\r\n");
528         cprintf(".\r\n");
529 }
530
531
532 //
533 // Implement DATE command.
534 //
535 void nntp_date(void) {
536         time_t now;
537         struct tm nowLocal;
538         struct tm nowUtc;
539         char tsFromUtc[32];
540
541         now = time(NULL);
542         localtime_r(&now, &nowLocal);
543         gmtime_r(&now, &nowUtc);
544
545         strftime(tsFromUtc, sizeof(tsFromUtc), "%Y%m%d%H%M%S", &nowUtc);
546
547         cprintf("111 %s\r\n", tsFromUtc);
548 }
549
550
551 //
552 // back end for the LISTGROUP command , called for each message number
553 //
554 void nntp_listgroup_backend(long msgnum, void *userdata) {
555
556         struct listgroup_range *lr = (struct listgroup_range *)userdata;
557
558         // check range if supplied
559         if (msgnum < lr->lo) return;
560         if ((lr->hi != 0) && (msgnum > lr->hi)) return;
561
562         cprintf("%ld\r\n", msgnum);
563 }
564
565
566 //
567 // Implements the GROUP and LISTGROUP commands
568 //
569 void nntp_group(const char *cmd) {
570         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
571
572         citnntp *nntpstate = (citnntp *) CC->session_specific_data;
573         char verb[16];
574         char requested_group[1024];
575         char message_range[256];
576         char range_lo[256];
577         char range_hi[256];
578         char requested_room[ROOMNAMELEN];
579         char augmented_roomname[ROOMNAMELEN];
580         int c = 0;
581         int ok = 0;
582         int ra = 0;
583         struct ctdlroom QRscratch;
584         int msgs, new;
585         long oldest,newest;
586         struct listgroup_range lr;
587
588         extract_token(verb, cmd, 0, ' ', sizeof verb);
589         extract_token(requested_group, cmd, 1, ' ', sizeof requested_group);
590         extract_token(message_range, cmd, 2, ' ', sizeof message_range);
591         extract_token(range_lo, message_range, 0, '-', sizeof range_lo);
592         extract_token(range_hi, message_range, 1, '-', sizeof range_hi);
593         lr.lo = atoi(range_lo);
594         lr.hi = atoi(range_hi);
595
596         /* In LISTGROUP mode we can specify an empty name for 'currently selected' */
597         if ((!strcasecmp(verb, "LISTGROUP")) && (IsEmptyStr(requested_group))) {
598                 room_to_newsgroup(requested_group, CC->room.QRname, sizeof requested_group);
599         }
600
601         /* First try a regular match */
602         newsgroup_to_room(requested_room, requested_group, sizeof requested_room);
603         c = CtdlGetRoom(&QRscratch, requested_room);
604
605         /* Then try a mailbox name match */
606         if (c != 0) {
607                 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname, &CC->user, requested_room);
608                 c = CtdlGetRoom(&QRscratch, augmented_roomname);
609                 if (c == 0) {
610                         safestrncpy(requested_room, augmented_roomname, sizeof(requested_room));
611                 }
612         }
613
614         /* If the room exists, check security/access */
615         if (c == 0) {
616                 /* See if there is an existing user/room relationship */
617                 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
618
619                 /* normal clients have to pass through security */
620                 if (ra & UA_KNOWN) {
621                         ok = 1;
622                 }
623         }
624
625         /* Fail here if no such room */
626         if (!ok) {
627                 cprintf("411 no such newsgroup\r\n");
628                 return;
629         }
630
631
632         /*
633          * CtdlUserGoto() formally takes us to the desired room, happily returning
634          * the number of messages and number of new messages.
635          */
636         memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
637         CtdlUserGoto(NULL, 0, 0, &msgs, &new, &oldest, &newest);
638         cprintf("211 %d %ld %ld %s\r\n", msgs, oldest, newest, requested_group);
639
640         // If this is a GROUP command, set the "current article number" to zero, and then stop here.
641         if (!strcasecmp(verb, "GROUP")) {
642                 nntpstate->current_article_number = oldest;
643                 return;
644         }
645
646         // If we get to this point we are running a LISTGROUP command.  Fetch those message numbers.
647         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, nntp_listgroup_backend, &lr);
648         cprintf(".\r\n");
649 }
650
651
652 //
653 // Implements the MODE command
654 //
655 void nntp_mode(const char *cmd) {
656
657         char which_mode[16];
658
659         extract_token(which_mode, cmd, 1, ' ', sizeof which_mode);
660
661         if (!strcasecmp(which_mode, "reader")) {
662                 // FIXME implement posting and change to 200
663                 cprintf("201 Reader mode activated\r\n");
664         }
665         else {
666                 cprintf("501 unknown mode\r\n");
667         }
668 }
669
670
671 //
672 // Implements the ARTICLE, HEAD, BODY, and STAT commands.
673 // (These commands all accept the same parameters; they differ only in how they output the retrieved message.)
674 //
675 void nntp_article(const char *cmd) {
676         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
677
678         citnntp *nntpstate = (citnntp *) CC->session_specific_data;
679         char which_command[16];
680         int acmd = 0;
681         char requested_article[256];
682         long requested_msgnum = 0;
683         char *lb, *rb = NULL;
684         int must_change_currently_selected_article = 0;
685
686         // We're going to store one of these values in the variable 'acmd' so that
687         // we can quickly check later which version of the output we want.
688         enum {
689                 ARTICLE,
690                 HEAD,
691                 BODY,
692                 STAT
693         };
694
695         extract_token(which_command, cmd, 0, ' ', sizeof which_command);
696
697         if (!strcasecmp(which_command, "article")) {
698                 acmd = ARTICLE;
699         }
700         else if (!strcasecmp(which_command, "head")) {
701                 acmd = HEAD;
702         }
703         else if (!strcasecmp(which_command, "body")) {
704                 acmd = BODY;
705         }
706         else if (!strcasecmp(which_command, "stat")) {
707                 acmd = STAT;
708         }
709         else {
710                 cprintf("500 I'm afraid I can't do that.\r\n");
711                 return;
712         }
713
714         // Which NNTP command was issued, determines whether we will fetch headers, body, or both.
715         int                     headers_only = HEADERS_ALL;
716         if (acmd == HEAD)       headers_only = HEADERS_FAST;
717         else if (acmd == BODY)  headers_only = HEADERS_NONE;
718         else if (acmd == STAT)  headers_only = HEADERS_FAST;
719
720         // now figure out what the client is asking for.
721         extract_token(requested_article, cmd, 1, ' ', sizeof requested_article);
722         lb = strchr(requested_article, '<');
723         rb = strchr(requested_article, '>');
724         requested_msgnum = atol(requested_article);
725
726         // If no article number or message-id is specified, the client wants the "currently selected article"
727         if (IsEmptyStr(requested_article)) {
728                 if (nntpstate->current_article_number < 1) {
729                         cprintf("420 No current article selected\r\n");
730                         return;
731                 }
732                 requested_msgnum = nntpstate->current_article_number;
733                 must_change_currently_selected_article = 1;
734                 // got it -- now fall through and keep going
735         }
736
737         // If the requested article is numeric, it maps directly to a message number.  Good.
738         else if (requested_msgnum > 0) {
739                 must_change_currently_selected_article = 1;
740                 // good -- fall through and keep going
741         }
742
743         // If the requested article has angle brackets, the client wants a specific message-id.
744         // We don't know how to do that yet.
745         else if ( (lb != NULL) && (rb != NULL) && (lb < rb) ) {
746                 must_change_currently_selected_article = 0;
747                 cprintf("500 I don't know how to fetch by message-id yet.\r\n");        // FIXME
748                 return;
749         }
750
751         // Anything else is noncompliant gobbledygook and should die in a car fire.
752         else {
753                 must_change_currently_selected_article = 0;
754                 cprintf("500 syntax error\r\n");
755                 return;
756         }
757
758         // At this point we know the message number of the "article" being requested.
759         // We have an awesome API call that does all the heavy lifting for us.
760         char *fetched_message_id = NULL;
761         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
762         int fetch = CtdlOutputMsg(requested_msgnum,
763                         MT_RFC822,              // output in RFC822 format ... sort of
764                         headers_only,           // headers, body, or both?
765                         0,                      // don't do Citadel protocol responses
766                         1,                      // CRLF newlines
767                         NULL,                   // teh whole thing, not just a section
768                         0,                      // no flags yet ... maybe new ones for Path: etc ?
769                         NULL,
770                         NULL,
771                         &fetched_message_id     // extract the message ID from the message as we go...
772         );
773         StrBuf *msgtext = CC->redirect_buffer;
774         CC->redirect_buffer = NULL;
775
776         if (fetch != om_ok) {
777                 cprintf("423 no article with that number\r\n");
778                 FreeStrBuf(&msgtext);
779                 return;
780         }
781
782         // RFC3977 6.2.1.2 specifes conditions under which the "currently selected article"
783         // MUST or MUST NOT be set to the message we just referenced.
784         if (must_change_currently_selected_article) {
785                 nntpstate->current_article_number = requested_msgnum;
786         }
787
788         // Now give the client what it asked for.
789         if (acmd == ARTICLE) {
790                 cprintf("220 %ld <%s>\r\n", requested_msgnum, fetched_message_id);
791         }
792         if (acmd == HEAD) {
793                 cprintf("221 %ld <%s>\r\n", requested_msgnum, fetched_message_id);
794         }
795         if (acmd == BODY) {
796                 cprintf("222 %ld <%s>\r\n", requested_msgnum, fetched_message_id);
797         }
798         if (acmd == STAT) {
799                 cprintf("223 %ld <%s>\r\n", requested_msgnum, fetched_message_id);
800                 FreeStrBuf(&msgtext);
801                 return;
802         }
803
804         client_write(SKEY(msgtext));
805         cprintf(".\r\n");                       // this protocol uses a dot terminator
806         FreeStrBuf(&msgtext);
807         if (fetched_message_id) free(fetched_message_id);
808 }
809
810
811 //
812 // Utility function for nntp_last_next() that turns a msgnum into a message ID.
813 // The memory for the returned string is pwnz0red by the caller.
814 //
815 char *message_id_from_msgnum(long msgnum) {
816
817         char *fetched_message_id = NULL;
818         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
819         CtdlOutputMsg(msgnum,
820                         MT_RFC822,              // output in RFC822 format ... sort of
821                         HEADERS_FAST,           // headers, body, or both?
822                         0,                      // don't do Citadel protocol responses
823                         1,                      // CRLF newlines
824                         NULL,                   // teh whole thing, not just a section
825                         0,                      // no flags yet ... maybe new ones for Path: etc ?
826                         NULL,
827                         NULL,
828                         &fetched_message_id     // extract the message ID from the message as we go...
829         );
830         StrBuf *msgtext = CC->redirect_buffer;
831         CC->redirect_buffer = NULL;
832
833         FreeStrBuf(&msgtext);
834         return(fetched_message_id);
835 }
836
837
838 //
839 // The LAST and NEXT commands are so similar that they are handled by a single function.
840 //
841 void nntp_last_next(const char *cmd) {
842         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
843
844         citnntp *nntpstate = (citnntp *) CC->session_specific_data;
845         char which_command[16];
846         int acmd = 0;
847
848         // We're going to store one of these values in the variable 'acmd' so that
849         // we can quickly check later which version of the output we want.
850         enum {
851                 NNTP_LAST,
852                 NNTP_NEXT
853         };
854
855         extract_token(which_command, cmd, 0, ' ', sizeof which_command);
856
857         if (!strcasecmp(which_command, "last")) {
858                 acmd = NNTP_LAST;
859         }
860         else if (!strcasecmp(which_command, "next")) {
861                 acmd = NNTP_NEXT;
862         }
863         else {
864                 cprintf("500 I'm afraid I can't do that.\r\n");
865                 return;
866         }
867
868         // ok, here we go ... fetch the msglist so we can figure out our place in the universe
869         struct nntp_msglist nm;
870         int i = 0;
871         long selected_msgnum = 0;
872         char *message_id = NULL;
873
874         nm = nntp_fetch_msglist(&CC->room);
875         if ((nm.num_msgs < 0) || (nm.msgnums == NULL)) {
876                 cprintf("500 something bad happened\r\n");
877                 return;
878         }
879
880         if ( (acmd == NNTP_LAST) && (nm.num_msgs == 0) ) {
881                         cprintf("422 no previous article in this group\r\n");   // nothing here
882         }
883
884         else if ( (acmd == NNTP_LAST) && (nntpstate->current_article_number <= nm.msgnums[0]) ) {
885                         cprintf("422 no previous article in this group\r\n");   // already at the beginning
886         }
887
888         else if (acmd == NNTP_LAST) {
889                 for (i=0; ((i<nm.num_msgs)&&(selected_msgnum<=0)); ++i) {
890                         if ( (nm.msgnums[i] >= nntpstate->current_article_number) && (i > 0) ) {
891                                 selected_msgnum = nm.msgnums[i-1];
892                         }
893                 }
894                 if (selected_msgnum > 0) {
895                         nntpstate->current_article_number = selected_msgnum;
896                         message_id = message_id_from_msgnum(nntpstate->current_article_number);
897                         cprintf("223 %ld <%s>\r\n", nntpstate->current_article_number, message_id);
898                         if (message_id) free(message_id);
899                 }
900                 else {
901                         cprintf("422 no previous article in this group\r\n");
902                 }
903         }
904
905         else if ( (acmd == NNTP_NEXT) && (nm.num_msgs == 0) ) {
906                         cprintf("421 no next article in this group\r\n");       // nothing here
907         }
908
909         else if ( (acmd == NNTP_NEXT) && (nntpstate->current_article_number >= nm.msgnums[nm.num_msgs-1]) ) {
910                         cprintf("421 no next article in this group\r\n");       // already at the end
911         }
912
913         else if (acmd == NNTP_NEXT) {
914                 for (i=0; ((i<nm.num_msgs)&&(selected_msgnum<=0)); ++i) {
915                         if (nm.msgnums[i] > nntpstate->current_article_number) {
916                                 selected_msgnum = nm.msgnums[i];
917                         }
918                 }
919                 if (selected_msgnum > 0) {
920                         nntpstate->current_article_number = selected_msgnum;
921                         message_id = message_id_from_msgnum(nntpstate->current_article_number);
922                         cprintf("223 %ld <%s>\r\n", nntpstate->current_article_number, message_id);
923                         if (message_id) free(message_id);
924                 }
925                 else {
926                         cprintf("421 no next article in this group\r\n");
927                 }
928         }
929
930         // should never get here
931         else {
932                 cprintf("500 internal error\r\n");
933         }
934
935         if (nm.msgnums != NULL) {
936                 free(nm.msgnums);
937         }
938
939 }
940
941
942 //
943 // back end for the XOVER command , called for each message number
944 //
945 void nntp_xover_backend(long msgnum, void *userdata) {
946
947         struct listgroup_range *lr = (struct listgroup_range *)userdata;
948
949         // check range if supplied
950         if (msgnum < lr->lo) return;
951         if ((lr->hi != 0) && (msgnum > lr->hi)) return;
952
953         struct CtdlMessage *msg = CtdlFetchMessage(msgnum, 0);
954         if (msg == NULL) {
955                 return;
956         }
957
958         // Teh RFC says we need:
959         // -------------------------
960         // Subject header content
961         // From header content
962         // Date header content
963         // Message-ID header content
964         // References header content
965         // :bytes metadata item
966         // :lines metadata item
967
968         time_t msgtime = atol(msg->cm_fields[eTimestamp]);
969         char strtimebuf[26];
970         ctime_r(&msgtime, strtimebuf);
971
972         // here we go -- print the line o'data
973         cprintf("%ld\t%s\t%s <%s>\t%s\t%s\t%s\t100\t10\r\n",
974                 msgnum,
975                 msg->cm_fields[eMsgSubject],
976                 msg->cm_fields[eAuthor],
977                 msg->cm_fields[erFc822Addr],
978                 strtimebuf,
979                 msg->cm_fields[emessageId],
980                 msg->cm_fields[eWeferences]
981         );
982
983         CM_Free(msg);
984 }
985
986
987 //
988 //
989 // XOVER is used by some clients, even if we don't offer it
990 //
991 void nntp_xover(const char *cmd) {
992         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
993
994         citnntp *nntpstate = (citnntp *) CC->session_specific_data;
995         char range[256];
996         struct listgroup_range lr;
997
998         extract_token(range, cmd, 1, ' ', sizeof range);
999         lr.lo = atol(range);
1000         if (lr.lo <= 0) {
1001                 lr.lo = nntpstate->current_article_number;
1002                 lr.hi = nntpstate->current_article_number;
1003         }
1004         else {
1005                 char *dash = strchr(range, '-');
1006                 if (dash != NULL) {
1007                         ++dash;
1008                         lr.hi = atol(dash);
1009                         if (lr.hi == 0) {
1010                                 lr.hi = LONG_MAX;
1011                         }
1012                         if (lr.hi < lr.lo) {
1013                                 lr.hi = lr.lo;
1014                         }
1015                 }
1016                 else {
1017                         lr.hi = lr.lo;
1018                 }
1019         }
1020
1021         cprintf("224 Overview information follows\r\n");
1022         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, nntp_xover_backend, &lr);
1023         cprintf(".\r\n");
1024 }
1025
1026
1027 // 
1028 // Main command loop for NNTP server sessions.
1029 //
1030 void nntp_command_loop(void)
1031 {
1032         StrBuf *Cmd = NewStrBuf();
1033         char cmdname[16];
1034
1035         time(&CC->lastcmd);
1036         if (CtdlClientGetLine(Cmd) < 1) {
1037                 syslog(LOG_CRIT, "NNTP: client disconnected: ending session.\n");
1038                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
1039                 FreeStrBuf(&Cmd);
1040                 return;
1041         }
1042         syslog(LOG_DEBUG, "NNTP: %s\n", ((!strncasecmp(ChrPtr(Cmd), "AUTHINFO", 8)) ? "AUTHINFO ..." : ChrPtr(Cmd)));
1043         extract_token(cmdname, ChrPtr(Cmd), 0, ' ', sizeof cmdname);
1044
1045         // Rumpelstiltskin lookups are *awesome*
1046
1047         if (!strcasecmp(cmdname, "quit")) {
1048                 nntp_quit();
1049         }
1050
1051         else if (!strcasecmp(cmdname, "help")) {
1052                 nntp_help();
1053         }
1054
1055         else if (!strcasecmp(cmdname, "date")) {
1056                 nntp_date();
1057         }
1058
1059         else if (!strcasecmp(cmdname, "capabilities")) {
1060                 nntp_capabilities();
1061         }
1062
1063         else if (!strcasecmp(cmdname, "starttls")) {
1064                 nntp_starttls();
1065         }
1066
1067         else if (!strcasecmp(cmdname, "authinfo")) {
1068                 nntp_authinfo(ChrPtr(Cmd));
1069         }
1070
1071         else if (!strcasecmp(cmdname, "newgroups")) {
1072                 nntp_newgroups(ChrPtr(Cmd));
1073         }
1074
1075         else if (!strcasecmp(cmdname, "list")) {
1076                 nntp_list(ChrPtr(Cmd));
1077         }
1078
1079         else if (!strcasecmp(cmdname, "group")) {
1080                 nntp_group(ChrPtr(Cmd));
1081         }
1082
1083         else if (!strcasecmp(cmdname, "listgroup")) {
1084                 nntp_group(ChrPtr(Cmd));
1085         }
1086
1087         else if (!strcasecmp(cmdname, "mode")) {
1088                 nntp_mode(ChrPtr(Cmd));
1089         }
1090
1091         else if (
1092                         (!strcasecmp(cmdname, "article"))
1093                         || (!strcasecmp(cmdname, "head"))
1094                         || (!strcasecmp(cmdname, "body"))
1095                         || (!strcasecmp(cmdname, "stat"))
1096                 )
1097         {
1098                 nntp_article(ChrPtr(Cmd));
1099         }
1100
1101         else if (
1102                         (!strcasecmp(cmdname, "last"))
1103                         || (!strcasecmp(cmdname, "next"))
1104                 )
1105         {
1106                 nntp_last_next(ChrPtr(Cmd));
1107         }
1108
1109         else if (
1110                         (!strcasecmp(cmdname, "xover"))
1111                         || (!strcasecmp(cmdname, "over"))
1112                 )
1113         {
1114                 nntp_xover(ChrPtr(Cmd));
1115         }
1116
1117         else {
1118                 cprintf("500 I'm afraid I can't do that.\r\n");
1119         }
1120
1121         FreeStrBuf(&Cmd);
1122 }
1123
1124
1125 //      ****************************************************************************
1126 //                            MODULE INITIALIZATION STUFF
1127 //      ****************************************************************************
1128
1129
1130 //
1131 // This cleanup function blows away the temporary memory used by
1132 // the NNTP server.
1133 //
1134 void nntp_cleanup_function(void)
1135 {
1136         /* Don't do this stuff if this is not an NNTP session! */
1137         if (CC->h_command_function != nntp_command_loop) return;
1138
1139         syslog(LOG_DEBUG, "Performing NNTP cleanup hook\n");
1140         citnntp *nntpstate = (citnntp *) CC->session_specific_data;
1141         if (nntpstate != NULL) {
1142                 free(nntpstate);
1143                 nntpstate = NULL;
1144         }
1145 }
1146
1147 const char *CitadelServiceNNTP="NNTP";
1148 const char *CitadelServiceNNTPS="NNTPS";
1149
1150 CTDL_MODULE_INIT(nntp)
1151 {
1152         if (!threading)
1153         {
1154                 CtdlRegisterServiceHook(CtdlGetConfigInt("c_nntp_port"),
1155                                         NULL,
1156                                         nntp_greeting,
1157                                         nntp_command_loop,
1158                                         NULL, 
1159                                         CitadelServiceNNTP);
1160
1161 #ifdef HAVE_OPENSSL
1162                 CtdlRegisterServiceHook(CtdlGetConfigInt("c_nntps_port"),
1163                                         NULL,
1164                                         nntps_greeting,
1165                                         nntp_command_loop,
1166                                         NULL,
1167                                         CitadelServiceNNTPS);
1168 #endif
1169
1170                 CtdlRegisterSessionHook(nntp_cleanup_function, EVT_STOP, PRIO_STOP + 250);
1171         }
1172         
1173         /* return our module name for the log */
1174         return "nntp";
1175 }