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