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