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