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