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