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