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