Networker: more verbose INFO-logging about what we do / did with files.
[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         int nMessages = 0;
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                 nMessages ++;
661         }
662
663         msgend = msgcur - 1;
664         if (msgstart >= 0L) {
665                 network_process_message(fp,
666                                         msgstart,
667                                         msgend,
668                                         working_ignetcfg,
669                                         the_netmap,
670                                         netmap_changed);
671                 nMessages ++;
672         }
673
674         if (nMessages > 0)
675                 QN_syslog(LOG_INFO,
676                           "network: processed %d messages in %s\n",
677                           nMessages,
678                           filename);
679
680         fclose(fp);
681         unlink(filename);
682 }
683
684
685 /*
686  * Process anything in the inbound queue
687  */
688 void network_do_spoolin(HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
689 {
690         struct CitContext *CCC = CC;
691         DIR *dp;
692         struct dirent *d;
693         struct dirent *filedir_entry;
694         struct stat statbuf;
695         char filename[PATH_MAX];
696         static time_t last_spoolin_mtime = 0L;
697         int d_type = 0;
698         int d_namelen;
699
700         /*
701          * Check the spoolin directory's modification time.  If it hasn't
702          * been touched, we don't need to scan it.
703          */
704         if (stat(ctdl_netin_dir, &statbuf)) return;
705         if (statbuf.st_mtime == last_spoolin_mtime) {
706                 QNM_syslog(LOG_DEBUG, "network: nothing in inbound queue\n");
707                 return;
708         }
709         last_spoolin_mtime = statbuf.st_mtime;
710         QNM_syslog(LOG_DEBUG, "network: processing inbound queue\n");
711
712         /*
713          * Ok, there's something interesting in there, so scan it.
714          */
715         dp = opendir(ctdl_netin_dir);
716         if (dp == NULL) return;
717
718         d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
719         if (d == NULL) {
720                 closedir(dp);
721                 return;
722         }
723
724         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
725                (filedir_entry != NULL))
726         {
727 #ifdef _DIRENT_HAVE_D_NAMLEN
728                 d_namelen = filedir_entry->d_namelen;
729
730 #else
731                 d_namelen = strlen(filedir_entry->d_name);
732 #endif
733
734 #ifdef _DIRENT_HAVE_D_TYPE
735                 d_type = filedir_entry->d_type;
736 #else
737                 d_type = DT_UNKNOWN;
738 #endif
739                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
740                         continue; /* Ignore backup files... */
741
742                 if ((d_namelen == 1) && 
743                     (filedir_entry->d_name[0] == '.'))
744                         continue;
745
746                 if ((d_namelen == 2) && 
747                     (filedir_entry->d_name[0] == '.') &&
748                     (filedir_entry->d_name[1] == '.'))
749                         continue;
750
751                 if (d_type == DT_UNKNOWN) {
752                         struct stat s;
753                         char path[PATH_MAX];
754
755                         snprintf(path,
756                                  PATH_MAX,
757                                  "%s/%s", 
758                                  ctdl_netin_dir,
759                                  filedir_entry->d_name);
760
761                         if (lstat(path, &s) == 0) {
762                                 d_type = IFTODT(s.st_mode);
763                         }
764                 }
765
766                 switch (d_type)
767                 {
768                 case DT_DIR:
769                         break;
770                 case DT_LNK: /* TODO: check whether its a file or a directory */
771                 case DT_REG:
772                         snprintf(filename, 
773                                 sizeof filename,
774                                 "%s/%s",
775                                 ctdl_netin_dir,
776                                 d->d_name
777                         );
778                         network_process_file(filename,
779                                              working_ignetcfg,
780                                              the_netmap,
781                                              netmap_changed);
782                 }
783         }
784
785         closedir(dp);
786         free(d);
787 }
788
789 /*
790  * Step 1: consolidate files in the outbound queue into one file per neighbor node
791  * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
792  */
793 void network_consolidate_spoolout(HashList *working_ignetcfg, HashList *the_netmap)
794 {
795         struct CitContext *CCC = CC;
796         IOBuffer IOB;
797         FDIOBuffer FDIO;
798         int d_namelen;
799         DIR *dp;
800         struct dirent *d;
801         struct dirent *filedir_entry;
802         const char *pch;
803         char spooloutfilename[PATH_MAX];
804         char filename[PATH_MAX];
805         const StrBuf *nexthop;
806         StrBuf *NextHop;
807         int i;
808         struct stat statbuf;
809         int nFailed = 0;
810         int d_type = 0;
811
812
813         /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
814         d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
815         if (d == NULL)  return;
816
817         dp = opendir(ctdl_netout_dir);
818         if (dp == NULL) {
819                 free(d);
820                 return;
821         }
822
823         NextHop = NewStrBuf();
824         memset(&IOB, 0, sizeof(IOBuffer));
825         memset(&FDIO, 0, sizeof(FDIOBuffer));
826         FDIO.IOB = &IOB;
827
828         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
829                (filedir_entry != NULL))
830         {
831 #ifdef _DIRENT_HAVE_D_NAMLEN
832                 d_namelen = filedir_entry->d_namelen;
833
834 #else
835                 d_namelen = strlen(filedir_entry->d_name);
836 #endif
837
838 #ifdef _DIRENT_HAVE_D_TYPE
839                 d_type = filedir_entry->d_type;
840 #else
841                 d_type = DT_UNKNOWN;
842 #endif
843                 if (d_type == DT_DIR)
844                         continue;
845
846                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
847                         continue; /* Ignore backup files... */
848
849                 if ((d_namelen == 1) && 
850                     (filedir_entry->d_name[0] == '.'))
851                         continue;
852
853                 if ((d_namelen == 2) && 
854                     (filedir_entry->d_name[0] == '.') &&
855                     (filedir_entry->d_name[1] == '.'))
856                         continue;
857
858                 pch = strchr(filedir_entry->d_name, '@');
859                 if (pch == NULL)
860                         continue;
861
862                 snprintf(filename, 
863                          sizeof filename,
864                          "%s/%s",
865                          ctdl_netout_dir,
866                          filedir_entry->d_name);
867
868                 StrBufPlain(NextHop,
869                             filedir_entry->d_name,
870                             pch - filedir_entry->d_name);
871
872                 snprintf(spooloutfilename,
873                          sizeof spooloutfilename,
874                          "%s/%s",
875                          ctdl_netout_dir,
876                          ChrPtr(NextHop));
877
878                 QN_syslog(LOG_DEBUG, "Consolidate %s to %s\n", filename, ChrPtr(NextHop));
879                 if (CtdlNetworkTalkingTo(SKEY(NextHop), NTT_CHECK)) {
880                         nFailed++;
881                         QN_syslog(LOG_DEBUG,
882                                   "Currently online with %s - skipping for now\n",
883                                   ChrPtr(NextHop)
884                                 );
885                 }
886                 else {
887                         size_t dsize;
888                         size_t fsize;
889                         int infd, outfd;
890                         const char *err = NULL;
891                         CtdlNetworkTalkingTo(SKEY(NextHop), NTT_ADD);
892
893                         infd = open(filename, O_RDONLY);
894                         if (infd == -1) {
895                                 nFailed++;
896                                 QN_syslog(LOG_ERR,
897                                           "failed to open %s for reading due to %s; skipping.\n",
898                                           filename, strerror(errno)
899                                         );
900                                 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
901                                 continue;                               
902                         }
903                         
904                         outfd = open(spooloutfilename,
905                                   O_EXCL|O_CREAT|O_NONBLOCK|O_WRONLY, 
906                                   S_IRUSR|S_IWUSR);
907                         if (outfd == -1)
908                         {
909                                 outfd = open(spooloutfilename,
910                                              O_EXCL|O_NONBLOCK|O_WRONLY, 
911                                              S_IRUSR | S_IWUSR);
912                         }
913                         if (outfd == -1) {
914                                 nFailed++;
915                                 QN_syslog(LOG_ERR,
916                                           "failed to open %s for reading due to %s; skipping.\n",
917                                           spooloutfilename, strerror(errno)
918                                         );
919                                 close(infd);
920                                 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
921                                 continue;
922                         }
923
924                         dsize = lseek(outfd, 0, SEEK_END);
925                         lseek(outfd, -dsize, SEEK_SET);
926
927                         fstat(infd, &statbuf);
928                         fsize = statbuf.st_size;
929 /*
930                         fsize = lseek(infd, 0, SEEK_END);
931 */                      
932                         IOB.fd = infd;
933                         FDIOBufferInit(&FDIO, &IOB, outfd, fsize + dsize);
934                         FDIO.ChunkSendRemain = fsize;
935                         FDIO.TotalSentAlready = dsize;
936                         err = NULL;
937                         errno = 0;
938                         do {} while ((FileMoveChunked(&FDIO, &err) > 0) && (err == NULL));
939                         if (err == NULL) {
940                                 unlink(filename);
941                                 QN_syslog(LOG_DEBUG,
942                                           "Spoolfile %s now "SIZE_T_FMT" k\n",
943                                           spooloutfilename,
944                                           (dsize + fsize)/1024
945                                         );                              
946                         }
947                         else {
948                                 nFailed++;
949                                 QN_syslog(LOG_ERR,
950                                           "failed to append to %s [%s]; rolling back..\n",
951                                           spooloutfilename, strerror(errno)
952                                         );
953                                 /* whoops partial append?? truncate spooloutfilename again! */
954                                 ftruncate(outfd, dsize);
955                         }
956                         FDIOBufferDelete(&FDIO);
957                         close(infd);
958                         close(outfd);
959                         CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
960                 }
961         }
962         closedir(dp);
963
964         if (nFailed > 0) {
965                 FreeStrBuf(&NextHop);
966                 QN_syslog(LOG_INFO,
967                           "skipping Spoolcleanup because of %d files unprocessed.\n",
968                           nFailed
969                         );
970
971                 return;
972         }
973
974         /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
975         dp = opendir(ctdl_netout_dir);
976         if (dp == NULL) {
977                 FreeStrBuf(&NextHop);
978                 free(d);
979                 return;
980         }
981
982         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
983                (filedir_entry != NULL))
984         {
985 #ifdef _DIRENT_HAVE_D_NAMLEN
986                 d_namelen = filedir_entry->d_namelen;
987
988 #else
989                 d_namelen = strlen(filedir_entry->d_name);
990 #endif
991
992 #ifdef _DIRENT_HAVE_D_TYPE
993                 d_type = filedir_entry->d_type;
994 #else
995                 d_type = DT_UNKNOWN;
996 #endif
997                 if (d_type == DT_DIR)
998                         continue;
999
1000                 if ((d_namelen == 1) && 
1001                     (filedir_entry->d_name[0] == '.'))
1002                         continue;
1003
1004                 if ((d_namelen == 2) && 
1005                     (filedir_entry->d_name[0] == '.') &&
1006                     (filedir_entry->d_name[1] == '.'))
1007                         continue;
1008
1009                 pch = strchr(filedir_entry->d_name, '@');
1010                 if (pch == NULL) /* no @ in name? consolidated file. */
1011                         continue;
1012
1013                 StrBufPlain(NextHop,
1014                             filedir_entry->d_name,
1015                             pch - filedir_entry->d_name);
1016
1017                 snprintf(filename, 
1018                         sizeof filename,
1019                         "%s/%s",
1020                         ctdl_netout_dir,
1021                         filedir_entry->d_name
1022                 );
1023
1024                 i = CtdlIsValidNode(&nexthop,
1025                                     NULL,
1026                                     NextHop,
1027                                     working_ignetcfg,
1028                                     the_netmap);
1029         
1030                 if ( (i != 0) || (StrLength(nexthop) > 0) ) {
1031                         unlink(filename);
1032                 }
1033         }
1034         FreeStrBuf(&NextHop);
1035         free(d);
1036         closedir(dp);
1037 }
1038
1039 void free_spoolcontrol_struct(SpoolControl **sc)
1040 {
1041         free_spoolcontrol_struct_members(*sc);
1042         free(*sc);
1043         *sc = NULL;
1044 }
1045
1046 void free_spoolcontrol_struct_members(SpoolControl *sc)
1047 {
1048         int i;
1049         FreeStrBuf(&sc->RoomInfo);
1050         FreeStrBuf(&sc->ListID);
1051         for (i = 0; i < maxRoomNetCfg; i++)
1052                 FreeStrBuf(&sc->Users[i]);
1053 }
1054
1055
1056
1057 /*
1058  * It's ok if these directories already exist.  Just fail silently.
1059  */
1060 void create_spool_dirs(void) {
1061         if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
1062                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
1063         if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
1064                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
1065         if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
1066                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
1067         if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
1068                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
1069         if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
1070                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
1071         if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
1072                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
1073         if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
1074                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
1075         if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
1076                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
1077 }
1078
1079 /*
1080  * Module entry point
1081  */
1082 CTDL_MODULE_INIT(network_spool)
1083 {
1084         if (!threading)
1085         {
1086                 CtdlREGISTERRoomCfgType(subpending,       ParseSubPendingLine,   0, 5, SerializeGeneric,  DeleteGenericCfgLine); /// todo: move this to mailinglist manager
1087                 CtdlREGISTERRoomCfgType(unsubpending,     ParseUnSubPendingLine, 0, 4, SerializeGeneric,  DeleteGenericCfgLine); /// todo: move this to mailinglist manager
1088                 CtdlREGISTERRoomCfgType(lastsent,         ParseLastSent,         1, 1, SerializeLastSent, DeleteLastSent);
1089                 CtdlREGISTERRoomCfgType(ignet_push_share, ParseGeneric,          0, 2, SerializeGeneric,  DeleteGenericCfgLine); // [remotenode|remoteroomname (optional)]// todo: move this to the ignet client
1090                 CtdlREGISTERRoomCfgType(listrecp,         ParseGeneric,          0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1091                 CtdlREGISTERRoomCfgType(digestrecp,       ParseGeneric,          0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1092                 CtdlREGISTERRoomCfgType(participate,      ParseGeneric,          0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1093                 CtdlREGISTERRoomCfgType(roommailalias,    ParseRoomAlias,        0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1094
1095                 create_spool_dirs();
1096 //////todo              CtdlRegisterCleanupHook(destroy_network_queue_room);
1097         }
1098         return "network_spool";
1099 }