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