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