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