28edae8e642c9eb827c982e4866e364843c48c3a
[citadel.git] / citadel / modules / nntp / serv_nntp.c
1 //
2 // NNTP server module FIXME THIS IS NOT FINISHED
3 //
4 // Copyright (c) 2014 by the citadel.org team
5 //
6 // This program is open source software; you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License version 3.
8 //  
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14
15 #include "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <termios.h>
20 #include <fcntl.h>
21 #include <signal.h>
22 #include <pwd.h>
23 #include <errno.h>
24 #include <sys/types.h>
25 #include <syslog.h>
26
27 #if TIME_WITH_SYS_TIME
28 # include <sys/time.h>
29 # include <time.h>
30 #else
31 # if HAVE_SYS_TIME_H
32 #  include <sys/time.h>
33 # else
34 #  include <time.h>
35 # endif
36 #endif
37
38 #include <sys/wait.h>
39 #include <ctype.h>
40 #include <string.h>
41 #include <limits.h>
42 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45 #include <libcitadel.h>
46 #include "citadel.h"
47 #include "server.h"
48 #include "citserver.h"
49 #include "support.h"
50 #include "config.h"
51 #include "control.h"
52 #include "user_ops.h"
53 #include "room_ops.h"
54 #include "database.h"
55 #include "msgbase.h"
56 #include "internet_addressing.h"
57 #include "genstamp.h"
58 #include "domain.h"
59 #include "clientsocket.h"
60 #include "locate_host.h"
61 #include "citadel_dirs.h"
62 #include "ctdl_module.h"
63 #include "serv_nntp.h"
64
65 extern long timezone;
66
67 //      ***************** BEGIN UTILITY FUNCTIONS THAT COULD BE MOVED ELSEWHERE LATER **************
68
69
70 //
71 // Tests whether the supplied string is a valid newsgroup name
72 // Returns true (nonzero) or false (0)
73 //
74 int is_valid_newsgroup_name(char *name) {
75         char *ptr = name;
76         int has_a_letter = 0;
77
78         if (!ptr) return(0);
79         if (!strncasecmp(name, "ctdl.", 5)) return(0);
80
81         while (*ptr != 0) {
82
83                 if (isalpha(ptr[0])) {
84                         has_a_letter = 1;
85                 }
86
87                 if (    (isalnum(ptr[0]))
88                         || (ptr[0] == '.')
89                         || (ptr[0] == '+')
90                         || (ptr[0] == '-')
91                 ) {
92                         ++ptr;
93                 }
94                 else {
95                         return(0);
96                 }
97         }
98         return(has_a_letter);
99 }
100
101
102
103 //
104 // Convert a Citadel room name to a valid newsgroup name
105 //
106 void room_to_newsgroup(char *target, char *source, size_t target_size) {
107
108         if (!target) return;
109         if (!source) return;
110
111         if (is_valid_newsgroup_name(source)) {
112                 strncpy(target, source, target_size);
113                 return;
114         }
115
116         strcpy(target, "ctdl.");
117         int len = 5;
118         char *ptr = source;
119         char ch;
120
121         while (ch=*ptr++, ch!=0) {
122                 if (len >= target_size) return;
123                 if (    (isalnum(ch))
124                         || (ch == '.')
125                         || (ch == '-')
126                 ) {
127                         target[len++] = ch;
128                         target[len] = 0;
129                 }
130                 else {
131                         target[len++] = '+' ;
132                         sprintf(&target[len], "%02x", ch);
133                         len += 2;
134                         target[len] = 0;
135                 }
136         }
137 }
138
139
140 //
141 // Convert a newsgroup name to a Citadel room name.
142 // This function recognizes names converted with room_to_newsgroup() and restores them with full fidelity.
143 //
144 void newsgroup_to_room(char *target, char *source, size_t target_size) {
145
146         if (!target) return;
147         if (!source) return;
148
149         if (strncasecmp(source, "ctdl.", 5)) {                  // not a converted room name; pass through as-is
150                 strncpy(target, source, target_size);
151                 return;
152         }
153
154         target[0] = 0;
155         int len = 0;
156         char *ptr = &source[5];
157         char ch;
158
159         while (ch=*ptr++, ch!=0) {
160                 if (len >= target_size) return;
161                 if (ch == '+') {
162                         char hex[3];
163                         long digit;
164                         hex[0] = *ptr++;
165                         hex[1] = *ptr++;
166                         hex[2] = 0;
167                         digit = strtol(hex, NULL, 16);
168                         ch = (char)digit;
169                 }
170                 target[len++] = ch;
171                 target[len] = 0;
172         }
173 }
174
175
176 //      *****************  END  UTILITY FUNCTIONS THAT COULD BE MOVED ELSEWHERE LATER **************
177
178
179
180 //
181 // Here's where our NNTP session begins its happy day.
182 //
183 void nntp_greeting(void)
184 {
185         strcpy(CC->cs_clientname, "NNTP session");
186         CC->cs_flags |= CS_STEALTH;
187
188         CC->session_specific_data = malloc(sizeof(citnntp));
189         citnntp *nntpstate = (citnntp *) CC->session_specific_data;
190         memset(nntpstate, 0, sizeof(citnntp));
191
192         if (CC->nologin==1) {
193                 cprintf("451 Too many connections are already open; please try again later.\r\n");
194                 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
195                 return;
196         }
197
198         // Note: the FQDN *must* appear as the first thing after the 220 code.
199         // Some clients (including citmail.c) depend on it being there.
200         //
201         cprintf("200 %s NNTP Citadel server is not finished yet\r\n", config.c_fqdn);
202 }
203
204
205 //
206 // NNTPS is just like NNTP, except it goes crypto right away.
207 //
208 void nntps_greeting(void) {
209         CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
210 #ifdef HAVE_OPENSSL
211         if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO;          /* kill session if no crypto */
212 #endif
213         nntp_greeting();
214 }
215
216
217
218 //
219 // implements the STARTTLS command
220 //
221 void nntp_starttls(void)
222 {
223         char ok_response[SIZ];
224         char nosup_response[SIZ];
225         char error_response[SIZ];
226
227         sprintf(ok_response, "382 Begin TLS negotiation now\r\n");
228         sprintf(nosup_response, "502 Can not initiate TLS negotiation\r\n");
229         sprintf(error_response, "580 Internal error\r\n");
230         CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
231 }
232
233
234 //
235 // Implements the CAPABILITY command
236 //
237 void nntp_capabilities(void)
238 {
239         cprintf("101 Capability list:\r\n");
240         cprintf("IMPLEMENTATION Citadel v%d.%02d\r\n", (REV_LEVEL/100), (REV_LEVEL%100));
241         cprintf("VERSION 2\r\n");
242         cprintf("READER\r\n");
243         cprintf("MODE-READER\r\n");
244         cprintf("LIST ACTIVE NEWSGROUPS\r\n");
245 #ifdef HAVE_OPENSSL
246         cprintf("STARTTLS\r\n");
247 #endif
248         if (!CC->logged_in) {
249                 cprintf("AUTHINFO USER\r\n");
250         }
251         cprintf(".\r\n");
252 }
253
254
255 // 
256 // Implements the QUIT command
257 //
258 void nntp_quit(void)
259 {
260         cprintf("221 Goodbye...\r\n");
261         CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
262 }
263
264
265 //
266 // Cleanup hook for this module
267 //
268 void nntp_cleanup(void)
269 {
270         /* nothing here yet */
271 }
272
273
274
275 //
276 // Implements the AUTHINFO USER command (RFC 4643)
277 //
278 void nntp_authinfo_user(const char *username)
279 {
280         int a = CtdlLoginExistingUser(NULL, username);
281         switch (a) {
282         case login_already_logged_in:
283                 cprintf("482 Already logged in\r\n");
284                 return;
285         case login_too_many_users:
286                 cprintf("481 Too many users are already online (maximum is %d)\r\n", config.c_maxsessions);
287                 return;
288         case login_ok:
289                 cprintf("381 Password required for %s\r\n", CC->curr_user);
290                 return;
291         case login_not_found:
292                 cprintf("481 %s not found\r\n", username);
293                 return;
294         default:
295                 cprintf("502 Internal error\r\n");
296         }
297 }
298
299
300 //
301 // Implements the AUTHINFO PASS command (RFC 4643)
302 //
303 void nntp_authinfo_pass(const char *buf)
304 {
305         int a;
306
307         a = CtdlTryPassword(buf, strlen(buf));
308
309         switch (a) {
310         case pass_already_logged_in:
311                 cprintf("482 Already logged in\r\n");
312                 return;
313         case pass_no_user:
314                 cprintf("482 Authentication commands issued out of sequence\r\n");
315                 return;
316         case pass_wrong_password:
317                 cprintf("481 Authentication failed\r\n");
318                 return;
319         case pass_ok:
320                 cprintf("281 Authentication accepted\r\n");
321                 return;
322         }
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 //
370 // Various output formats for the LIST commands
371 //
372 enum {
373         NNTP_LIST_ACTIVE,
374         NNTP_LIST_ACTIVE_TIMES,
375         NNTP_LIST_DISTRIB_PATS,
376         NNTP_LIST_HEADERS,
377         NNTP_LIST_NEWSGROUPS,
378         NNTP_LIST_OVERVIEW_FMT
379 };
380
381
382 //
383 // Output a room name (newsgroup name) in formats required for LIST and NEWGROUPS command
384 //
385 void output_roomname_in_list_format(struct ctdlroom *qrbuf, int which_format, char *wildmat_pattern) {
386         char n_name[1024];
387         struct nntp_msglist nm;
388         long low_water_mark = 0;
389         long high_water_mark = 0;
390
391         room_to_newsgroup(n_name, qrbuf->QRname, sizeof n_name);
392
393         if ((wildmat_pattern != NULL) && (!IsEmptyStr(wildmat_pattern))) {
394                 if (!wildmat(n_name, wildmat_pattern)) {
395                         return;
396                 }
397         }
398
399         nm = nntp_fetch_msglist(qrbuf);
400         if ((nm.num_msgs > 0) && (nm.msgnums != NULL)) {
401                 low_water_mark = nm.msgnums[0];
402                 high_water_mark = nm.msgnums[nm.num_msgs - 1];
403         }
404
405         // Only the mandatory formats are supported
406         switch(which_format) {
407         case NNTP_LIST_ACTIVE:
408                 // FIXME we have hardcoded "n" for "no posting allowed" -- fix when we add posting
409                 cprintf("%s %ld %ld n\r\n", n_name, high_water_mark, low_water_mark);
410                 break;
411         case NNTP_LIST_NEWSGROUPS:
412                 cprintf("%s %s\r\n", n_name, qrbuf->QRname);
413                 break;
414         }
415
416         if (nm.msgnums != NULL) {
417                 free(nm.msgnums);
418         }
419 }
420
421
422
423 //
424 // Called once per room by nntp_newgroups() to qualify and possibly output a single room
425 //
426 void nntp_newgroups_backend(struct ctdlroom *qrbuf, void *data)
427 {
428         int ra;
429         int view;
430         time_t thetime = *(time_t *)data;
431
432         CtdlRoomAccess(qrbuf, &CC->user, &ra, &view);
433
434         /*
435          * The "created after <date/time>" heuristics depend on the happy coincidence
436          * that for a very long time we have used a unix timestamp as the room record's
437          * generation number (QRgen).  When this module is merged into the master
438          * source tree we should rename QRgen to QR_create_time or something like that.
439          */
440
441         if (ra & UA_KNOWN) {
442                 if (qrbuf->QRgen >= thetime) {
443                         output_roomname_in_list_format(qrbuf, NNTP_LIST_ACTIVE, NULL);
444                 }
445         }
446 }
447
448
449 //
450 // Implements the NEWGROUPS command
451 //
452 void nntp_newgroups(const char *cmd) {
453         /*
454          * HACK: this works because the 5XX series error codes from citadel
455          * protocol will also be considered error codes by an NNTP client
456          */
457         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
458
459
460         char stringy_date[16];
461         char stringy_time[16];
462         char stringy_gmt[16];
463         struct tm tm;
464         time_t thetime;
465
466         extract_token(stringy_date, cmd, 1, ' ', sizeof stringy_date);
467         extract_token(stringy_time, cmd, 2, ' ', sizeof stringy_time);
468         extract_token(stringy_gmt, cmd, 3, ' ', sizeof stringy_gmt);
469
470         memset(&tm, 0, sizeof tm);
471         if (strlen(stringy_date) == 6) {
472                 sscanf(stringy_date, "%2d%2d%2d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday);
473                 tm.tm_year += 100;
474         }
475         else {
476                 sscanf(stringy_date, "%4d%2d%2d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday);
477                 tm.tm_year -= 1900;
478         }
479         tm.tm_mon -= 1;         // tm_mon is zero based (0=January)
480         tm.tm_isdst = (-1);     // let the C library figure out whether DST is in effect
481         sscanf(stringy_time, "%2d%2d%2d", &tm.tm_hour, &tm.tm_min ,&tm.tm_sec);
482         thetime = mktime(&tm);
483         if (!strcasecmp(stringy_gmt, "GMT")) {
484                 tzset();
485                 thetime += timezone;
486         }
487
488
489         cprintf("231 list of new newsgroups follows\r\n");
490         CtdlGetUser(&CC->user, CC->curr_user);
491         CtdlForEachRoom(nntp_newgroups_backend, &thetime);
492         cprintf(".\r\n");
493 }
494
495
496 //
497 // Called once per room by nntp_list() to qualify and possibly output a single room
498 //
499 void nntp_list_backend(struct ctdlroom *qrbuf, void *data)
500 {
501         int ra;
502         int view;
503         struct nntp_list_data *nld = (struct nntp_list_data *)data;
504
505         CtdlRoomAccess(qrbuf, &CC->user, &ra, &view);
506         if (ra & UA_KNOWN) {
507                 output_roomname_in_list_format(qrbuf, nld->list_format, nld->wildmat_pattern);
508         }
509 }
510
511
512 //
513 // Implements the LIST commands
514 //
515 void nntp_list(const char *cmd) {
516         //
517         // HACK: this works because the 5XX series error codes from citadel
518         // protocol will also be considered error codes by an NNTP client
519         //
520         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
521
522         char list_format[64];
523         char wildmat_pattern[1024];
524         struct nntp_list_data nld;
525
526         extract_token(list_format, cmd, 1, ' ', sizeof list_format);
527         extract_token(wildmat_pattern, cmd, 2, ' ', sizeof wildmat_pattern);
528
529         if (strlen(wildmat_pattern) > 0) {
530                 nld.wildmat_pattern = wildmat_pattern;
531         }
532         else {
533                 nld.wildmat_pattern = NULL;
534         }
535
536         if ( (strlen(cmd) < 6) || (!strcasecmp(list_format, "ACTIVE")) ) {
537                 nld.list_format = NNTP_LIST_ACTIVE;
538         }
539         else if (!strcasecmp(list_format, "NEWSGROUPS")) {
540                 nld.list_format = NNTP_LIST_NEWSGROUPS;
541         }
542         else {
543                 cprintf("501 syntax error , unsupported list format\r\n");
544                 return;
545         }
546
547         cprintf("215 list of newsgroups follows\r\n");
548         CtdlGetUser(&CC->user, CC->curr_user);
549         CtdlForEachRoom(nntp_list_backend, &nld);
550         cprintf(".\r\n");
551 }
552
553
554 //
555 // Implement HELP command.
556 //
557 void nntp_help(void) {
558         cprintf("100 This is the Citadel NNTP service.\r\n");
559         cprintf("RTFM http://www.ietf.org/rfc/rfc3977.txt\r\n");
560         cprintf(".\r\n");
561 }
562
563
564 //
565 // back end for the LISTGROUP command , called for each message number
566 //
567 void nntp_listgroup_backend(long msgnum, void *userdata) {
568
569         struct listgroup_range *lr = (struct listgroup_range *)userdata;
570
571         // check range if supplied
572         if (msgnum < lr->lo) return;
573         if ((lr->hi != 0) && (msgnum > lr->hi)) return;
574
575         cprintf("%ld\r\n", msgnum);
576 }
577
578
579 //
580 // Implements the GROUP and LISTGROUP commands
581 //
582 void nntp_group(const char *cmd) {
583         //
584         // HACK: this works because the 5XX series error codes from citadel
585         // protocol will also be considered error codes by an NNTP client
586         //
587         if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
588
589         citnntp *nntpstate = (citnntp *) CC->session_specific_data;
590         char verb[16];
591         char requested_group[1024];
592         char message_range[256];
593         char range_lo[256];
594         char range_hi[256];
595         char requested_room[ROOMNAMELEN];
596         char augmented_roomname[ROOMNAMELEN];
597         int c = 0;
598         int ok = 0;
599         int ra = 0;
600         struct ctdlroom QRscratch;
601         int msgs, new;
602         long oldest,newest;
603         struct listgroup_range lr;
604
605         extract_token(verb, cmd, 0, ' ', sizeof verb);
606         extract_token(requested_group, cmd, 1, ' ', sizeof requested_group);
607         extract_token(message_range, cmd, 2, ' ', sizeof message_range);
608         extract_token(range_lo, message_range, 0, '-', sizeof range_lo);
609         extract_token(range_hi, message_range, 1, '-', sizeof range_hi);
610         lr.lo = atoi(range_lo);
611         lr.hi = atoi(range_hi);
612
613         /* In LISTGROUP mode we can specify an empty name for 'currently selected' */
614         if ((!strcasecmp(verb, "LISTGROUP")) && (IsEmptyStr(requested_group))) {
615                 room_to_newsgroup(requested_group, CC->room.QRname, sizeof requested_group);
616         }
617
618         /* First try a regular match */
619         newsgroup_to_room(requested_room, requested_group, sizeof requested_room);
620         c = CtdlGetRoom(&QRscratch, requested_room);
621
622         /* Then try a mailbox name match */
623         if (c != 0) {
624                 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname, &CC->user, requested_room);
625                 c = CtdlGetRoom(&QRscratch, augmented_roomname);
626                 if (c == 0) {
627                         safestrncpy(requested_room, augmented_roomname, sizeof(requested_room));
628                 }
629         }
630
631         /* If the room exists, check security/access */
632         if (c == 0) {
633                 /* See if there is an existing user/room relationship */
634                 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
635
636                 /* normal clients have to pass through security */
637                 if (ra & UA_KNOWN) {
638                         ok = 1;
639                 }
640         }
641
642         /* Fail here if no such room */
643         if (!ok) {
644                 cprintf("411 no such newsgroup\r\n");
645                 return;
646         }
647
648
649         /*
650          * CtdlUserGoto() formally takes us to the desired room, happily returning
651          * the number of messages and number of new messages.
652          */
653         memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
654         CtdlUserGoto(NULL, 0, 0, &msgs, &new, &oldest, &newest);
655         cprintf("211 %d %ld %ld %s\r\n", msgs, oldest, newest, requested_group);
656
657         // If this is a GROUP command, set the "current article number" to zero, and then stop here.
658         if (!strcasecmp(verb, "GROUP")) {
659                 nntpstate->current_article_number = 0;
660                 return;
661         }
662
663         // If we get to this point we are running a LISTGROUP command.  Fetch those message numbers.
664         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, nntp_listgroup_backend, &lr);
665         cprintf(".\r\n");
666 }
667
668
669 //
670 // Implements the MODE command
671 //
672 void nntp_mode(const char *cmd) {
673
674         char which_mode[16];
675
676         extract_token(which_mode, cmd, 1, ' ', sizeof which_mode);
677
678         if (!strcasecmp(which_mode, "reader")) {
679                 cprintf("201 Reader mode FIXME implement posting and change to 200\r\n");
680         }
681         else {
682                 cprintf("501 unknown mode\r\n");
683         }
684 }
685
686
687
688 //
689 // Implements the ARTICLE, HEAD, BODY, and STAT commands.
690 // (These commands all accept the same parameters; they differ only in how they output the retrieved message.)
691 //
692 void nntp_article(const char *cmd) {
693
694         // We're going to store one of these values in the variable 'acmd' so that
695         enum {
696                 ARTICLE,
697                 HEAD,
698                 BODY,
699                 STAT
700         };
701
702         char which_command[16];
703         int acmd = 0;
704         extract_token(which_command, cmd, 0, ' ', sizeof which_command);
705
706         if (!strcasecmp(which_command, "article")) {
707                 acmd = ARTICLE;
708         }
709         else if (!strcasecmp(which_command, "head")) {
710                 acmd = HEAD;
711         }
712         else if (!strcasecmp(which_command, "body")) {
713                 acmd = BODY;
714         }
715         else if (!strcasecmp(which_command, "stat")) {
716                 acmd = STAT;
717         }
718         else {
719                 cprintf("500 I'm afraid I can't do that.\r\n");
720                 return;
721         }
722
723         // Which NNTP command was issued, determines whether we will fetch headers, body, or both.
724         int                     headers_only = HEADERS_ALL;
725         if (acmd == HEAD)       headers_only = HEADERS_FAST;
726         else if (acmd == BODY)  headers_only = HEADERS_NONE;
727         else if (acmd == STAT)  headers_only = HEADERS_FAST;
728
729         // now figure out what the client is asking for.
730         char requested_article[256];
731         long requested_msgnum = 0;
732         char *lb, *rb = NULL;
733         extract_token(requested_article, cmd, 1, ' ', sizeof requested_article);
734         lb = strchr(requested_article, '<');
735         rb = strchr(requested_article, '>');
736         requested_msgnum = atol(requested_article);
737
738         // If no article number or message-id is specified, the client wants the "next" article.
739         // We don't know how to do that yet.
740         if (IsEmptyStr(requested_article)) {
741                 cprintf("500 FIXME I don't know how to fetch next yet.\r\n");
742                 return;
743         }
744
745         // If the requested article is numeric, it maps directly to a message number.  Good.
746         else if (requested_msgnum > 0) {
747                 // good -- fall through and keep going
748         }
749
750         // If the requested article has angle brackets, the client wants a specific message-id.
751         // We don't know how to do that yet.
752         else if ( (lb != NULL) && (rb != NULL) && (lb < rb) ) {
753                 cprintf("500 FIXME I don't know how to fetch by message-id yet.\r\n");
754                 return;
755         }
756
757         // Anything else is noncompliant gobbledygook and should die in a car fire.
758         // Also, the weasel who is spreading untrue rumors about me at work should die in a slow and painful car fire.
759         else {
760                 cprintf("500 syntax error\r\n");
761                 return;
762         }
763
764         // At this point we know the message number of the "article" being requested.
765         // We have an awesome API call that does all the heavy lifting for us.
766         char *fetched_message_id = NULL;
767         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
768         int fetch = CtdlOutputMsg(requested_msgnum,
769                         MT_RFC822,              // output in RFC822 format ... sort of
770                         headers_only,           // headers, body, or both?
771                         0,                      // don't do Citadel protocol responses
772                         1,                      // CRLF newlines
773                         NULL,                   // teh whole thing, not just a section
774                         0,                      // no flags yet ... maybe new ones for Path: etc ?
775                         NULL,
776                         NULL,
777                         &fetched_message_id     // extract the message ID from the message as we go...
778         );
779         StrBuf *msgtext = CC->redirect_buffer;
780         CC->redirect_buffer = NULL;
781
782         if (fetch != om_ok) {
783                 cprintf("423 no article with that number\r\n");
784                 FreeStrBuf(&msgtext);
785                 return;
786         }
787
788         if (acmd == ARTICLE) {
789                 cprintf("220 %ld <%s>\r\n", requested_msgnum, fetched_message_id);
790         }
791         if (acmd == HEAD) {
792                 cprintf("221 %ld <%s>\r\n", requested_msgnum, fetched_message_id);
793         }
794         if (acmd == BODY) {
795                 cprintf("222 %ld <%s>\r\n", requested_msgnum, fetched_message_id);
796         }
797         if (acmd == STAT) {
798                 cprintf("223 %ld <%s>\r\n", requested_msgnum, fetched_message_id);
799                 FreeStrBuf(&msgtext);
800                 return;
801         }
802
803         client_write(SKEY(msgtext));
804         cprintf(".\r\n");                       // this protocol uses a dot terminator
805         FreeStrBuf(&msgtext);
806         if (fetched_message_id) free(fetched_message_id);
807 }
808
809
810 // 
811 // Main command loop for NNTP server sessions.
812 //
813 void nntp_command_loop(void)
814 {
815         StrBuf *Cmd = NewStrBuf();
816         char cmdname[16];
817
818         time(&CC->lastcmd);
819         if (CtdlClientGetLine(Cmd) < 1) {
820                 syslog(LOG_CRIT, "NNTP: client disconnected: ending session.\n");
821                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
822                 FreeStrBuf(&Cmd);
823                 return;
824         }
825         syslog(LOG_DEBUG, "NNTP: %s\n", ((!strncasecmp(ChrPtr(Cmd), "AUTHINFO", 8)) ? "AUTHINFO ..." : ChrPtr(Cmd)));
826         extract_token(cmdname, ChrPtr(Cmd), 0, ' ', sizeof cmdname);
827
828         // Rumpelstiltskin lookups are *awesome*
829
830         if (!strcasecmp(cmdname, "quit")) {
831                 nntp_quit();
832         }
833
834         else if (!strcasecmp(cmdname, "help")) {
835                 nntp_help();
836         }
837
838         else if (!strcasecmp(cmdname, "capabilities")) {
839                 nntp_capabilities();
840         }
841
842         else if (!strcasecmp(cmdname, "starttls")) {
843                 nntp_starttls();
844         }
845
846         else if (!strcasecmp(cmdname, "authinfo")) {
847                 nntp_authinfo(ChrPtr(Cmd));
848         }
849
850         else if (!strcasecmp(cmdname, "newgroups")) {
851                 nntp_newgroups(ChrPtr(Cmd));
852         }
853
854         else if (!strcasecmp(cmdname, "list")) {
855                 nntp_list(ChrPtr(Cmd));
856         }
857
858         else if (!strcasecmp(cmdname, "group")) {
859                 nntp_group(ChrPtr(Cmd));
860         }
861
862         else if (!strcasecmp(cmdname, "listgroup")) {
863                 nntp_group(ChrPtr(Cmd));
864         }
865
866         else if (!strcasecmp(cmdname, "mode")) {
867                 nntp_mode(ChrPtr(Cmd));
868         }
869
870         else if (
871                         (!strcasecmp(cmdname, "article"))
872                         || (!strcasecmp(cmdname, "head"))
873                         || (!strcasecmp(cmdname, "body"))
874                         || (!strcasecmp(cmdname, "stat"))
875                 ) {
876                 nntp_article(ChrPtr(Cmd));
877         }
878
879         else {
880                 cprintf("500 I'm afraid I can't do that.\r\n");
881         }
882
883         FreeStrBuf(&Cmd);
884 }
885
886
887 //      ****************************************************************************
888 //                            MODULE INITIALIZATION STUFF
889 //      ****************************************************************************
890
891
892 //
893 // This cleanup function blows away the temporary memory used by
894 // the NNTP server.
895 //
896 void nntp_cleanup_function(void)
897 {
898         /* Don't do this stuff if this is not an NNTP session! */
899         if (CC->h_command_function != nntp_command_loop) return;
900
901         syslog(LOG_DEBUG, "Performing NNTP cleanup hook\n");
902         citnntp *nntpstate = (citnntp *) CC->session_specific_data;
903         if (nntpstate != NULL) {
904                 free(nntpstate);
905                 nntpstate = NULL;
906         }
907 }
908
909 const char *CitadelServiceNNTP="NNTP";
910
911 CTDL_MODULE_INIT(nntp)
912 {
913         if (!threading)
914         {
915                 CtdlRegisterServiceHook(119,                    // FIXME config.c_nntp_port,
916                                         NULL,
917                                         nntp_greeting,
918                                         nntp_command_loop,
919                                         NULL, 
920                                         CitadelServiceNNTP);
921
922 #ifdef HAVE_OPENSSL
923                 CtdlRegisterServiceHook(563,                    // FIXME config.c_nntps_port,
924                                         NULL,
925                                         nntps_greeting,
926                                         nntp_command_loop,
927                                         NULL,
928                                         CitadelServiceNNTP);
929 #endif
930
931                 CtdlRegisterCleanupHook(nntp_cleanup);
932                 CtdlRegisterSessionHook(nntp_cleanup_function, EVT_STOP, PRIO_STOP + 250);
933         }
934         
935         /* return our module name for the log */
936         return "nntp";
937 }