NetQueue: make logging runtime configurable; add context.
[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 as published by
9  *  the Free Software Foundation; either version 3 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  * ** NOTE **   A word on the S_NETCONFIGS semaphore:
22  * This is a fairly high-level type of critical section.  It ensures that no
23  * two threads work on the netconfigs files at the same time.  Since we do
24  * so many things inside these, here are the rules:
25  *  1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
26  *  2. Do *not* perform any I/O with the client during these sections.
27  *
28  */
29
30 /*
31  * Duration of time (in seconds) after which pending list subscribe/unsubscribe
32  * requests that have not been confirmed will be deleted.
33  */
34 #define EXP     259200  /* three days */
35
36 #include "sysdep.h"
37 #include <stdlib.h>
38 #include <unistd.h>
39 #include <stdio.h>
40 #include <fcntl.h>
41 #include <ctype.h>
42 #include <signal.h>
43 #include <pwd.h>
44 #include <errno.h>
45 #include <sys/stat.h>
46 #include <sys/types.h>
47 #include <dirent.h>
48 #if TIME_WITH_SYS_TIME
49 # include <sys/time.h>
50 # include <time.h>
51 #else
52 # if HAVE_SYS_TIME_H
53 #  include <sys/time.h>
54 # else
55 #  include <time.h>
56 # endif
57 #endif
58 #ifdef HAVE_SYSCALL_H
59 # include <syscall.h>
60 #else 
61 # if HAVE_SYS_SYSCALL_H
62 #  include <sys/syscall.h>
63 # endif
64 #endif
65
66 #include <sys/wait.h>
67 #include <string.h>
68 #include <limits.h>
69 #include <libcitadel.h>
70 #include "citadel.h"
71 #include "server.h"
72 #include "citserver.h"
73 #include "support.h"
74 #include "config.h"
75 #include "user_ops.h"
76 #include "database.h"
77 #include "msgbase.h"
78 #include "internet_addressing.h"
79 #include "serv_network.h"
80 #include "clientsocket.h"
81 #include "file_ops.h"
82 #include "citadel_dirs.h"
83 #include "threads.h"
84
85 #ifndef HAVE_SNPRINTF
86 #include "snprintf.h"
87 #endif
88
89 #include "context.h"
90 #include "netconfig.h"
91 #include "netspool.h"
92 #include "netmail.h"
93 #include "ctdl_module.h"
94
95
96         
97
98 int read_spoolcontrol_file(SpoolControl **scc, char *filename)
99 {
100         FILE *fp;
101         char instr[SIZ];
102         char buf[SIZ];
103         char nodename[256];
104         char roomname[ROOMNAMELEN];
105         size_t miscsize = 0;
106         size_t linesize = 0;
107         int skipthisline = 0;
108         namelist *nptr = NULL;
109         maplist *mptr = NULL;
110         SpoolControl *sc;
111
112         fp = fopen(filename, "r");
113         if (fp == NULL) {
114                 return 0;
115         }
116         sc = malloc(sizeof(SpoolControl));
117         memset(sc, 0, sizeof(SpoolControl));
118         *scc = sc;
119
120         while (fgets(buf, sizeof buf, fp) != NULL) {
121                 buf[strlen(buf)-1] = 0;
122
123                 extract_token(instr, buf, 0, '|', sizeof instr);
124                 if (!strcasecmp(instr, strof(lastsent))) {
125                         sc->lastsent = extract_long(buf, 1);
126                 }
127                 else if (!strcasecmp(instr, strof(listrecp))) {
128                         nptr = (namelist *)
129                                 malloc(sizeof(namelist));
130                         nptr->next = sc->listrecps;
131                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
132                         sc->listrecps = nptr;
133                 }
134                 else if (!strcasecmp(instr, strof(participate))) {
135                         nptr = (namelist *)
136                                 malloc(sizeof(namelist));
137                         nptr->next = sc->participates;
138                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
139                         sc->participates = nptr;
140                 }
141                 else if (!strcasecmp(instr, strof(digestrecp))) {
142                         nptr = (namelist *)
143                                 malloc(sizeof(namelist));
144                         nptr->next = sc->digestrecps;
145                         extract_token(nptr->name, buf, 1, '|', sizeof nptr->name);
146                         sc->digestrecps = nptr;
147                 }
148                 else if (!strcasecmp(instr, strof(ignet_push_share))) {
149                         extract_token(nodename, buf, 1, '|', sizeof nodename);
150                         extract_token(roomname, buf, 2, '|', sizeof roomname);
151                         mptr = (maplist *) malloc(sizeof(maplist));
152                         mptr->next = sc->ignet_push_shares;
153                         strcpy(mptr->remote_nodename, nodename);
154                         strcpy(mptr->remote_roomname, roomname);
155                         sc->ignet_push_shares = mptr;
156                 }
157                 else {
158                         /* Preserve 'other' lines ... *unless* they happen to
159                          * be subscribe/unsubscribe pendings with expired
160                          * timestamps.
161                          */
162                         skipthisline = 0;
163                         if (!strncasecmp(buf, strof(subpending)"|", 11)) {
164                                 if (time(NULL) - extract_long(buf, 4) > EXP) {
165                                         skipthisline = 1;
166                                 }
167                         }
168                         if (!strncasecmp(buf, strof(unsubpending)"|", 13)) {
169                                 if (time(NULL) - extract_long(buf, 3) > EXP) {
170                                         skipthisline = 1;
171                                 }
172                         }
173
174                         if (skipthisline == 0) {
175                                 linesize = strlen(buf);
176                                 sc->misc = realloc(sc->misc,
177                                         (miscsize + linesize + 2) );
178                                 sprintf(&sc->misc[miscsize], "%s\n", buf);
179                                 miscsize = miscsize + linesize + 1;
180                         }
181                 }
182
183
184         }
185         fclose(fp);
186         return 1;
187 }
188
189 void free_spoolcontrol_struct(SpoolControl **scc)
190 {
191         SpoolControl *sc;
192         namelist *nptr = NULL;
193         maplist *mptr = NULL;
194
195         sc = *scc;
196         while (sc->listrecps != NULL) {
197                 nptr = sc->listrecps->next;
198                 free(sc->listrecps);
199                 sc->listrecps = nptr;
200         }
201         /* Do the same for digestrecps */
202         while (sc->digestrecps != NULL) {
203                 nptr = sc->digestrecps->next;
204                 free(sc->digestrecps);
205                 sc->digestrecps = nptr;
206         }
207         /* Do the same for participates */
208         while (sc->participates != NULL) {
209                 nptr = sc->participates->next;
210                 free(sc->participates);
211                 sc->participates = nptr;
212         }
213         while (sc->ignet_push_shares != NULL) {
214                 mptr = sc->ignet_push_shares->next;
215                 free(sc->ignet_push_shares);
216                 sc->ignet_push_shares = mptr;
217         }
218         free(sc->misc);
219         free(sc);
220         *scc=NULL;
221 }
222
223 int writenfree_spoolcontrol_file(SpoolControl **scc, char *filename)
224 {
225         char tempfilename[PATH_MAX];
226         int TmpFD;
227         SpoolControl *sc;
228         namelist *nptr = NULL;
229         maplist *mptr = NULL;
230         long len;
231         time_t unixtime;
232         struct timeval tv;
233         long reltid; /* if we don't have SYS_gettid, use "random" value */
234         StrBuf *Cfg;
235         int rc;
236
237         len = strlen(filename);
238         memcpy(tempfilename, filename, len + 1);
239
240
241 #if defined(HAVE_SYSCALL_H) && defined (SYS_gettid)
242         reltid = syscall(SYS_gettid);
243 #endif
244         gettimeofday(&tv, NULL);
245         /* Promote to time_t; types differ on some OSes (like darwin) */
246         unixtime = tv.tv_sec;
247
248         sprintf(tempfilename + len, ".%ld-%ld", reltid, unixtime);
249         sc = *scc;
250         errno = 0;
251         TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
252         Cfg = NewStrBuf();
253         if ((TmpFD < 0) || (errno != 0)) {
254                 syslog(LOG_CRIT, "ERROR: cannot open %s: %s\n",
255                         filename, strerror(errno));
256                 free_spoolcontrol_struct(scc);
257                 unlink(tempfilename);
258         }
259         else {
260                 fchown(TmpFD, config.c_ctdluid, 0);
261                 StrBufAppendPrintf(Cfg, "lastsent|%ld\n", sc->lastsent);
262                 
263                 /* Write out the listrecps while freeing from memory at the
264                  * same time.  Am I clever or what?  :)
265                  */
266                 while (sc->listrecps != NULL) {
267                     StrBufAppendPrintf(Cfg, "listrecp|%s\n", sc->listrecps->name);
268                         nptr = sc->listrecps->next;
269                         free(sc->listrecps);
270                         sc->listrecps = nptr;
271                 }
272                 /* Do the same for digestrecps */
273                 while (sc->digestrecps != NULL) {
274                         StrBufAppendPrintf(Cfg, "digestrecp|%s\n", sc->digestrecps->name);
275                         nptr = sc->digestrecps->next;
276                         free(sc->digestrecps);
277                         sc->digestrecps = nptr;
278                 }
279                 /* Do the same for participates */
280                 while (sc->participates != NULL) {
281                         StrBufAppendPrintf(Cfg, "participate|%s\n", sc->participates->name);
282                         nptr = sc->participates->next;
283                         free(sc->participates);
284                         sc->participates = nptr;
285                 }
286                 while (sc->ignet_push_shares != NULL) {
287                         StrBufAppendPrintf(Cfg, "ignet_push_share|%s", sc->ignet_push_shares->remote_nodename);
288                         if (!IsEmptyStr(sc->ignet_push_shares->remote_roomname)) {
289                                 StrBufAppendPrintf(Cfg, "|%s", sc->ignet_push_shares->remote_roomname);
290                         }
291                         StrBufAppendPrintf(Cfg, "\n");
292                         mptr = sc->ignet_push_shares->next;
293                         free(sc->ignet_push_shares);
294                         sc->ignet_push_shares = mptr;
295                 }
296                 if (sc->misc != NULL) {
297                         StrBufAppendBufPlain(Cfg, sc->misc, -1, 0);
298                 }
299                 free(sc->misc);
300
301                 rc = write(TmpFD, ChrPtr(Cfg), StrLength(Cfg));
302                 if ((rc >=0 ) && (rc == StrLength(Cfg))) 
303                 {
304                         close(TmpFD);
305                         rename(tempfilename, filename);
306                 }
307                 else {
308                         syslog(LOG_EMERG, 
309                                       "unable to write %s; [%s]; not enough space on the disk?\n", 
310                                       tempfilename, 
311                                       strerror(errno));
312                         close(TmpFD);
313                         unlink(tempfilename);
314                 }
315                 FreeStrBuf(&Cfg);
316                 free(sc);
317                 *scc=NULL;
318         }
319         return 1;
320 }
321 int is_recipient(SpoolControl *sc, const char *Name)
322 {
323         namelist *nptr;
324         size_t len;
325
326         len = strlen(Name);
327         nptr = sc->listrecps;
328         while (nptr != NULL) {
329                 if (strncmp(Name, nptr->name, len)==0)
330                         return 1;
331                 nptr = nptr->next;
332         }
333         /* Do the same for digestrecps */
334         nptr = sc->digestrecps;
335         while (nptr != NULL) {
336                 if (strncmp(Name, nptr->name, len)==0)
337                         return 1;
338                 nptr = nptr->next;
339         }
340         /* Do the same for participates */
341         nptr = sc->participates;
342         while (nptr != NULL) {
343                 if (strncmp(Name, nptr->name, len)==0)
344                         return 1;
345                 nptr = nptr->next;
346         }
347         return 0;
348 }
349
350
351 /*
352  * Batch up and send all outbound traffic from the current room
353  */
354 void network_spoolout_room(RoomProcList *room_to_spool,                        
355                            HashList *working_ignetcfg,
356                            HashList *the_netmap)
357 {
358         char buf[SIZ];
359         char filename[PATH_MAX];
360         SpoolControl *sc;
361         int i;
362
363         /*
364          * If the room doesn't exist, don't try to perform its networking tasks.
365          * Normally this should never happen, but once in a while maybe a room gets
366          * queued for networking and then deleted before it can happen.
367          */
368         if (CtdlGetRoom(&CC->room, room_to_spool->name) != 0) {
369                 syslog(LOG_CRIT, "ERROR: cannot load <%s>\n", room_to_spool->name);
370                 return;
371         }
372
373         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
374         begin_critical_section(S_NETCONFIGS);
375
376         /* Only do net processing for rooms that have netconfigs */
377         if (!read_spoolcontrol_file(&sc, filename))
378         {
379                 end_critical_section(S_NETCONFIGS);
380                 return;
381         }
382         syslog(LOG_INFO, "Networking started for <%s>\n", CC->room.QRname);
383
384         sc->working_ignetcfg = working_ignetcfg;
385         sc->the_netmap = the_netmap;
386
387         /* If there are digest recipients, we have to build a digest */
388         if (sc->digestrecps != NULL) {
389                 sc->digestfp = tmpfile();
390                 fprintf(sc->digestfp, "Content-type: text/plain\n\n");
391         }
392
393         /* Do something useful */
394         CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
395                 network_spool_msg, sc);
396
397         /* If we wrote a digest, deliver it and then close it */
398         snprintf(buf, sizeof buf, "room_%s@%s",
399                 CC->room.QRname, config.c_fqdn);
400         for (i=0; buf[i]; ++i) {
401                 buf[i] = tolower(buf[i]);
402                 if (isspace(buf[i])) buf[i] = '_';
403         }
404         if (sc->digestfp != NULL) {
405                 fprintf(sc->digestfp,   " -----------------------------------"
406                                         "------------------------------------"
407                                         "-------\n"
408                                         "You are subscribed to the '%s' "
409                                         "list.\n"
410                                         "To post to the list: %s\n",
411                                         CC->room.QRname, buf
412                 );
413                 network_deliver_digest(sc);     /* deliver and close */
414         }
415
416         /* Now rewrite the config file */
417         writenfree_spoolcontrol_file(&sc, filename);
418         end_critical_section(S_NETCONFIGS);
419 }
420
421 /*
422  * Process a buffer containing a single message from a single file
423  * from the inbound queue 
424  */
425 void network_process_buffer(char *buffer, long size, HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
426 {
427         struct CitContext *CCC = CC;
428         StrBuf *Buf = NULL;
429         struct CtdlMessage *msg = NULL;
430         long pos;
431         int field;
432         struct recptypes *recp = NULL;
433         char target_room[ROOMNAMELEN];
434         struct ser_ret sermsg;
435         char *oldpath = NULL;
436         char filename[PATH_MAX];
437         FILE *fp;
438         const StrBuf *nexthop = NULL;
439         unsigned char firstbyte;
440         unsigned char lastbyte;
441
442         QN_syslog(LOG_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
443
444         /* Validate just a little bit.  First byte should be FF and * last byte should be 00. */
445         firstbyte = buffer[0];
446         lastbyte = buffer[size-1];
447         if ( (firstbyte != 255) || (lastbyte != 0) ) {
448                 QN_syslog(LOG_ERR, "Corrupt message ignored.  Length=%ld, firstbyte = %d, lastbyte = %d\n",
449                           size, firstbyte, lastbyte);
450                 return;
451         }
452
453         /* Set default target room to trash */
454         strcpy(target_room, TWITROOM);
455
456         /* Load the message into memory */
457         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
458         memset(msg, 0, sizeof(struct CtdlMessage));
459         msg->cm_magic = CTDLMESSAGE_MAGIC;
460         msg->cm_anon_type = buffer[1];
461         msg->cm_format_type = buffer[2];
462
463         for (pos = 3; pos < size; ++pos) {
464                 field = buffer[pos];
465                 msg->cm_fields[field] = strdup(&buffer[pos+1]);
466                 pos = pos + strlen(&buffer[(int)pos]);
467         }
468
469         /* Check for message routing */
470         if (msg->cm_fields['D'] != NULL) {
471                 if (strcasecmp(msg->cm_fields['D'], config.c_nodename)) {
472
473                         /* route the message */
474                         Buf = NewStrBufPlain(msg->cm_fields['D'], -1);
475                         if (is_valid_node(&nexthop, 
476                                           NULL, 
477                                           Buf, 
478                                           working_ignetcfg, 
479                                           the_netmap) == 0) 
480                         {
481                                 /* prepend our node to the path */
482                                 if (msg->cm_fields['P'] != NULL) {
483                                         oldpath = msg->cm_fields['P'];
484                                         msg->cm_fields['P'] = NULL;
485                                 }
486                                 else {
487                                         oldpath = strdup("unknown_user");
488                                 }
489                                 size = strlen(oldpath) + SIZ;
490                                 msg->cm_fields['P'] = malloc(size);
491                                 snprintf(msg->cm_fields['P'], size, "%s!%s",
492                                         config.c_nodename, oldpath);
493                                 free(oldpath);
494
495                                 /* serialize the message */
496                                 serialize_message(&sermsg, msg);
497
498                                 /* now send it */
499                                 if (StrLength(nexthop) == 0) {
500                                         nexthop = Buf;
501                                 }
502                                 snprintf(filename,
503                                          sizeof filename,
504                                          "%s/%s@%lx%x",
505                                          ctdl_netout_dir,
506                                          ChrPtr(nexthop),
507                                          time(NULL),
508                                          rand()
509                                 );
510                                 QN_syslog(LOG_DEBUG, "Appending to %s\n", filename);
511                                 fp = fopen(filename, "ab");
512                                 if (fp != NULL) {
513                                         fwrite(sermsg.ser, sermsg.len, 1, fp);
514                                         fclose(fp);
515                                 }
516                                 else {
517                                         QN_syslog(LOG_ERR, "%s: %s\n", filename, strerror(errno));
518                                 }
519                                 free(sermsg.ser);
520                                 CtdlFreeMessage(msg);
521                                 FreeStrBuf(&Buf);
522                                 return;
523                         }
524                         
525                         else {  /* invalid destination node name */
526                                 FreeStrBuf(&Buf);
527
528                                 network_bounce(msg,
529 "A message you sent could not be delivered due to an invalid destination node"
530 " name.  Please check the address and try sending the message again.\n");
531                                 msg = NULL;
532                                 return;
533
534                         }
535                 }
536         }
537
538         /*
539          * Check to see if we already have a copy of this message, and
540          * abort its processing if so.  (We used to post a warning to Aide>
541          * every time this happened, but the network is now so densely
542          * connected that it's inevitable.)
543          */
544         if (network_usetable(msg) != 0) {
545                 CtdlFreeMessage(msg);
546                 return;
547         }
548
549         /* Learn network topology from the path */
550         if ((msg->cm_fields['N'] != NULL) && (msg->cm_fields['P'] != NULL)) {
551                 network_learn_topology(msg->cm_fields['N'], 
552                                        msg->cm_fields['P'], 
553                                        the_netmap, 
554                                        netmap_changed);
555         }
556
557         /* Is the sending node giving us a very persuasive suggestion about
558          * which room this message should be saved in?  If so, go with that.
559          */
560         if (msg->cm_fields['C'] != NULL) {
561                 safestrncpy(target_room, msg->cm_fields['C'], sizeof target_room);
562         }
563
564         /* Otherwise, does it have a recipient?  If so, validate it... */
565         else if (msg->cm_fields['R'] != NULL) {
566                 recp = validate_recipients(msg->cm_fields['R'], NULL, 0);
567                 if (recp != NULL) if (recp->num_error != 0) {
568                         network_bounce(msg,
569                                 "A message you sent could not be delivered due to an invalid address.\n"
570                                 "Please check the address and try sending the message again.\n");
571                         msg = NULL;
572                         free_recipients(recp);
573                         QNM_syslog(LOG_DEBUG, "Bouncing message due to invalid recipient address.\n");
574                         return;
575                 }
576                 strcpy(target_room, "");        /* no target room if mail */
577         }
578
579         /* Our last shot at finding a home for this message is to see if
580          * it has the O field (Originating room) set.
581          */
582         else if (msg->cm_fields['O'] != NULL) {
583                 safestrncpy(target_room, msg->cm_fields['O'], sizeof target_room);
584         }
585
586         /* Strip out fields that are only relevant during transit */
587         if (msg->cm_fields['D'] != NULL) {
588                 free(msg->cm_fields['D']);
589                 msg->cm_fields['D'] = NULL;
590         }
591         if (msg->cm_fields['C'] != NULL) {
592                 free(msg->cm_fields['C']);
593                 msg->cm_fields['C'] = NULL;
594         }
595
596         /* save the message into a room */
597         if (PerformNetprocHooks(msg, target_room) == 0) {
598                 msg->cm_flags = CM_SKIP_HOOKS;
599                 CtdlSubmitMsg(msg, recp, target_room, 0);
600         }
601         CtdlFreeMessage(msg);
602         free_recipients(recp);
603 }
604
605
606 /*
607  * Process a single message from a single file from the inbound queue 
608  */
609 void network_process_message(FILE *fp, 
610                              long msgstart, 
611                              long msgend,
612                              HashList *working_ignetcfg,
613                              HashList *the_netmap, 
614                              int *netmap_changed)
615 {
616         long hold_pos;
617         long size;
618         char *buffer;
619
620         hold_pos = ftell(fp);
621         size = msgend - msgstart + 1;
622         buffer = malloc(size);
623         if (buffer != NULL) {
624                 fseek(fp, msgstart, SEEK_SET);
625                 if (fread(buffer, size, 1, fp) > 0) {
626                         network_process_buffer(buffer, 
627                                                size, 
628                                                working_ignetcfg, 
629                                                the_netmap, 
630                                                netmap_changed);
631                 }
632                 free(buffer);
633         }
634
635         fseek(fp, hold_pos, SEEK_SET);
636 }
637
638
639 /*
640  * Process a single file from the inbound queue 
641  */
642 void network_process_file(char *filename,
643                           HashList *working_ignetcfg,
644                           HashList *the_netmap, 
645                           int *netmap_changed)
646 {
647         struct CitContext *CCC = CC;
648         FILE *fp;
649         long msgstart = (-1L);
650         long msgend = (-1L);
651         long msgcur = 0L;
652         int ch;
653
654
655         fp = fopen(filename, "rb");
656         if (fp == NULL) {
657                 QN_syslog(LOG_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
658                 return;
659         }
660
661         fseek(fp, 0L, SEEK_END);
662         QN_syslog(LOG_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
663         rewind(fp);
664
665         /* Look for messages in the data stream and break them out */
666         while (ch = getc(fp), ch >= 0) {
667         
668                 if (ch == 255) {
669                         if (msgstart >= 0L) {
670                                 msgend = msgcur - 1;
671                                 network_process_message(fp,
672                                                         msgstart,
673                                                         msgend,
674                                                         working_ignetcfg,
675                                                         the_netmap,
676                                                         netmap_changed);
677                         }
678                         msgstart = msgcur;
679                 }
680
681                 ++msgcur;
682         }
683
684         msgend = msgcur - 1;
685         if (msgstart >= 0L) {
686                 network_process_message(fp,
687                                         msgstart,
688                                         msgend,
689                                         working_ignetcfg,
690                                         the_netmap,
691                                         netmap_changed);
692         }
693
694         fclose(fp);
695         unlink(filename);
696 }
697
698
699 /*
700  * Process anything in the inbound queue
701  */
702 void network_do_spoolin(HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
703 {
704         struct CitContext *CCC = CC;
705         DIR *dp;
706         struct dirent *d;
707         struct stat statbuf;
708         char filename[PATH_MAX];
709         static time_t last_spoolin_mtime = 0L;
710
711         /*
712          * Check the spoolin directory's modification time.  If it hasn't
713          * been touched, we don't need to scan it.
714          */
715         if (stat(ctdl_netin_dir, &statbuf)) return;
716         if (statbuf.st_mtime == last_spoolin_mtime) {
717                 QNM_syslog(LOG_DEBUG, "network: nothing in inbound queue\n");
718                 return;
719         }
720         last_spoolin_mtime = statbuf.st_mtime;
721         QNM_syslog(LOG_DEBUG, "network: processing inbound queue\n");
722
723         /*
724          * Ok, there's something interesting in there, so scan it.
725          */
726         dp = opendir(ctdl_netin_dir);
727         if (dp == NULL) return;
728
729         while (d = readdir(dp), d != NULL) {
730                 if ((strcmp(d->d_name, ".")) && (strcmp(d->d_name, ".."))) {
731                         snprintf(filename, 
732                                 sizeof filename,
733                                 "%s/%s",
734                                 ctdl_netin_dir,
735                                 d->d_name
736                         );
737                         network_process_file(filename,
738                                              working_ignetcfg,
739                                              the_netmap,
740                                              netmap_changed);
741                 }
742         }
743
744         closedir(dp);
745 }
746
747 /*
748  * Step 1: consolidate files in the outbound queue into one file per neighbor node
749  * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
750  */
751 void network_consolidate_spoolout(HashList *working_ignetcfg, HashList *the_netmap)
752 {
753         struct CitContext *CCC = CC;
754         IOBuffer IOB;
755         FDIOBuffer FDIO;
756         int d_namelen;
757         DIR *dp;
758         struct dirent *d;
759         struct dirent *filedir_entry;
760         const char *pch;
761         char spooloutfilename[PATH_MAX];
762         char filename[PATH_MAX];
763         const StrBuf *nexthop;
764         StrBuf *NextHop;
765         int i;
766         int nFailed = 0;
767
768         /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
769         d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
770         if (d == NULL)  return;
771
772         dp = opendir(ctdl_netout_dir);
773         if (dp == NULL) {
774                 free(d);
775                 return;
776         }
777
778         NextHop = NewStrBuf();
779         memset(&IOB, 0, sizeof(IOBuffer));
780         memset(&FDIO, 0, sizeof(FDIOBuffer));
781         FDIO.IOB = &IOB;
782
783         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
784                (filedir_entry != NULL))
785         {
786 #ifdef _DIRENT_HAVE_D_NAMELEN
787                 d_namelen = filedir_entry->d_namelen;
788 #else
789
790 #ifndef DT_UNKNOWN
791 #define DT_UNKNOWN     0
792 #define DT_DIR         4
793 #define DT_REG         8
794 #define DT_LNK         10
795
796 #define IFTODT(mode)   (((mode) & 0170000) >> 12)
797 #define DTTOIF(dirtype)        ((dirtype) << 12)
798 #endif
799                 d_namelen = strlen(filedir_entry->d_name);
800 #endif
801                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
802                         continue; /* Ignore backup files... */
803
804                 if ((d_namelen == 1) && 
805                     (filedir_entry->d_name[0] == '.'))
806                         continue;
807
808                 if ((d_namelen == 2) && 
809                     (filedir_entry->d_name[0] == '.') &&
810                     (filedir_entry->d_name[1] == '.'))
811                         continue;
812
813                 pch = strchr(filedir_entry->d_name, '@');
814                 if (pch == NULL)
815                         continue;
816
817                 snprintf(filename, 
818                          sizeof filename,
819                          "%s/%s",
820                          ctdl_netout_dir,
821                          filedir_entry->d_name);
822
823                 StrBufPlain(NextHop,
824                             filedir_entry->d_name,
825                             pch - filedir_entry->d_name);
826
827                 snprintf(spooloutfilename,
828                          sizeof spooloutfilename,
829                          "%s/%s",
830                          ctdl_netout_dir,
831                          ChrPtr(NextHop));
832
833                 QN_syslog(LOG_DEBUG, "Consolidate %s to %s\n", filename, ChrPtr(NextHop));
834                 if (network_talking_to(SKEY(NextHop), NTT_CHECK)) {
835                         nFailed++;
836                         QN_syslog(LOG_DEBUG,
837                                   "Currently online with %s - skipping for now\n",
838                                   ChrPtr(NextHop)
839                                 );
840                 }
841                 else {
842                         size_t dsize;
843                         size_t fsize;
844                         int fd;
845                         const char *err = NULL;
846                         network_talking_to(SKEY(NextHop), NTT_ADD);
847
848                         IOB.fd = open(filename, O_RDONLY);
849                         if (IOB.fd == -1) {
850                                 nFailed++;
851                                 QN_syslog(LOG_ERR,
852                                           "failed to open %s for reading due to %s; skipping.\n",
853                                           filename, strerror(errno)
854                                         );
855                                 network_talking_to(SKEY(NextHop), NTT_REMOVE);
856                                 continue;                               
857                         }
858                         
859                         fd = open(spooloutfilename,
860                                   O_EXCL|O_CREAT|O_NONBLOCK|O_WRONLY, 
861                                   S_IRUSR|S_IWUSR);
862                         if (fd == -1)
863                         {
864                                 fd = open(spooloutfilename,
865                                           O_EXCL|O_NONBLOCK|O_WRONLY, 
866                                           S_IRUSR | S_IWUSR);
867                         }
868                         if (fd == -1) {
869                                 nFailed++;
870                                 QN_syslog(LOG_ERR,
871                                           "failed to open %s for reading due to %s; skipping.\n",
872                                           spooloutfilename, strerror(errno)
873                                         );
874                                 close(IOB.fd);
875                                 network_talking_to(SKEY(NextHop), NTT_REMOVE);
876                                 continue;
877                         }
878                         dsize = lseek(fd, 0, SEEK_END);
879                         fsize = lseek(IOB.fd, 0, SEEK_END);
880                         
881                         FDIOBufferInit(&FDIO, &IOB, fd, fsize + dsize);
882                         FDIO.ChunkSendRemain = fsize;
883                         FDIO.TotalSentAlready = dsize;
884                         err = NULL;
885                         do {} while ((FileMoveChunked(&FDIO, &err) > 0) && (err == NULL));
886                         if (err == NULL) {
887                                 unlink(filename);
888                         }
889                         else {
890                                 nFailed++;
891                                 QN_syslog(LOG_ERR,
892                                           "failed to append to %s [%s]; rolling back..\n",
893                                           spooloutfilename, strerror(errno)
894                                         );
895                                 /* whoops partial append?? truncate spooloutfilename again! */
896                                 ftruncate(fd, dsize);
897                         }
898                         FDIOBufferDelete(&FDIO);
899                         close(IOB.fd);
900                         close(fd);
901                         network_talking_to(SKEY(NextHop), NTT_REMOVE);
902                 }
903         }
904         closedir(dp);
905
906         if (nFailed > 0) {
907                 FreeStrBuf(&NextHop);
908                 QN_syslog(LOG_INFO,
909                           "skipping Spoolcleanup because of %d files unprocessed.\n",
910                           nFailed
911                         );
912
913                 return;
914         }
915
916         /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
917         dp = opendir(ctdl_netout_dir);
918         if (dp == NULL) {
919                 FreeStrBuf(&NextHop);
920                 free(d);
921                 return;
922         }
923
924         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
925                (filedir_entry != NULL))
926         {
927 #ifdef _DIRENT_HAVE_D_NAMELEN
928                 d_namelen = filedir_entry->d_namelen;
929                 d_type = filedir_entry->d_type;
930 #else
931
932 #ifndef DT_UNKNOWN
933 #define DT_UNKNOWN     0
934 #define DT_DIR         4
935 #define DT_REG         8
936 #define DT_LNK         10
937
938 #define IFTODT(mode)   (((mode) & 0170000) >> 12)
939 #define DTTOIF(dirtype)        ((dirtype) << 12)
940 #endif
941                 d_namelen = strlen(filedir_entry->d_name);
942 #endif
943                 if ((d_namelen == 1) && 
944                     (filedir_entry->d_name[0] == '.'))
945                         continue;
946
947                 if ((d_namelen == 2) && 
948                     (filedir_entry->d_name[0] == '.') &&
949                     (filedir_entry->d_name[1] == '.'))
950                         continue;
951
952                 pch = strchr(filedir_entry->d_name, '@');
953                 if (pch == NULL) /* no @ in name? consolidated file. */
954                         continue;
955
956                 StrBufPlain(NextHop,
957                             filedir_entry->d_name,
958                             pch - filedir_entry->d_name);
959
960                 snprintf(filename, 
961                         sizeof filename,
962                         "%s/%s",
963                         ctdl_netout_dir,
964                         filedir_entry->d_name
965                 );
966
967                 i = is_valid_node(&nexthop,
968                                   NULL,
969                                   NextHop,
970                                   working_ignetcfg,
971                                   the_netmap);
972         
973                 if ( (i != 0) || (StrLength(nexthop) > 0) ) {
974                         unlink(filename);
975                 }
976         }
977         FreeStrBuf(&NextHop);
978         free(d);
979         closedir(dp);
980 }
981
982
983
984
985 /*
986  * It's ok if these directories already exist.  Just fail silently.
987  */
988 void create_spool_dirs(void) {
989         if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
990                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
991         if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
992                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
993         if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
994                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
995         if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
996                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
997         if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
998                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
999         if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
1000                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
1001         if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
1002                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
1003         if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
1004                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
1005 }
1006
1007 /*
1008  * Module entry point
1009  */
1010 CTDL_MODULE_INIT(network_spool)
1011 {
1012         if (!threading)
1013         {
1014                 create_spool_dirs();
1015 //////todo              CtdlRegisterCleanupHook(destroy_network_queue_room);
1016         }
1017         return "network_spool";
1018 }