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