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