1e686d3bc1cc92b53299c66af109333f2507a74d
[citadel.git] / citadel / modules / nntp / serv_nntp.c
1 //
2 // NNTP server module (RFC 3977)
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         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", config.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 v%d.%02d\r\n", (REV_LEVEL/100), (REV_LEVEL%100));
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(NULL, 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", config.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                 cprintf("201 Reader mode FIXME implement posting and change to 200\r\n");
690         }
691         else {
692                 cprintf("501 unknown mode\r\n");
693         }
694 }
695
696
697 //
698 // Implements the ARTICLE, HEAD, BODY, and STAT commands.
699 // (These commands all accept the same parameters; they differ only in how they output the retrieved message.)
700 //
701 void nntp_article(const char *cmd) {
702         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
703
704         citnntp *nntpstate = (citnntp *) CC->session_specific_data;
705         char which_command[16];
706         int acmd = 0;
707         char requested_article[256];
708         long requested_msgnum = 0;
709         char *lb, *rb = NULL;
710         int must_change_currently_selected_article = 0;
711
712         // We're going to store one of these values in the variable 'acmd' so that
713         // we can quickly check later which version of the output we want.
714         enum {
715                 ARTICLE,
716                 HEAD,
717                 BODY,
718                 STAT
719         };
720
721         extract_token(which_command, cmd, 0, ' ', sizeof which_command);
722
723         if (!strcasecmp(which_command, "article")) {
724                 acmd = ARTICLE;
725         }
726         else if (!strcasecmp(which_command, "head")) {
727                 acmd = HEAD;
728         }
729         else if (!strcasecmp(which_command, "body")) {
730                 acmd = BODY;
731         }
732         else if (!strcasecmp(which_command, "stat")) {
733                 acmd = STAT;
734         }
735         else {
736                 cprintf("500 I'm afraid I can't do that.\r\n");
737                 return;
738         }
739
740         // Which NNTP command was issued, determines whether we will fetch headers, body, or both.
741         int                     headers_only = HEADERS_ALL;
742         if (acmd == HEAD)       headers_only = HEADERS_FAST;
743         else if (acmd == BODY)  headers_only = HEADERS_NONE;
744         else if (acmd == STAT)  headers_only = HEADERS_FAST;
745
746         // now figure out what the client is asking for.
747         extract_token(requested_article, cmd, 1, ' ', sizeof requested_article);
748         lb = strchr(requested_article, '<');
749         rb = strchr(requested_article, '>');
750         requested_msgnum = atol(requested_article);
751
752         // If no article number or message-id is specified, the client wants the "currently selected article"
753         if (IsEmptyStr(requested_article)) {
754                 if (nntpstate->current_article_number < 1) {
755                         cprintf("420 No current article selected\r\n");
756                         return;
757                 }
758                 requested_msgnum = nntpstate->current_article_number;
759                 must_change_currently_selected_article = 1;
760                 // got it -- now fall through and keep going
761         }
762
763         // If the requested article is numeric, it maps directly to a message number.  Good.
764         else if (requested_msgnum > 0) {
765                 must_change_currently_selected_article = 1;
766                 // good -- fall through and keep going
767         }
768
769         // If the requested article has angle brackets, the client wants a specific message-id.
770         // We don't know how to do that yet.
771         else if ( (lb != NULL) && (rb != NULL) && (lb < rb) ) {
772                 must_change_currently_selected_article = 0;
773                 cprintf("500 FIXME I don't know how to fetch by message-id yet.\r\n");
774                 return;
775         }
776
777         // Anything else is noncompliant gobbledygook and should die in a car fire.
778         else {
779                 must_change_currently_selected_article = 0;
780                 cprintf("500 syntax error\r\n");
781                 return;
782         }
783
784         // At this point we know the message number of the "article" being requested.
785         // We have an awesome API call that does all the heavy lifting for us.
786         char *fetched_message_id = NULL;
787         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
788         int fetch = CtdlOutputMsg(requested_msgnum,
789                         MT_RFC822,              // output in RFC822 format ... sort of
790                         headers_only,           // headers, body, or both?
791                         0,                      // don't do Citadel protocol responses
792                         1,                      // CRLF newlines
793                         NULL,                   // teh whole thing, not just a section
794                         0,                      // no flags yet ... maybe new ones for Path: etc ?
795                         NULL,
796                         NULL,
797                         &fetched_message_id     // extract the message ID from the message as we go...
798         );
799         StrBuf *msgtext = CC->redirect_buffer;
800         CC->redirect_buffer = NULL;
801
802         if (fetch != om_ok) {
803                 cprintf("423 no article with that number\r\n");
804                 FreeStrBuf(&msgtext);
805                 return;
806         }
807
808         // RFC3977 6.2.1.2 specifes conditions under which the "currently selected article"
809         // MUST or MUST NOT be set to the message we just referenced.
810         if (must_change_currently_selected_article) {
811                 nntpstate->current_article_number = requested_msgnum;
812         }
813
814         // Now give the client what it asked for.
815         if (acmd == ARTICLE) {
816                 cprintf("220 %ld <%s>\r\n", requested_msgnum, fetched_message_id);
817         }
818         if (acmd == HEAD) {
819                 cprintf("221 %ld <%s>\r\n", requested_msgnum, fetched_message_id);
820         }
821         if (acmd == BODY) {
822                 cprintf("222 %ld <%s>\r\n", requested_msgnum, fetched_message_id);
823         }
824         if (acmd == STAT) {
825                 cprintf("223 %ld <%s>\r\n", requested_msgnum, fetched_message_id);
826                 FreeStrBuf(&msgtext);
827                 return;
828         }
829
830         client_write(SKEY(msgtext));
831         cprintf(".\r\n");                       // this protocol uses a dot terminator
832         FreeStrBuf(&msgtext);
833         if (fetched_message_id) free(fetched_message_id);
834 }
835
836
837 //
838 // Utility function for nntp_last_next() that turns a msgnum into a message ID.
839 // The memory for the returned string is pwnz0red by the caller.
840 //
841 char *message_id_from_msgnum(long msgnum) {
842
843         char *fetched_message_id = NULL;
844         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
845         CtdlOutputMsg(msgnum,
846                         MT_RFC822,              // output in RFC822 format ... sort of
847                         HEADERS_FAST,           // headers, body, or both?
848                         0,                      // don't do Citadel protocol responses
849                         1,                      // CRLF newlines
850                         NULL,                   // teh whole thing, not just a section
851                         0,                      // no flags yet ... maybe new ones for Path: etc ?
852                         NULL,
853                         NULL,
854                         &fetched_message_id     // extract the message ID from the message as we go...
855         );
856         StrBuf *msgtext = CC->redirect_buffer;
857         CC->redirect_buffer = NULL;
858
859         FreeStrBuf(&msgtext);
860         return(fetched_message_id);
861 }
862
863
864 //
865 // The LAST and NEXT commands are so similar that they are handled by a single function.
866 //
867 void nntp_last_next(const char *cmd) {
868         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
869
870         citnntp *nntpstate = (citnntp *) CC->session_specific_data;
871         char which_command[16];
872         int acmd = 0;
873
874         // We're going to store one of these values in the variable 'acmd' so that
875         // we can quickly check later which version of the output we want.
876         enum {
877                 NNTP_LAST,
878                 NNTP_NEXT
879         };
880
881         extract_token(which_command, cmd, 0, ' ', sizeof which_command);
882
883         if (!strcasecmp(which_command, "last")) {
884                 acmd = NNTP_LAST;
885         }
886         else if (!strcasecmp(which_command, "next")) {
887                 acmd = NNTP_NEXT;
888         }
889         else {
890                 cprintf("500 I'm afraid I can't do that.\r\n");
891                 return;
892         }
893
894         // ok, here we go ... fetch the msglist so we can figure out our place in the universe
895         struct nntp_msglist nm;
896         int i = 0;
897         long selected_msgnum = 0;
898         char *message_id = NULL;
899
900         nm = nntp_fetch_msglist(&CC->room);
901         if ((nm.num_msgs < 0) || (nm.msgnums == NULL)) {
902                 cprintf("500 something bad happened\r\n");
903                 return;
904         }
905
906         if ( (acmd == NNTP_LAST) && (nm.num_msgs == 0) ) {
907                         cprintf("422 no previous article in this group\r\n");   // nothing here
908         }
909
910         else if ( (acmd == NNTP_LAST) && (nntpstate->current_article_number <= nm.msgnums[0]) ) {
911                         cprintf("422 no previous article in this group\r\n");   // already at the beginning
912         }
913
914         else if (acmd == NNTP_LAST) {
915                 for (i=0; ((i<nm.num_msgs)&&(selected_msgnum<=0)); ++i) {
916                         if ( (nm.msgnums[i] >= nntpstate->current_article_number) && (i > 0) ) {
917                                 selected_msgnum = nm.msgnums[i-1];
918                         }
919                 }
920                 if (selected_msgnum > 0) {
921                         nntpstate->current_article_number = selected_msgnum;
922                         message_id = message_id_from_msgnum(nntpstate->current_article_number);
923                         cprintf("223 %ld <%s>\r\n", nntpstate->current_article_number, message_id);
924                         if (message_id) free(message_id);
925                 }
926                 else {
927                         cprintf("422 no previous article in this group\r\n");
928                 }
929         }
930
931         else if ( (acmd == NNTP_NEXT) && (nm.num_msgs == 0) ) {
932                         cprintf("421 no next article in this group\r\n");       // nothing here
933         }
934
935         else if ( (acmd == NNTP_NEXT) && (nntpstate->current_article_number >= nm.msgnums[nm.num_msgs-1]) ) {
936                         cprintf("421 no next article in this group\r\n");       // already at the end
937         }
938
939         else if (acmd == NNTP_NEXT) {
940                 for (i=0; ((i<nm.num_msgs)&&(selected_msgnum<=0)); ++i) {
941                         if (nm.msgnums[i] > nntpstate->current_article_number) {
942                                 selected_msgnum = nm.msgnums[i];
943                         }
944                 }
945                 if (selected_msgnum > 0) {
946                         nntpstate->current_article_number = selected_msgnum;
947                         message_id = message_id_from_msgnum(nntpstate->current_article_number);
948                         cprintf("223 %ld <%s>\r\n", nntpstate->current_article_number, message_id);
949                         if (message_id) free(message_id);
950                 }
951                 else {
952                         cprintf("421 no next article in this group\r\n");
953                 }
954         }
955
956         // should never get here
957         else {
958                 cprintf("500 internal error\r\n");
959         }
960
961         if (nm.msgnums != NULL) {
962                 free(nm.msgnums);
963         }
964
965 }
966
967
968 //
969 // back end for the XOVER command , called for each message number
970 //
971 void nntp_xover_backend(long msgnum, void *userdata) {
972
973         struct listgroup_range *lr = (struct listgroup_range *)userdata;
974
975         // check range if supplied
976         if (msgnum < lr->lo) return;
977         if ((lr->hi != 0) && (msgnum > lr->hi)) return;
978
979         struct CtdlMessage *msg = CtdlFetchMessage(msgnum, 0);
980         if (msg == NULL) {
981                 return;
982         }
983
984         // Teh RFC says we need:
985         // -------------------------
986         // Subject header content
987         // From header content
988         // Date header content
989         // Message-ID header content
990         // References header content
991         // :bytes metadata item
992         // :lines metadata item
993
994         time_t msgtime = atol(msg->cm_fields[eTimestamp]);
995         char strtimebuf[26];
996         ctime_r(&msgtime, strtimebuf);
997
998         // here we go -- print the line o'data
999         cprintf("%ld\t%s\t%s <%s>\t%s\t%s\t%s\t100\t10\r\n",
1000                 msgnum,
1001                 msg->cm_fields[eMsgSubject],
1002                 msg->cm_fields[eAuthor],
1003                 msg->cm_fields[erFc822Addr],
1004                 strtimebuf,
1005                 msg->cm_fields[emessageId],
1006                 msg->cm_fields[eWeferences]
1007         );
1008
1009         CM_Free(msg);
1010 }
1011
1012
1013 //
1014 //
1015 // XOVER is used by some clients, even if we don't offer it
1016 //
1017 void nntp_xover(const char *cmd) {
1018         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
1019
1020         citnntp *nntpstate = (citnntp *) CC->session_specific_data;
1021         char range[256];
1022         struct listgroup_range lr;
1023
1024         extract_token(range, cmd, 1, ' ', sizeof range);
1025         lr.lo = atol(range);
1026         if (lr.lo <= 0) {
1027                 lr.lo = nntpstate->current_article_number;
1028                 lr.hi = nntpstate->current_article_number;
1029         }
1030         else {
1031                 char *dash = strchr(range, '-');
1032                 if (dash != NULL) {
1033                         ++dash;
1034                         lr.hi = atol(dash);
1035                         if (lr.hi == 0) {
1036                                 lr.hi = LONG_MAX;
1037                         }
1038                         if (lr.hi < lr.lo) {
1039                                 lr.hi = lr.lo;
1040                         }
1041                 }
1042                 else {
1043                         lr.hi = lr.lo;
1044                 }
1045         }
1046
1047         cprintf("224 Overview information follows\r\n");
1048         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, nntp_xover_backend, &lr);
1049         cprintf(".\r\n");
1050 }
1051
1052
1053 // 
1054 // Main command loop for NNTP server sessions.
1055 //
1056 void nntp_command_loop(void)
1057 {
1058         StrBuf *Cmd = NewStrBuf();
1059         char cmdname[16];
1060
1061         time(&CC->lastcmd);
1062         if (CtdlClientGetLine(Cmd) < 1) {
1063                 syslog(LOG_CRIT, "NNTP: client disconnected: ending session.\n");
1064                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
1065                 FreeStrBuf(&Cmd);
1066                 return;
1067         }
1068         syslog(LOG_DEBUG, "NNTP: %s\n", ((!strncasecmp(ChrPtr(Cmd), "AUTHINFO", 8)) ? "AUTHINFO ..." : ChrPtr(Cmd)));
1069         extract_token(cmdname, ChrPtr(Cmd), 0, ' ', sizeof cmdname);
1070
1071         // Rumpelstiltskin lookups are *awesome*
1072
1073         if (!strcasecmp(cmdname, "quit")) {
1074                 nntp_quit();
1075         }
1076
1077         else if (!strcasecmp(cmdname, "help")) {
1078                 nntp_help();
1079         }
1080
1081         else if (!strcasecmp(cmdname, "date")) {
1082                 nntp_date();
1083         }
1084
1085         else if (!strcasecmp(cmdname, "capabilities")) {
1086                 nntp_capabilities();
1087         }
1088
1089         else if (!strcasecmp(cmdname, "starttls")) {
1090                 nntp_starttls();
1091         }
1092
1093         else if (!strcasecmp(cmdname, "authinfo")) {
1094                 nntp_authinfo(ChrPtr(Cmd));
1095         }
1096
1097         else if (!strcasecmp(cmdname, "newgroups")) {
1098                 nntp_newgroups(ChrPtr(Cmd));
1099         }
1100
1101         else if (!strcasecmp(cmdname, "list")) {
1102                 nntp_list(ChrPtr(Cmd));
1103         }
1104
1105         else if (!strcasecmp(cmdname, "group")) {
1106                 nntp_group(ChrPtr(Cmd));
1107         }
1108
1109         else if (!strcasecmp(cmdname, "listgroup")) {
1110                 nntp_group(ChrPtr(Cmd));
1111         }
1112
1113         else if (!strcasecmp(cmdname, "mode")) {
1114                 nntp_mode(ChrPtr(Cmd));
1115         }
1116
1117         else if (
1118                         (!strcasecmp(cmdname, "article"))
1119                         || (!strcasecmp(cmdname, "head"))
1120                         || (!strcasecmp(cmdname, "body"))
1121                         || (!strcasecmp(cmdname, "stat"))
1122                 )
1123         {
1124                 nntp_article(ChrPtr(Cmd));
1125         }
1126
1127         else if (
1128                         (!strcasecmp(cmdname, "last"))
1129                         || (!strcasecmp(cmdname, "next"))
1130                 )
1131         {
1132                 nntp_last_next(ChrPtr(Cmd));
1133         }
1134
1135         else if (
1136                         (!strcasecmp(cmdname, "xover"))
1137                         || (!strcasecmp(cmdname, "over"))
1138                 )
1139         {
1140                 nntp_xover(ChrPtr(Cmd));
1141         }
1142
1143         else {
1144                 cprintf("500 I'm afraid I can't do that.\r\n");
1145         }
1146
1147         FreeStrBuf(&Cmd);
1148 }
1149
1150
1151 //      ****************************************************************************
1152 //                            MODULE INITIALIZATION STUFF
1153 //      ****************************************************************************
1154
1155
1156 //
1157 // This cleanup function blows away the temporary memory used by
1158 // the NNTP server.
1159 //
1160 void nntp_cleanup_function(void)
1161 {
1162         /* Don't do this stuff if this is not an NNTP session! */
1163         if (CC->h_command_function != nntp_command_loop) return;
1164
1165         syslog(LOG_DEBUG, "Performing NNTP cleanup hook\n");
1166         citnntp *nntpstate = (citnntp *) CC->session_specific_data;
1167         if (nntpstate != NULL) {
1168                 free(nntpstate);
1169                 nntpstate = NULL;
1170         }
1171 }
1172
1173 const char *CitadelServiceNNTP="NNTP";
1174
1175 CTDL_MODULE_INIT(nntp)
1176 {
1177         if (!threading)
1178         {
1179                 CtdlRegisterServiceHook(119,                    // FIXME config.c_nntp_port,
1180                                         NULL,
1181                                         nntp_greeting,
1182                                         nntp_command_loop,
1183                                         NULL, 
1184                                         CitadelServiceNNTP);
1185
1186 #ifdef HAVE_OPENSSL
1187                 CtdlRegisterServiceHook(563,                    // FIXME config.c_nntps_port,
1188                                         NULL,
1189                                         nntps_greeting,
1190                                         nntp_command_loop,
1191                                         NULL,
1192                                         CitadelServiceNNTP);
1193 #endif
1194
1195                 CtdlRegisterCleanupHook(nntp_cleanup);
1196                 CtdlRegisterSessionHook(nntp_cleanup_function, EVT_STOP, PRIO_STOP + 250);
1197         }
1198         
1199         /* return our module name for the log */
1200         return "nntp";
1201 }