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