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