Protect precious strlens, as pointed out by John Goerzen
[citadel.git] / citadel / modules / network / serv_netspool.c
1 /*
2  * This module handles shared rooms, inter-Citadel mail, and outbound
3  * mailing list processing.
4  *
5  * Copyright (c) 2000-2015 by the citadel.org team
6  *
7  * This program is open source software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License, version 3.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * ** NOTE **   A word on the S_NETCONFIGS semaphore:
16  * This is a fairly high-level type of critical section.  It ensures that no
17  * two threads work on the netconfigs files at the same time.  Since we do
18  * so many things inside these, here are the rules:
19  *  1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
20  *  2. Do *not* perform any I/O with the client during these sections.
21  *
22  */
23
24 /*
25  * Duration of time (in seconds) after which pending list subscribe/unsubscribe
26  * requests that have not been confirmed will be deleted.
27  */
28 #define EXP     259200  /* three days */
29
30 #include "sysdep.h"
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include <stdio.h>
34 #include <fcntl.h>
35 #include <ctype.h>
36 #include <signal.h>
37 #include <pwd.h>
38 #include <errno.h>
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 #include <dirent.h>
42 #if TIME_WITH_SYS_TIME
43 # include <sys/time.h>
44 # include <time.h>
45 #else
46 # if HAVE_SYS_TIME_H
47 #  include <sys/time.h>
48 # else
49 #  include <time.h>
50 # endif
51 #endif
52 #ifdef HAVE_SYSCALL_H
53 # include <syscall.h>
54 #else 
55 # if HAVE_SYS_SYSCALL_H
56 #  include <sys/syscall.h>
57 # endif
58 #endif
59
60 #include <sys/wait.h>
61 #include <string.h>
62 #include <limits.h>
63 #include <libcitadel.h>
64 #include "citadel.h"
65 #include "server.h"
66 #include "citserver.h"
67 #include "support.h"
68 #include "config.h"
69 #include "user_ops.h"
70 #include "database.h"
71 #include "msgbase.h"
72 #include "internet_addressing.h"
73 #include "serv_network.h"
74 #include "clientsocket.h"
75 #include "citadel_dirs.h"
76 #include "threads.h"
77 #include "context.h"
78
79 #include "ctdl_module.h"
80
81 #include "netspool.h"
82 #include "netmail.h"
83
84
85 #ifndef DT_UNKNOWN
86 #define DT_UNKNOWN     0
87 #define DT_DIR         4
88 #define DT_REG         8
89 #define DT_LNK         10
90
91 #define IFTODT(mode)   (((mode) & 0170000) >> 12)
92 #define DTTOIF(dirtype)        ((dirtype) << 12)
93 #endif
94
95
96 /*
97  * Bounce a message back to the sender
98  */
99 void network_bounce(struct CtdlMessage **pMsg, char *reason)
100 {
101         struct CitContext *CCC = CC;
102         char buf[SIZ];
103         char bouncesource[SIZ];
104         char recipient[SIZ];
105         recptypes *valid = NULL;
106         char force_room[ROOMNAMELEN];
107         static int serialnum = 0;
108         long len;
109         struct CtdlMessage *msg = *pMsg;
110         *pMsg = NULL;
111         QNM_syslog(LOG_DEBUG, "entering network_bounce()\n");
112
113         if (msg == NULL) return;
114
115         snprintf(bouncesource, sizeof bouncesource, "%s@%s", BOUNCESOURCE, CtdlGetConfigStr("c_nodename"));
116
117         /* 
118          * Give it a fresh message ID
119          */
120         len = snprintf(buf, sizeof(buf),
121                        "%ld.%04lx.%04x@%s",
122                        (long)time(NULL),
123                        (long)getpid(),
124                        ++serialnum,
125                        CtdlGetConfigStr("c_fqdn"));
126
127         CM_SetField(msg, emessageId, buf, len);
128
129         /*
130          * FIXME ... right now we're just sending a bounce; we really want to
131          * include the text of the bounced message.
132          */
133         if (!IsEmptyStr(reason)) {
134                 CM_SetField(msg, eMesageText, reason, strlen(reason));
135         }
136         msg->cm_format_type = 0;
137
138         /*
139          * Turn the message around
140          */
141         CM_FlushField(msg, eRecipient);
142         CM_FlushField(msg, eDestination);
143
144         len = snprintf(recipient, sizeof(recipient), "%s@%s",
145                        msg->cm_fields[eAuthor],
146                        msg->cm_fields[eNodeName]);
147
148         CM_SetField(msg, eAuthor, HKEY(BOUNCESOURCE));
149         CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
150         CM_SetField(msg, eMsgSubject, HKEY("Delivery Status Notification (Failure)"));
151
152         Netmap_AddMe(msg, HKEY("unknown_user"));
153
154         /* Now submit the message */
155         valid = validate_recipients(recipient, NULL, 0);
156         if (valid != NULL) if (valid->num_error != 0) {
157                 free_recipients(valid);
158                 valid = NULL;
159         }
160         if ( (valid == NULL) || (!strcasecmp(recipient, bouncesource)) ) {
161                 strcpy(force_room, CtdlGetConfigStr("c_aideroom"));
162         }
163         else {
164                 strcpy(force_room, "");
165         }
166         if ( (valid == NULL) && IsEmptyStr(force_room) ) {
167                 strcpy(force_room, CtdlGetConfigStr("c_aideroom"));
168         }
169         CtdlSubmitMsg(msg, valid, force_room, 0);
170
171         /* Clean up */
172         if (valid != NULL) free_recipients(valid);
173         CM_Free(msg);
174         QNM_syslog(LOG_DEBUG, "leaving network_bounce()\n");
175 }
176
177
178 void ParseLastSent(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCFG)
179 {
180         RoomNetCfgLine *nptr;
181         nptr = (RoomNetCfgLine *)
182                 malloc(sizeof(RoomNetCfgLine));
183         memset(nptr, 0, sizeof(RoomNetCfgLine));
184         OneRNCFG->lastsent = extract_long(LinePos, 0);
185         OneRNCFG->NetConfigs[ThisOne->C] = nptr;
186 }
187
188 void ParseRoomAlias(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *rncfg)
189 {
190         if (rncfg->Sender != NULL)
191                 return;
192
193         ParseGeneric(ThisOne, Line, LinePos, rncfg);
194         rncfg->Sender = NewStrBufDup(rncfg->NetConfigs[roommailalias]->Value[0]);
195 }
196
197 void ParseSubPendingLine(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCFG)
198 {
199         if (time(NULL) - extract_long(LinePos, 3) > EXP) 
200                 return; /* expired subscription... */
201
202         ParseGeneric(ThisOne, Line, LinePos, OneRNCFG);
203 }
204 void ParseUnSubPendingLine(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCFG)
205 {
206         if (time(NULL) - extract_long(LinePos, 2) > EXP)
207                 return; /* expired subscription... */
208
209         ParseGeneric(ThisOne, Line, LinePos, OneRNCFG);
210 }
211
212
213 void SerializeLastSent(const CfgLineType *ThisOne, StrBuf *OutputBuffer, OneRoomNetCfg *RNCfg, RoomNetCfgLine *data)
214 {
215         StrBufAppendBufPlain(OutputBuffer, CKEY(ThisOne->Str), 0);
216         StrBufAppendPrintf(OutputBuffer, "|%ld\n", RNCfg->lastsent);
217 }
218
219 void DeleteLastSent(const CfgLineType *ThisOne, RoomNetCfgLine **data)
220 {
221         free(*data);
222         *data = NULL;
223 }
224
225 static const RoomNetCfg SpoolCfgs [4] = {
226         listrecp,
227         digestrecp,
228         participate,
229         ignet_push_share
230 };
231
232 static const long SpoolCfgsCopyN [4] = {
233         1, 1, 1, 2
234 };
235
236 int HaveSpoolConfig(OneRoomNetCfg* RNCfg)
237 {
238         int i;
239         int interested = 0;
240         for (i=0; i < 4; i++) if (RNCfg->NetConfigs[SpoolCfgs[i]] == NULL) interested = 1;
241         return interested;
242 }
243
244 void Netmap_AddMe(struct CtdlMessage *msg, const char *defl, long defllen)
245 {
246         long node_len;
247         char buf[SIZ];
248
249         /* prepend our node to the path */
250         if (CM_IsEmpty(msg, eMessagePath)) {
251                 CM_SetField(msg, eMessagePath, defl, defllen);
252         }
253         node_len = strlen(CtdlGetConfigStr("c_nodename"));
254         if (node_len >= SIZ) 
255                 node_len = SIZ - 1;
256         memcpy(buf, CtdlGetConfigStr("c_nodename"), node_len);
257         buf[node_len] = '!';
258         buf[node_len + 1] = '\0';
259         CM_PrependToField(msg, eMessagePath, buf, node_len + 1);
260 }
261
262 void InspectQueuedRoom(SpoolControl **pSC,
263                        RoomProcList *room_to_spool,     
264                        HashList *working_ignetcfg,
265                        HashList *the_netmap)
266 {
267         struct CitContext *CCC = CC;
268         SpoolControl *sc;
269         int i = 0;
270
271         sc = (SpoolControl*)malloc(sizeof(SpoolControl));
272         memset(sc, 0, sizeof(SpoolControl));
273         sc->RNCfg = room_to_spool->OneRNCfg;
274         sc->lastsent = room_to_spool->lastsent;
275         sc->working_ignetcfg = working_ignetcfg;
276         sc->the_netmap = the_netmap;
277
278         /*
279          * If the room doesn't exist, don't try to perform its networking tasks.
280          * Normally this should never happen, but once in a while maybe a room gets
281          * queued for networking and then deleted before it can happen.
282          */
283         if (CtdlGetRoom(&sc->room, room_to_spool->name) != 0) {
284                 syslog(LOG_CRIT, "ERROR: cannot load <%s>\n", room_to_spool->name);
285                 free(sc);
286                 return;
287         }
288         if (sc->room.QRhighest <= sc->lastsent)
289         {
290                 QN_syslog(LOG_DEBUG, "nothing to do for <%s>\n", room_to_spool->name);
291                 free(sc);
292                 return;
293         }
294
295         begin_critical_section(S_NETCONFIGS);
296         if (sc->RNCfg == NULL)
297                 sc->RNCfg = CtdlGetNetCfgForRoom(sc->room.QRnumber);
298
299         if (!HaveSpoolConfig(sc->RNCfg))
300         {
301                 end_critical_section(S_NETCONFIGS);
302                 free(sc);
303                 /* nothing to do for this room... */
304                 return;
305         }
306
307         /* Now lets remember whats needed for the actual work... */
308
309         for (i=0; i < 4; i++)
310         {
311                 aggregate_recipients(&sc->Users[SpoolCfgs[i]],
312                                      SpoolCfgs[i],
313                                      sc->RNCfg,
314                                      SpoolCfgsCopyN[i]);
315         }
316         
317         if (StrLength(sc->RNCfg->Sender) > 0)
318                 sc->Users[roommailalias] = NewStrBufDup(sc->RNCfg->Sender);
319         end_critical_section(S_NETCONFIGS);
320
321         sc->next = *pSC;
322         *pSC = sc;
323
324 }
325
326 void CalcListID(SpoolControl *sc)
327 {
328         StrBuf *RoomName;
329         const char *err;
330         int fd;
331         struct CitContext *CCC = CC;
332         char filename[PATH_MAX];
333 #define MAX_LISTIDLENGTH 150
334
335         assoc_file_name(filename, sizeof filename, &sc->room, ctdl_info_dir);
336         fd = open(filename, 0);
337
338         if (fd > 0) {
339                 struct stat stbuf;
340
341                 if ((fstat(fd, &stbuf) == 0) &&
342                     (stbuf.st_size > 0))
343                 {
344                         sc->RoomInfo = NewStrBufPlain(NULL, stbuf.st_size + 1);
345                         StrBufReadBLOB(sc->RoomInfo, &fd, 0, stbuf.st_size, &err);
346                 }
347                 close(fd);
348         }
349
350         sc->ListID = NewStrBufPlain(NULL, 1024);
351         if (StrLength(sc->RoomInfo) > 0)
352         {
353                 const char *Pos = NULL;
354                 StrBufSipLine(sc->ListID, sc->RoomInfo, &Pos);
355
356                 if (StrLength(sc->ListID) > MAX_LISTIDLENGTH)
357                 {
358                         StrBufCutAt(sc->ListID, MAX_LISTIDLENGTH, NULL);
359                         StrBufAppendBufPlain(sc->ListID, HKEY("..."), 0);
360                 }
361                 StrBufAsciify(sc->ListID, ' ');
362         }
363         else
364         {
365                 StrBufAppendBufPlain(sc->ListID, CCC->room.QRname, -1, 0);
366         }
367
368         StrBufAppendBufPlain(sc->ListID, HKEY("<"), 0);
369         RoomName = NewStrBufPlain (sc->room.QRname, -1);
370         StrBufAsciify(RoomName, '_');
371         StrBufReplaceChars(RoomName, ' ', '_');
372
373         if (StrLength(sc->Users[roommailalias]) > 0)
374         {
375                 long Pos;
376                 const char *AtPos;
377
378                 Pos = StrLength(sc->ListID);
379                 StrBufAppendBuf(sc->ListID, sc->Users[roommailalias], 0);
380                 AtPos = strchr(ChrPtr(sc->ListID) + Pos, '@');
381
382                 if (AtPos != NULL)
383                 {
384                         StrBufPeek(sc->ListID, AtPos, 0, '.');
385                 }
386         }
387         else
388         {
389                 StrBufAppendBufPlain(sc->ListID, HKEY("room_"), 0);
390                 StrBufAppendBuf(sc->ListID, RoomName, 0);
391                 StrBufAppendBufPlain(sc->ListID, HKEY("."), 0);
392                 StrBufAppendBufPlain(sc->ListID, CtdlGetConfigStr("c_fqdn"), -1, 0);
393                 /*
394                  * this used to be:
395                  * roomname <Room-Number.list-id.fqdn>
396                  * according to rfc2919.txt it only has to be a uniq identifier
397                  * under the domain of the system; 
398                  * in general MUAs use it to calculate the reply address nowadays.
399                  */
400         }
401         StrBufAppendBufPlain(sc->ListID, HKEY(">"), 0);
402
403         if (StrLength(sc->Users[roommailalias]) == 0)
404         {
405                 sc->Users[roommailalias] = NewStrBuf();
406                 
407                 StrBufAppendBufPlain(sc->Users[roommailalias], HKEY("room_"), 0);
408                 StrBufAppendBuf(sc->Users[roommailalias], RoomName, 0);
409                 StrBufAppendBufPlain(sc->Users[roommailalias], HKEY("@"), 0);
410                 StrBufAppendBufPlain(sc->Users[roommailalias], CtdlGetConfigStr("c_fqdn"), -1, 0);
411
412                 StrBufLowerCase(sc->Users[roommailalias]);
413         }
414
415         FreeStrBuf(&RoomName);
416 }
417
418 static time_t last_digest_delivery = 0;
419
420 /*
421  * Batch up and send all outbound traffic from the current room
422  */
423 void network_spoolout_room(SpoolControl *sc)
424 {
425         struct CitContext *CCC = CC;
426         char buf[SIZ];
427         int i;
428         long lastsent;
429
430         /*
431          * If the room doesn't exist, don't try to perform its networking tasks.
432          * Normally this should never happen, but once in a while maybe a room gets
433          * queued for networking and then deleted before it can happen.
434          */
435         memcpy (&CCC->room, &sc->room, sizeof(ctdlroom));
436
437         syslog(LOG_INFO, "Networking started for <%s>\n", CCC->room.QRname);
438
439         CalcListID(sc);
440
441         /* remember where we started... */
442         lastsent = sc->lastsent;
443
444         /* Fetch the messages we ought to send & prepare them. */
445         CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
446                 network_spool_msg, sc);
447
448         if (StrLength(sc->Users[roommailalias]) > 0)
449         {
450                 long len;
451                 len = StrLength(sc->Users[roommailalias]);
452                 if (len + 1 > sizeof(buf))
453                         len = sizeof(buf) - 1;
454                 memcpy(buf, ChrPtr(sc->Users[roommailalias]), len);
455                 buf[len] = '\0';
456         }
457         else
458         {
459                 snprintf(buf, sizeof buf, "room_%s@%s",
460                          CCC->room.QRname, CtdlGetConfigStr("c_fqdn"));
461         }
462
463         for (i=0; buf[i]; ++i) {
464                 buf[i] = tolower(buf[i]);
465                 if (isspace(buf[i])) buf[i] = '_';
466         }
467
468
469         /* If we wrote a digest, deliver it and then close it */
470         if (sc->Users[digestrecp] != NULL) {
471                 time_t now = time(NULL);
472                 time_t secs_today = now % (24 * 60 * 60);
473                 long delta = 0;
474
475                 if (last_digest_delivery != 0) {
476                         delta = now - last_digest_delivery;
477                         delta = (24 * 60 * 60) - delta;
478                 }
479
480                 if ((secs_today < 300) && 
481                     (delta < 300))
482                 {
483                         if (sc->digestfp == NULL) {
484                                 sc->digestfp = create_digest_file(&sc->room, 0);
485                         }
486                         if (sc->digestfp != NULL) {
487                                 last_digest_delivery = now;
488                                 fprintf(sc->digestfp,
489                                         " -----------------------------------"
490                                         "------------------------------------"
491                                         "-------\n"
492                                         "You are subscribed to the '%s' "
493                                         "list.\n"
494                                         "To post to the list: %s\n",
495                                         CCC->room.QRname, buf
496                                         );
497                                 network_deliver_digest(sc);     /* deliver */
498                                 remove_digest_file(&sc->room);
499                         }
500                 }
501         }
502         if (sc->digestfp != NULL) {
503                 fclose(sc->digestfp);
504                 sc->digestfp = NULL;
505         }
506
507         /* Now rewrite the config file */
508         if (sc->lastsent != lastsent)
509         {
510                 begin_critical_section(S_NETCONFIGS);
511                 sc->RNCfg = CtdlGetNetCfgForRoom(sc->room.QRnumber);
512
513                 sc->RNCfg->lastsent = sc->lastsent;
514                 sc->RNCfg->changed = 1;
515                 end_critical_section(S_NETCONFIGS);
516         }
517 }
518
519
520 /*
521  * Check the use table.  This is a list of messages which have recently
522  * arrived on the system.  It is maintained and queried to prevent the same
523  * message from being entered into the database multiple times if it happens
524  * to arrive multiple times by accident.
525  */
526 int network_usetable(struct CtdlMessage *msg)
527 {
528         StrBuf *msgid;
529         struct CitContext *CCC = CC;
530         time_t now;
531
532         /* Bail out if we can't generate a message ID */
533         if ((msg == NULL) || CM_IsEmpty(msg, emessageId))
534         {
535                 return(0);
536         }
537
538         /* Generate the message ID */
539         msgid = NewStrBufPlain(CM_KEY(msg, emessageId));
540         if (haschar(ChrPtr(msgid), '@') == 0) {
541                 StrBufAppendBufPlain(msgid, HKEY("@"), 0);
542                 if (!CM_IsEmpty(msg, eNodeName)) {
543                         StrBufAppendBufPlain(msgid, CM_KEY(msg, eNodeName), 0);
544                 }
545                 else {
546                         FreeStrBuf(&msgid);
547                         return(0);
548                 }
549         }
550         now = time(NULL);
551         if (CheckIfAlreadySeen("Networker Import",
552                                msgid,
553                                now, 0,
554                                eUpdate,
555                                CCC->cs_pid, 0) != 0)
556         {
557                 FreeStrBuf(&msgid);
558                 return(1);
559         }
560         FreeStrBuf(&msgid);
561
562         return(0);
563 }
564
565
566 /*
567  * Process a buffer containing a single message from a single file
568  * from the inbound queue 
569  */
570 void network_process_buffer(char *buffer, long size, HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
571 {
572         long len;
573         struct CitContext *CCC = CC;
574         StrBuf *Buf = NULL;
575         struct CtdlMessage *msg = NULL;
576         long pos;
577         int field;
578         recptypes *recp = NULL;
579         char target_room[ROOMNAMELEN];
580         struct ser_ret sermsg;
581         char filename[PATH_MAX];
582         FILE *fp;
583         const StrBuf *nexthop = NULL;
584         unsigned char firstbyte;
585         unsigned char lastbyte;
586
587         QN_syslog(LOG_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
588
589         /* Validate just a little bit.  First byte should be FF and * last byte should be 00. */
590         firstbyte = buffer[0];
591         lastbyte = buffer[size-1];
592         if ( (firstbyte != 255) || (lastbyte != 0) ) {
593                 QN_syslog(LOG_ERR, "Corrupt message ignored.  Length=%ld, firstbyte = %d, lastbyte = %d\n",
594                           size, firstbyte, lastbyte);
595                 return;
596         }
597
598         /* Set default target room to trash */
599         strcpy(target_room, TWITROOM);
600
601         /* Load the message into memory */
602         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
603         memset(msg, 0, sizeof(struct CtdlMessage));
604         msg->cm_magic = CTDLMESSAGE_MAGIC;
605         msg->cm_anon_type = buffer[1];
606         msg->cm_format_type = buffer[2];
607
608         for (pos = 3; pos < size; ++pos) {
609                 field = buffer[pos];
610                 len = strlen(buffer + pos + 1);
611                 CM_SetField(msg, field, buffer + pos + 1, len);
612                 pos = pos + len + 1;
613         }
614
615         /* Check for message routing */
616         if (!CM_IsEmpty(msg, eDestination)) {
617                 if (strcasecmp(msg->cm_fields[eDestination], CtdlGetConfigStr("c_nodename"))) {
618
619                         /* route the message */
620                         Buf = NewStrBufPlain(CM_KEY(msg,eDestination));
621                         if (CtdlIsValidNode(&nexthop, 
622                                             NULL, 
623                                             Buf, 
624                                             working_ignetcfg, 
625                                             the_netmap) == 0) 
626                         {
627                                 Netmap_AddMe(msg, HKEY("unknown_user"));
628
629                                 /* serialize the message */
630                                 CtdlSerializeMessage(&sermsg, msg);
631
632                                 /* now send it */
633                                 if (StrLength(nexthop) == 0) {
634                                         nexthop = Buf;
635                                 }
636                                 snprintf(filename,
637                                          sizeof filename,
638                                          "%s/%s@%lx%x",
639                                          ctdl_netout_dir,
640                                          ChrPtr(nexthop),
641                                          time(NULL),
642                                          rand()
643                                 );
644                                 QN_syslog(LOG_DEBUG, "Appending to %s\n", filename);
645                                 fp = fopen(filename, "ab");
646                                 if (fp != NULL) {
647                                         fwrite(sermsg.ser, sermsg.len, 1, fp);
648                                         fclose(fp);
649                                 }
650                                 else {
651                                         QN_syslog(LOG_ERR, "%s: %s\n", filename, strerror(errno));
652                                 }
653                                 free(sermsg.ser);
654                                 CM_Free(msg);
655                                 FreeStrBuf(&Buf);
656                                 return;
657                         }
658                         
659                         else {  /* invalid destination node name */
660                                 FreeStrBuf(&Buf);
661
662                                 network_bounce(&msg,
663 "A message you sent could not be delivered due to an invalid destination node"
664 " name.  Please check the address and try sending the message again.\n");
665                                 return;
666
667                         }
668                 }
669         }
670
671         /*
672          * Check to see if we already have a copy of this message, and
673          * abort its processing if so.  (We used to post a warning to Aide>
674          * every time this happened, but the network is now so densely
675          * connected that it's inevitable.)
676          */
677         if (network_usetable(msg) != 0) {
678                 CM_Free(msg);
679                 return;
680         }
681
682         /* Learn network topology from the path */
683         if (!CM_IsEmpty(msg, eNodeName) && !CM_IsEmpty(msg, eMessagePath)) {
684                 NetworkLearnTopology(msg->cm_fields[eNodeName], 
685                                      msg->cm_fields[eMessagePath], 
686                                      the_netmap, 
687                                      netmap_changed);
688         }
689
690         /* Is the sending node giving us a very persuasive suggestion about
691          * which room this message should be saved in?  If so, go with that.
692          */
693         if (!CM_IsEmpty(msg, eRemoteRoom)) {
694                 safestrncpy(target_room, msg->cm_fields[eRemoteRoom], sizeof target_room);
695         }
696
697         /* Otherwise, does it have a recipient?  If so, validate it... */
698         else if (!CM_IsEmpty(msg, eRecipient)) {
699                 recp = validate_recipients(msg->cm_fields[eRecipient], NULL, 0);
700                 if (recp != NULL) if (recp->num_error != 0) {
701                         network_bounce(&msg,
702                                 "A message you sent could not be delivered due to an invalid address.\n"
703                                 "Please check the address and try sending the message again.\n");
704                         free_recipients(recp);
705                         QNM_syslog(LOG_DEBUG, "Bouncing message due to invalid recipient address.\n");
706                         return;
707                 }
708                 strcpy(target_room, "");        /* no target room if mail */
709         }
710
711         /* Our last shot at finding a home for this message is to see if
712          * it has the eOriginalRoom (O) field (Originating room) set.
713          */
714         else if (!CM_IsEmpty(msg, eOriginalRoom)) {
715                 safestrncpy(target_room, msg->cm_fields[eOriginalRoom], sizeof target_room);
716         }
717
718         /* Strip out fields that are only relevant during transit */
719         CM_FlushField(msg, eDestination);
720         CM_FlushField(msg, eRemoteRoom);
721
722         /* save the message into a room */
723         if (PerformNetprocHooks(msg, target_room) == 0) {
724                 msg->cm_flags = CM_SKIP_HOOKS;
725                 CtdlSubmitMsg(msg, recp, target_room, 0);
726         }
727         CM_Free(msg);
728         free_recipients(recp);
729 }
730
731
732 /*
733  * Process a single message from a single file from the inbound queue 
734  */
735 void network_process_message(FILE *fp, 
736                              long msgstart, 
737                              long msgend,
738                              HashList *working_ignetcfg,
739                              HashList *the_netmap, 
740                              int *netmap_changed)
741 {
742         long hold_pos;
743         long size;
744         char *buffer;
745
746         hold_pos = ftell(fp);
747         size = msgend - msgstart + 1;
748         buffer = malloc(size);
749         if (buffer != NULL) {
750                 fseek(fp, msgstart, SEEK_SET);
751                 if (fread(buffer, size, 1, fp) > 0) {
752                         network_process_buffer(buffer, 
753                                                size, 
754                                                working_ignetcfg, 
755                                                the_netmap, 
756                                                netmap_changed);
757                 }
758                 free(buffer);
759         }
760
761         fseek(fp, hold_pos, SEEK_SET);
762 }
763
764
765 /*
766  * Process a single file from the inbound queue 
767  */
768 void network_process_file(char *filename,
769                           HashList *working_ignetcfg,
770                           HashList *the_netmap, 
771                           int *netmap_changed)
772 {
773         struct CitContext *CCC = CC;
774         FILE *fp;
775         long msgstart = (-1L);
776         long msgend = (-1L);
777         long msgcur = 0L;
778         int ch;
779         int nMessages = 0;
780
781         fp = fopen(filename, "rb");
782         if (fp == NULL) {
783                 QN_syslog(LOG_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
784                 return;
785         }
786
787         fseek(fp, 0L, SEEK_END);
788         QN_syslog(LOG_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
789         rewind(fp);
790
791         /* Look for messages in the data stream and break them out */
792         while (ch = getc(fp), ch >= 0) {
793         
794                 if (ch == 255) {
795                         if (msgstart >= 0L) {
796                                 msgend = msgcur - 1;
797                                 network_process_message(fp,
798                                                         msgstart,
799                                                         msgend,
800                                                         working_ignetcfg,
801                                                         the_netmap,
802                                                         netmap_changed);
803                         }
804                         msgstart = msgcur;
805                 }
806
807                 ++msgcur;
808                 nMessages ++;
809         }
810
811         msgend = msgcur - 1;
812         if (msgstart >= 0L) {
813                 network_process_message(fp,
814                                         msgstart,
815                                         msgend,
816                                         working_ignetcfg,
817                                         the_netmap,
818                                         netmap_changed);
819                 nMessages ++;
820         }
821
822         if (nMessages > 0)
823                 QN_syslog(LOG_INFO,
824                           "network: processed %d messages in %s\n",
825                           nMessages,
826                           filename);
827
828         fclose(fp);
829         unlink(filename);
830 }
831
832
833 /*
834  * Process anything in the inbound queue
835  */
836 void network_do_spoolin(HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
837 {
838         struct CitContext *CCC = CC;
839         DIR *dp;
840         struct dirent *d;
841         struct dirent *filedir_entry;
842         struct stat statbuf;
843         char filename[PATH_MAX];
844         static time_t last_spoolin_mtime = 0L;
845         int d_type = 0;
846         int d_namelen;
847
848         /*
849          * Check the spoolin directory's modification time.  If it hasn't
850          * been touched, we don't need to scan it.
851          */
852         if (stat(ctdl_netin_dir, &statbuf)) return;
853         if (statbuf.st_mtime == last_spoolin_mtime) {
854                 QNM_syslog(LOG_DEBUG, "network: nothing in inbound queue\n");
855                 return;
856         }
857         last_spoolin_mtime = statbuf.st_mtime;
858         QNM_syslog(LOG_DEBUG, "network: processing inbound queue\n");
859
860         /*
861          * Ok, there's something interesting in there, so scan it.
862          */
863         dp = opendir(ctdl_netin_dir);
864         if (dp == NULL) return;
865
866         d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
867         if (d == NULL) {
868                 closedir(dp);
869                 return;
870         }
871
872         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
873                (filedir_entry != NULL))
874         {
875 #ifdef _DIRENT_HAVE_D_NAMLEN
876                 d_namelen = filedir_entry->d_namlen;
877
878 #else
879                 d_namelen = strlen(filedir_entry->d_name);
880 #endif
881
882 #ifdef _DIRENT_HAVE_D_TYPE
883                 d_type = filedir_entry->d_type;
884 #else
885                 d_type = DT_UNKNOWN;
886 #endif
887                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
888                         continue; /* Ignore backup files... */
889
890                 if ((d_namelen == 1) && 
891                     (filedir_entry->d_name[0] == '.'))
892                         continue;
893
894                 if ((d_namelen == 2) && 
895                     (filedir_entry->d_name[0] == '.') &&
896                     (filedir_entry->d_name[1] == '.'))
897                         continue;
898
899                 if (d_type == DT_UNKNOWN) {
900                         struct stat s;
901                         char path[PATH_MAX];
902
903                         snprintf(path,
904                                  PATH_MAX,
905                                  "%s/%s", 
906                                  ctdl_netin_dir,
907                                  filedir_entry->d_name);
908
909                         if (lstat(path, &s) == 0) {
910                                 d_type = IFTODT(s.st_mode);
911                         }
912                 }
913
914                 switch (d_type)
915                 {
916                 case DT_DIR:
917                         break;
918                 case DT_LNK: /* TODO: check whether its a file or a directory */
919                 case DT_REG:
920                         snprintf(filename, 
921                                 sizeof filename,
922                                 "%s/%s",
923                                 ctdl_netin_dir,
924                                 d->d_name
925                         );
926                         network_process_file(filename,
927                                              working_ignetcfg,
928                                              the_netmap,
929                                              netmap_changed);
930                 }
931         }
932
933         closedir(dp);
934         free(d);
935 }
936
937 /*
938  * Step 1: consolidate files in the outbound queue into one file per neighbor node
939  * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
940  */
941 void network_consolidate_spoolout(HashList *working_ignetcfg, HashList *the_netmap)
942 {
943         struct CitContext *CCC = CC;
944         IOBuffer IOB;
945         FDIOBuffer FDIO;
946         int d_namelen;
947         DIR *dp;
948         struct dirent *d;
949         struct dirent *filedir_entry;
950         const char *pch;
951         char spooloutfilename[PATH_MAX];
952         char filename[PATH_MAX];
953         const StrBuf *nexthop;
954         StrBuf *NextHop;
955         int i;
956         struct stat statbuf;
957         int nFailed = 0;
958         int d_type = 0;
959
960
961         /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
962         d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
963         if (d == NULL)  return;
964
965         dp = opendir(ctdl_netout_dir);
966         if (dp == NULL) {
967                 free(d);
968                 return;
969         }
970
971         NextHop = NewStrBuf();
972         memset(&IOB, 0, sizeof(IOBuffer));
973         memset(&FDIO, 0, sizeof(FDIOBuffer));
974         FDIO.IOB = &IOB;
975
976         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
977                (filedir_entry != NULL))
978         {
979 #ifdef _DIRENT_HAVE_D_NAMLEN
980                 d_namelen = filedir_entry->d_namlen;
981
982 #else
983                 d_namelen = strlen(filedir_entry->d_name);
984 #endif
985
986 #ifdef _DIRENT_HAVE_D_TYPE
987                 d_type = filedir_entry->d_type;
988 #else
989                 d_type = DT_UNKNOWN;
990 #endif
991                 if (d_type == DT_DIR)
992                         continue;
993
994                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
995                         continue; /* Ignore backup files... */
996
997                 if ((d_namelen == 1) && 
998                     (filedir_entry->d_name[0] == '.'))
999                         continue;
1000
1001                 if ((d_namelen == 2) && 
1002                     (filedir_entry->d_name[0] == '.') &&
1003                     (filedir_entry->d_name[1] == '.'))
1004                         continue;
1005
1006                 pch = strchr(filedir_entry->d_name, '@');
1007                 if (pch == NULL)
1008                         continue;
1009
1010                 snprintf(filename, 
1011                          sizeof filename,
1012                          "%s/%s",
1013                          ctdl_netout_dir,
1014                          filedir_entry->d_name);
1015
1016                 StrBufPlain(NextHop,
1017                             filedir_entry->d_name,
1018                             pch - filedir_entry->d_name);
1019
1020                 snprintf(spooloutfilename,
1021                          sizeof spooloutfilename,
1022                          "%s/%s",
1023                          ctdl_netout_dir,
1024                          ChrPtr(NextHop));
1025
1026                 QN_syslog(LOG_DEBUG, "Consolidate %s to %s\n", filename, ChrPtr(NextHop));
1027                 if (CtdlNetworkTalkingTo(SKEY(NextHop), NTT_CHECK)) {
1028                         nFailed++;
1029                         QN_syslog(LOG_DEBUG,
1030                                   "Currently online with %s - skipping for now\n",
1031                                   ChrPtr(NextHop)
1032                                 );
1033                 }
1034                 else {
1035                         size_t dsize;
1036                         size_t fsize;
1037                         int infd, outfd;
1038                         const char *err = NULL;
1039                         CtdlNetworkTalkingTo(SKEY(NextHop), NTT_ADD);
1040
1041                         infd = open(filename, O_RDONLY);
1042                         if (infd == -1) {
1043                                 nFailed++;
1044                                 QN_syslog(LOG_ERR,
1045                                           "failed to open %s for reading due to %s; skipping.\n",
1046                                           filename, strerror(errno)
1047                                         );
1048                                 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
1049                                 continue;                               
1050                         }
1051                         
1052                         outfd = open(spooloutfilename,
1053                                   O_EXCL|O_CREAT|O_NONBLOCK|O_WRONLY, 
1054                                   S_IRUSR|S_IWUSR);
1055                         if (outfd == -1)
1056                         {
1057                                 outfd = open(spooloutfilename,
1058                                              O_EXCL|O_NONBLOCK|O_WRONLY, 
1059                                              S_IRUSR | S_IWUSR);
1060                         }
1061                         if (outfd == -1) {
1062                                 nFailed++;
1063                                 QN_syslog(LOG_ERR,
1064                                           "failed to open %s for reading due to %s; skipping.\n",
1065                                           spooloutfilename, strerror(errno)
1066                                         );
1067                                 close(infd);
1068                                 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
1069                                 continue;
1070                         }
1071
1072                         dsize = lseek(outfd, 0, SEEK_END);
1073                         lseek(outfd, -dsize, SEEK_SET);
1074
1075                         fstat(infd, &statbuf);
1076                         fsize = statbuf.st_size;
1077 /*
1078                         fsize = lseek(infd, 0, SEEK_END);
1079 */                      
1080                         IOB.fd = infd;
1081                         FDIOBufferInit(&FDIO, &IOB, outfd, fsize + dsize);
1082                         FDIO.ChunkSendRemain = fsize;
1083                         FDIO.TotalSentAlready = dsize;
1084                         err = NULL;
1085                         errno = 0;
1086                         do {} while ((FileMoveChunked(&FDIO, &err) > 0) && (err == NULL));
1087                         if (err == NULL) {
1088                                 unlink(filename);
1089                                 QN_syslog(LOG_DEBUG,
1090                                           "Spoolfile %s now "SIZE_T_FMT" k\n",
1091                                           spooloutfilename,
1092                                           (dsize + fsize)/1024
1093                                         );                              
1094                         }
1095                         else {
1096                                 nFailed++;
1097                                 QN_syslog(LOG_ERR,
1098                                           "failed to append to %s [%s]; rolling back..\n",
1099                                           spooloutfilename, strerror(errno)
1100                                         );
1101                                 /* whoops partial append?? truncate spooloutfilename again! */
1102                                 ftruncate(outfd, dsize);
1103                         }
1104                         FDIOBufferDelete(&FDIO);
1105                         close(infd);
1106                         close(outfd);
1107                         CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
1108                 }
1109         }
1110         closedir(dp);
1111
1112         if (nFailed > 0) {
1113                 FreeStrBuf(&NextHop);
1114                 QN_syslog(LOG_INFO,
1115                           "skipping Spoolcleanup because of %d files unprocessed.\n",
1116                           nFailed
1117                         );
1118
1119                 return;
1120         }
1121
1122         /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1123         dp = opendir(ctdl_netout_dir);
1124         if (dp == NULL) {
1125                 FreeStrBuf(&NextHop);
1126                 free(d);
1127                 return;
1128         }
1129
1130         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
1131                (filedir_entry != NULL))
1132         {
1133 #ifdef _DIRENT_HAVE_D_NAMLEN
1134                 d_namelen = filedir_entry->d_namlen;
1135
1136 #else
1137                 d_namelen = strlen(filedir_entry->d_name);
1138 #endif
1139
1140 #ifdef _DIRENT_HAVE_D_TYPE
1141                 d_type = filedir_entry->d_type;
1142 #else
1143                 d_type = DT_UNKNOWN;
1144 #endif
1145                 if (d_type == DT_DIR)
1146                         continue;
1147
1148                 if ((d_namelen == 1) && 
1149                     (filedir_entry->d_name[0] == '.'))
1150                         continue;
1151
1152                 if ((d_namelen == 2) && 
1153                     (filedir_entry->d_name[0] == '.') &&
1154                     (filedir_entry->d_name[1] == '.'))
1155                         continue;
1156
1157                 pch = strchr(filedir_entry->d_name, '@');
1158                 if (pch == NULL) /* no @ in name? consolidated file. */
1159                         continue;
1160
1161                 StrBufPlain(NextHop,
1162                             filedir_entry->d_name,
1163                             pch - filedir_entry->d_name);
1164
1165                 snprintf(filename, 
1166                         sizeof filename,
1167                         "%s/%s",
1168                         ctdl_netout_dir,
1169                         filedir_entry->d_name
1170                 );
1171
1172                 i = CtdlIsValidNode(&nexthop,
1173                                     NULL,
1174                                     NextHop,
1175                                     working_ignetcfg,
1176                                     the_netmap);
1177         
1178                 if ( (i != 0) || (StrLength(nexthop) > 0) ) {
1179                         unlink(filename);
1180                 }
1181         }
1182         FreeStrBuf(&NextHop);
1183         free(d);
1184         closedir(dp);
1185 }
1186
1187 void free_spoolcontrol_struct(SpoolControl **sc)
1188 {
1189         free_spoolcontrol_struct_members(*sc);
1190         free(*sc);
1191         *sc = NULL;
1192 }
1193
1194 void free_spoolcontrol_struct_members(SpoolControl *sc)
1195 {
1196         int i;
1197         FreeStrBuf(&sc->RoomInfo);
1198         FreeStrBuf(&sc->ListID);
1199         for (i = 0; i < maxRoomNetCfg; i++)
1200                 FreeStrBuf(&sc->Users[i]);
1201 }
1202
1203
1204
1205 /*
1206  * It's ok if these directories already exist.  Just fail silently.
1207  */
1208 void create_spool_dirs(void) {
1209         if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
1210                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
1211         if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
1212                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
1213         if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
1214                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
1215         if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
1216                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
1217         if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
1218                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
1219         if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
1220                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
1221         if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
1222                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
1223         if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
1224                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
1225 }
1226
1227 /*
1228  * Module entry point
1229  */
1230 CTDL_MODULE_INIT(network_spool)
1231 {
1232         if (!threading)
1233         {
1234                 CtdlREGISTERRoomCfgType(subpending,       ParseSubPendingLine,   0, 5, SerializeGeneric,  DeleteGenericCfgLine); /// todo: move this to mailinglist manager
1235                 CtdlREGISTERRoomCfgType(unsubpending,     ParseUnSubPendingLine, 0, 4, SerializeGeneric,  DeleteGenericCfgLine); /// todo: move this to mailinglist manager
1236                 CtdlREGISTERRoomCfgType(lastsent,         ParseLastSent,         1, 1, SerializeLastSent, DeleteLastSent);
1237                 CtdlREGISTERRoomCfgType(ignet_push_share, ParseGeneric,          0, 2, SerializeGeneric,  DeleteGenericCfgLine); // [remotenode|remoteroomname (optional)]// todo: move this to the ignet client
1238                 CtdlREGISTERRoomCfgType(listrecp,         ParseGeneric,          0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1239                 CtdlREGISTERRoomCfgType(digestrecp,       ParseGeneric,          0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1240                 CtdlREGISTERRoomCfgType(participate,      ParseGeneric,          0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1241                 CtdlREGISTERRoomCfgType(roommailalias,    ParseRoomAlias,        0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1242
1243                 create_spool_dirs();
1244 //////todo              CtdlRegisterCleanupHook(destroy_network_queue_room);
1245         }
1246         return "network_spool";
1247 }