Adjust preconditions for attempting a digest delivery.
[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         /* If there are digest recipients, we have to build a digest */
357         if (sc->Users[digestrecp] != NULL) {
358                 
359                 sc->digestfp = create_digest_file(&sc->room);
360                 sc->haveDigest = ftell(sc->digestfp) > 0;
361                 if (!sc->haveDigest) {
362                         fprintf(sc->digestfp, "Content-type: text/plain\n\n");
363                 }
364         }
365
366         CalcListID(sc);
367
368         /* remember where we started... */
369         lastsent = sc->lastsent;
370
371         /* Fetch the messages we ought to send & prepare them. */
372         CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL,
373                 network_spool_msg, sc);
374
375         if (StrLength(sc->Users[roommailalias]) > 0)
376         {
377                 long len;
378                 len = StrLength(sc->Users[roommailalias]);
379                 if (len + 1 > sizeof(buf))
380                         len = sizeof(buf) - 1;
381                 memcpy(buf, ChrPtr(sc->Users[roommailalias]), len);
382                 buf[len] = '\0';
383         }
384         else
385         {
386                 snprintf(buf, sizeof buf, "room_%s@%s",
387                          CCC->room.QRname, config.c_fqdn);
388         }
389
390         for (i=0; buf[i]; ++i) {
391                 buf[i] = tolower(buf[i]);
392                 if (isspace(buf[i])) buf[i] = '_';
393         }
394
395
396         /* If we wrote a digest, deliver it and then close it */
397         if (sc->digestfp != NULL) {
398                 time_t now = time(NULL);
399                 time_t secs_today = now % (24 * 60 * 60);
400                 long delta = 0;
401
402                 if (last_digest_delivery != 0) {
403                         delta = now - last_digest_delivery;
404                         delta = (24 * 60 * 60) - delta;
405                 }
406
407                 if (sc->haveDigest     &&
408                     (secs_today < 300) && 
409                     (delta < 300) )
410                 {
411                         last_digest_delivery = now;
412                         fprintf(sc->digestfp,
413                                 " -----------------------------------"
414                                 "------------------------------------"
415                                 "-------\n"
416                                 "You are subscribed to the '%s' "
417                                 "list.\n"
418                                 "To post to the list: %s\n",
419                                 CCC->room.QRname, buf
420                                 );
421                         network_deliver_digest(sc);     /* deliver */
422                 }
423                 fclose(sc->digestfp);
424                 sc->digestfp = NULL;
425                 remove_digest_file(&sc->room);
426         }
427
428         /* Now rewrite the config file */
429         if (sc->lastsent != lastsent)
430         {
431                 begin_critical_section(S_NETCONFIGS);
432                 sc->RNCfg = CtdlGetNetCfgForRoom(sc->room.QRnumber);
433
434                 sc->RNCfg->lastsent = sc->lastsent;
435                 sc->RNCfg->changed = 1;
436                 end_critical_section(S_NETCONFIGS);
437         }
438 }
439
440 /*
441  * Process a buffer containing a single message from a single file
442  * from the inbound queue 
443  */
444 void network_process_buffer(char *buffer, long size, HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
445 {
446         long len;
447         struct CitContext *CCC = CC;
448         StrBuf *Buf = NULL;
449         struct CtdlMessage *msg = NULL;
450         long pos;
451         int field;
452         recptypes *recp = NULL;
453         char target_room[ROOMNAMELEN];
454         struct ser_ret sermsg;
455         char filename[PATH_MAX];
456         FILE *fp;
457         const StrBuf *nexthop = NULL;
458         unsigned char firstbyte;
459         unsigned char lastbyte;
460
461         QN_syslog(LOG_DEBUG, "network_process_buffer() processing %ld bytes\n", size);
462
463         /* Validate just a little bit.  First byte should be FF and * last byte should be 00. */
464         firstbyte = buffer[0];
465         lastbyte = buffer[size-1];
466         if ( (firstbyte != 255) || (lastbyte != 0) ) {
467                 QN_syslog(LOG_ERR, "Corrupt message ignored.  Length=%ld, firstbyte = %d, lastbyte = %d\n",
468                           size, firstbyte, lastbyte);
469                 return;
470         }
471
472         /* Set default target room to trash */
473         strcpy(target_room, TWITROOM);
474
475         /* Load the message into memory */
476         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
477         memset(msg, 0, sizeof(struct CtdlMessage));
478         msg->cm_magic = CTDLMESSAGE_MAGIC;
479         msg->cm_anon_type = buffer[1];
480         msg->cm_format_type = buffer[2];
481
482         for (pos = 3; pos < size; ++pos) {
483                 field = buffer[pos];
484                 len = strlen(buffer + pos + 1);
485                 CM_SetField(msg, field, buffer + pos + 1, len);
486                 pos = pos + len + 1;
487         }
488
489         /* Check for message routing */
490         if (!CM_IsEmpty(msg, eDestination)) {
491                 if (strcasecmp(msg->cm_fields[eDestination], config.c_nodename)) {
492
493                         /* route the message */
494                         Buf = NewStrBufPlain(CM_KEY(msg,eDestination));
495                         if (CtdlIsValidNode(&nexthop, 
496                                             NULL, 
497                                             Buf, 
498                                             working_ignetcfg, 
499                                             the_netmap) == 0) 
500                         {
501                                 Netmap_AddMe(msg, HKEY("unknown_user"));
502
503                                 /* serialize the message */
504                                 CtdlSerializeMessage(&sermsg, msg);
505
506                                 /* now send it */
507                                 if (StrLength(nexthop) == 0) {
508                                         nexthop = Buf;
509                                 }
510                                 snprintf(filename,
511                                          sizeof filename,
512                                          "%s/%s@%lx%x",
513                                          ctdl_netout_dir,
514                                          ChrPtr(nexthop),
515                                          time(NULL),
516                                          rand()
517                                 );
518                                 QN_syslog(LOG_DEBUG, "Appending to %s\n", filename);
519                                 fp = fopen(filename, "ab");
520                                 if (fp != NULL) {
521                                         fwrite(sermsg.ser, sermsg.len, 1, fp);
522                                         fclose(fp);
523                                 }
524                                 else {
525                                         QN_syslog(LOG_ERR, "%s: %s\n", filename, strerror(errno));
526                                 }
527                                 free(sermsg.ser);
528                                 CM_Free(msg);
529                                 FreeStrBuf(&Buf);
530                                 return;
531                         }
532                         
533                         else {  /* invalid destination node name */
534                                 FreeStrBuf(&Buf);
535
536                                 network_bounce(msg,
537 "A message you sent could not be delivered due to an invalid destination node"
538 " name.  Please check the address and try sending the message again.\n");
539                                 msg = NULL;
540                                 return;
541
542                         }
543                 }
544         }
545
546         /*
547          * Check to see if we already have a copy of this message, and
548          * abort its processing if so.  (We used to post a warning to Aide>
549          * every time this happened, but the network is now so densely
550          * connected that it's inevitable.)
551          */
552         if (network_usetable(msg) != 0) {
553                 CM_Free(msg);
554                 return;
555         }
556
557         /* Learn network topology from the path */
558         if (!CM_IsEmpty(msg, eNodeName) && !CM_IsEmpty(msg, eMessagePath)) {
559                 NetworkLearnTopology(msg->cm_fields[eNodeName], 
560                                      msg->cm_fields[eMessagePath], 
561                                      the_netmap, 
562                                      netmap_changed);
563         }
564
565         /* Is the sending node giving us a very persuasive suggestion about
566          * which room this message should be saved in?  If so, go with that.
567          */
568         if (!CM_IsEmpty(msg, eRemoteRoom)) {
569                 safestrncpy(target_room, msg->cm_fields[eRemoteRoom], sizeof target_room);
570         }
571
572         /* Otherwise, does it have a recipient?  If so, validate it... */
573         else if (!CM_IsEmpty(msg, eRecipient)) {
574                 recp = validate_recipients(msg->cm_fields[eRecipient], NULL, 0);
575                 if (recp != NULL) if (recp->num_error != 0) {
576                         network_bounce(msg,
577                                 "A message you sent could not be delivered due to an invalid address.\n"
578                                 "Please check the address and try sending the message again.\n");
579                         msg = NULL;
580                         free_recipients(recp);
581                         QNM_syslog(LOG_DEBUG, "Bouncing message due to invalid recipient address.\n");
582                         return;
583                 }
584                 strcpy(target_room, "");        /* no target room if mail */
585         }
586
587         /* Our last shot at finding a home for this message is to see if
588          * it has the eOriginalRoom (O) field (Originating room) set.
589          */
590         else if (!CM_IsEmpty(msg, eOriginalRoom)) {
591                 safestrncpy(target_room, msg->cm_fields[eOriginalRoom], sizeof target_room);
592         }
593
594         /* Strip out fields that are only relevant during transit */
595         CM_FlushField(msg, eDestination);
596         CM_FlushField(msg, eRemoteRoom);
597
598         /* save the message into a room */
599         if (PerformNetprocHooks(msg, target_room) == 0) {
600                 msg->cm_flags = CM_SKIP_HOOKS;
601                 CtdlSubmitMsg(msg, recp, target_room, 0);
602         }
603         CM_Free(msg);
604         free_recipients(recp);
605 }
606
607
608 /*
609  * Process a single message from a single file from the inbound queue 
610  */
611 void network_process_message(FILE *fp, 
612                              long msgstart, 
613                              long msgend,
614                              HashList *working_ignetcfg,
615                              HashList *the_netmap, 
616                              int *netmap_changed)
617 {
618         long hold_pos;
619         long size;
620         char *buffer;
621
622         hold_pos = ftell(fp);
623         size = msgend - msgstart + 1;
624         buffer = malloc(size);
625         if (buffer != NULL) {
626                 fseek(fp, msgstart, SEEK_SET);
627                 if (fread(buffer, size, 1, fp) > 0) {
628                         network_process_buffer(buffer, 
629                                                size, 
630                                                working_ignetcfg, 
631                                                the_netmap, 
632                                                netmap_changed);
633                 }
634                 free(buffer);
635         }
636
637         fseek(fp, hold_pos, SEEK_SET);
638 }
639
640
641 /*
642  * Process a single file from the inbound queue 
643  */
644 void network_process_file(char *filename,
645                           HashList *working_ignetcfg,
646                           HashList *the_netmap, 
647                           int *netmap_changed)
648 {
649         struct CitContext *CCC = CC;
650         FILE *fp;
651         long msgstart = (-1L);
652         long msgend = (-1L);
653         long msgcur = 0L;
654         int ch;
655         int nMessages = 0;
656
657         fp = fopen(filename, "rb");
658         if (fp == NULL) {
659                 QN_syslog(LOG_CRIT, "Error opening %s: %s\n", filename, strerror(errno));
660                 return;
661         }
662
663         fseek(fp, 0L, SEEK_END);
664         QN_syslog(LOG_INFO, "network: processing %ld bytes from %s\n", ftell(fp), filename);
665         rewind(fp);
666
667         /* Look for messages in the data stream and break them out */
668         while (ch = getc(fp), ch >= 0) {
669         
670                 if (ch == 255) {
671                         if (msgstart >= 0L) {
672                                 msgend = msgcur - 1;
673                                 network_process_message(fp,
674                                                         msgstart,
675                                                         msgend,
676                                                         working_ignetcfg,
677                                                         the_netmap,
678                                                         netmap_changed);
679                         }
680                         msgstart = msgcur;
681                 }
682
683                 ++msgcur;
684                 nMessages ++;
685         }
686
687         msgend = msgcur - 1;
688         if (msgstart >= 0L) {
689                 network_process_message(fp,
690                                         msgstart,
691                                         msgend,
692                                         working_ignetcfg,
693                                         the_netmap,
694                                         netmap_changed);
695                 nMessages ++;
696         }
697
698         if (nMessages > 0)
699                 QN_syslog(LOG_INFO,
700                           "network: processed %d messages in %s\n",
701                           nMessages,
702                           filename);
703
704         fclose(fp);
705         unlink(filename);
706 }
707
708
709 /*
710  * Process anything in the inbound queue
711  */
712 void network_do_spoolin(HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
713 {
714         struct CitContext *CCC = CC;
715         DIR *dp;
716         struct dirent *d;
717         struct dirent *filedir_entry;
718         struct stat statbuf;
719         char filename[PATH_MAX];
720         static time_t last_spoolin_mtime = 0L;
721         int d_type = 0;
722         int d_namelen;
723
724         /*
725          * Check the spoolin directory's modification time.  If it hasn't
726          * been touched, we don't need to scan it.
727          */
728         if (stat(ctdl_netin_dir, &statbuf)) return;
729         if (statbuf.st_mtime == last_spoolin_mtime) {
730                 QNM_syslog(LOG_DEBUG, "network: nothing in inbound queue\n");
731                 return;
732         }
733         last_spoolin_mtime = statbuf.st_mtime;
734         QNM_syslog(LOG_DEBUG, "network: processing inbound queue\n");
735
736         /*
737          * Ok, there's something interesting in there, so scan it.
738          */
739         dp = opendir(ctdl_netin_dir);
740         if (dp == NULL) return;
741
742         d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
743         if (d == NULL) {
744                 closedir(dp);
745                 return;
746         }
747
748         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
749                (filedir_entry != NULL))
750         {
751 #ifdef _DIRENT_HAVE_D_NAMLEN
752                 d_namelen = filedir_entry->d_namlen;
753
754 #else
755                 d_namelen = strlen(filedir_entry->d_name);
756 #endif
757
758 #ifdef _DIRENT_HAVE_D_TYPE
759                 d_type = filedir_entry->d_type;
760 #else
761                 d_type = DT_UNKNOWN;
762 #endif
763                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
764                         continue; /* Ignore backup files... */
765
766                 if ((d_namelen == 1) && 
767                     (filedir_entry->d_name[0] == '.'))
768                         continue;
769
770                 if ((d_namelen == 2) && 
771                     (filedir_entry->d_name[0] == '.') &&
772                     (filedir_entry->d_name[1] == '.'))
773                         continue;
774
775                 if (d_type == DT_UNKNOWN) {
776                         struct stat s;
777                         char path[PATH_MAX];
778
779                         snprintf(path,
780                                  PATH_MAX,
781                                  "%s/%s", 
782                                  ctdl_netin_dir,
783                                  filedir_entry->d_name);
784
785                         if (lstat(path, &s) == 0) {
786                                 d_type = IFTODT(s.st_mode);
787                         }
788                 }
789
790                 switch (d_type)
791                 {
792                 case DT_DIR:
793                         break;
794                 case DT_LNK: /* TODO: check whether its a file or a directory */
795                 case DT_REG:
796                         snprintf(filename, 
797                                 sizeof filename,
798                                 "%s/%s",
799                                 ctdl_netin_dir,
800                                 d->d_name
801                         );
802                         network_process_file(filename,
803                                              working_ignetcfg,
804                                              the_netmap,
805                                              netmap_changed);
806                 }
807         }
808
809         closedir(dp);
810         free(d);
811 }
812
813 /*
814  * Step 1: consolidate files in the outbound queue into one file per neighbor node
815  * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
816  */
817 void network_consolidate_spoolout(HashList *working_ignetcfg, HashList *the_netmap)
818 {
819         struct CitContext *CCC = CC;
820         IOBuffer IOB;
821         FDIOBuffer FDIO;
822         int d_namelen;
823         DIR *dp;
824         struct dirent *d;
825         struct dirent *filedir_entry;
826         const char *pch;
827         char spooloutfilename[PATH_MAX];
828         char filename[PATH_MAX];
829         const StrBuf *nexthop;
830         StrBuf *NextHop;
831         int i;
832         struct stat statbuf;
833         int nFailed = 0;
834         int d_type = 0;
835
836
837         /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
838         d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
839         if (d == NULL)  return;
840
841         dp = opendir(ctdl_netout_dir);
842         if (dp == NULL) {
843                 free(d);
844                 return;
845         }
846
847         NextHop = NewStrBuf();
848         memset(&IOB, 0, sizeof(IOBuffer));
849         memset(&FDIO, 0, sizeof(FDIOBuffer));
850         FDIO.IOB = &IOB;
851
852         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
853                (filedir_entry != NULL))
854         {
855 #ifdef _DIRENT_HAVE_D_NAMLEN
856                 d_namelen = filedir_entry->d_namlen;
857
858 #else
859                 d_namelen = strlen(filedir_entry->d_name);
860 #endif
861
862 #ifdef _DIRENT_HAVE_D_TYPE
863                 d_type = filedir_entry->d_type;
864 #else
865                 d_type = DT_UNKNOWN;
866 #endif
867                 if (d_type == DT_DIR)
868                         continue;
869
870                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
871                         continue; /* Ignore backup files... */
872
873                 if ((d_namelen == 1) && 
874                     (filedir_entry->d_name[0] == '.'))
875                         continue;
876
877                 if ((d_namelen == 2) && 
878                     (filedir_entry->d_name[0] == '.') &&
879                     (filedir_entry->d_name[1] == '.'))
880                         continue;
881
882                 pch = strchr(filedir_entry->d_name, '@');
883                 if (pch == NULL)
884                         continue;
885
886                 snprintf(filename, 
887                          sizeof filename,
888                          "%s/%s",
889                          ctdl_netout_dir,
890                          filedir_entry->d_name);
891
892                 StrBufPlain(NextHop,
893                             filedir_entry->d_name,
894                             pch - filedir_entry->d_name);
895
896                 snprintf(spooloutfilename,
897                          sizeof spooloutfilename,
898                          "%s/%s",
899                          ctdl_netout_dir,
900                          ChrPtr(NextHop));
901
902                 QN_syslog(LOG_DEBUG, "Consolidate %s to %s\n", filename, ChrPtr(NextHop));
903                 if (CtdlNetworkTalkingTo(SKEY(NextHop), NTT_CHECK)) {
904                         nFailed++;
905                         QN_syslog(LOG_DEBUG,
906                                   "Currently online with %s - skipping for now\n",
907                                   ChrPtr(NextHop)
908                                 );
909                 }
910                 else {
911                         size_t dsize;
912                         size_t fsize;
913                         int infd, outfd;
914                         const char *err = NULL;
915                         CtdlNetworkTalkingTo(SKEY(NextHop), NTT_ADD);
916
917                         infd = open(filename, O_RDONLY);
918                         if (infd == -1) {
919                                 nFailed++;
920                                 QN_syslog(LOG_ERR,
921                                           "failed to open %s for reading due to %s; skipping.\n",
922                                           filename, strerror(errno)
923                                         );
924                                 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
925                                 continue;                               
926                         }
927                         
928                         outfd = open(spooloutfilename,
929                                   O_EXCL|O_CREAT|O_NONBLOCK|O_WRONLY, 
930                                   S_IRUSR|S_IWUSR);
931                         if (outfd == -1)
932                         {
933                                 outfd = open(spooloutfilename,
934                                              O_EXCL|O_NONBLOCK|O_WRONLY, 
935                                              S_IRUSR | S_IWUSR);
936                         }
937                         if (outfd == -1) {
938                                 nFailed++;
939                                 QN_syslog(LOG_ERR,
940                                           "failed to open %s for reading due to %s; skipping.\n",
941                                           spooloutfilename, strerror(errno)
942                                         );
943                                 close(infd);
944                                 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
945                                 continue;
946                         }
947
948                         dsize = lseek(outfd, 0, SEEK_END);
949                         lseek(outfd, -dsize, SEEK_SET);
950
951                         fstat(infd, &statbuf);
952                         fsize = statbuf.st_size;
953 /*
954                         fsize = lseek(infd, 0, SEEK_END);
955 */                      
956                         IOB.fd = infd;
957                         FDIOBufferInit(&FDIO, &IOB, outfd, fsize + dsize);
958                         FDIO.ChunkSendRemain = fsize;
959                         FDIO.TotalSentAlready = dsize;
960                         err = NULL;
961                         errno = 0;
962                         do {} while ((FileMoveChunked(&FDIO, &err) > 0) && (err == NULL));
963                         if (err == NULL) {
964                                 unlink(filename);
965                                 QN_syslog(LOG_DEBUG,
966                                           "Spoolfile %s now "SIZE_T_FMT" k\n",
967                                           spooloutfilename,
968                                           (dsize + fsize)/1024
969                                         );                              
970                         }
971                         else {
972                                 nFailed++;
973                                 QN_syslog(LOG_ERR,
974                                           "failed to append to %s [%s]; rolling back..\n",
975                                           spooloutfilename, strerror(errno)
976                                         );
977                                 /* whoops partial append?? truncate spooloutfilename again! */
978                                 ftruncate(outfd, dsize);
979                         }
980                         FDIOBufferDelete(&FDIO);
981                         close(infd);
982                         close(outfd);
983                         CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
984                 }
985         }
986         closedir(dp);
987
988         if (nFailed > 0) {
989                 FreeStrBuf(&NextHop);
990                 QN_syslog(LOG_INFO,
991                           "skipping Spoolcleanup because of %d files unprocessed.\n",
992                           nFailed
993                         );
994
995                 return;
996         }
997
998         /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
999         dp = opendir(ctdl_netout_dir);
1000         if (dp == NULL) {
1001                 FreeStrBuf(&NextHop);
1002                 free(d);
1003                 return;
1004         }
1005
1006         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
1007                (filedir_entry != NULL))
1008         {
1009 #ifdef _DIRENT_HAVE_D_NAMLEN
1010                 d_namelen = filedir_entry->d_namlen;
1011
1012 #else
1013                 d_namelen = strlen(filedir_entry->d_name);
1014 #endif
1015
1016 #ifdef _DIRENT_HAVE_D_TYPE
1017                 d_type = filedir_entry->d_type;
1018 #else
1019                 d_type = DT_UNKNOWN;
1020 #endif
1021                 if (d_type == DT_DIR)
1022                         continue;
1023
1024                 if ((d_namelen == 1) && 
1025                     (filedir_entry->d_name[0] == '.'))
1026                         continue;
1027
1028                 if ((d_namelen == 2) && 
1029                     (filedir_entry->d_name[0] == '.') &&
1030                     (filedir_entry->d_name[1] == '.'))
1031                         continue;
1032
1033                 pch = strchr(filedir_entry->d_name, '@');
1034                 if (pch == NULL) /* no @ in name? consolidated file. */
1035                         continue;
1036
1037                 StrBufPlain(NextHop,
1038                             filedir_entry->d_name,
1039                             pch - filedir_entry->d_name);
1040
1041                 snprintf(filename, 
1042                         sizeof filename,
1043                         "%s/%s",
1044                         ctdl_netout_dir,
1045                         filedir_entry->d_name
1046                 );
1047
1048                 i = CtdlIsValidNode(&nexthop,
1049                                     NULL,
1050                                     NextHop,
1051                                     working_ignetcfg,
1052                                     the_netmap);
1053         
1054                 if ( (i != 0) || (StrLength(nexthop) > 0) ) {
1055                         unlink(filename);
1056                 }
1057         }
1058         FreeStrBuf(&NextHop);
1059         free(d);
1060         closedir(dp);
1061 }
1062
1063 void free_spoolcontrol_struct(SpoolControl **sc)
1064 {
1065         free_spoolcontrol_struct_members(*sc);
1066         free(*sc);
1067         *sc = NULL;
1068 }
1069
1070 void free_spoolcontrol_struct_members(SpoolControl *sc)
1071 {
1072         int i;
1073         FreeStrBuf(&sc->RoomInfo);
1074         FreeStrBuf(&sc->ListID);
1075         for (i = 0; i < maxRoomNetCfg; i++)
1076                 FreeStrBuf(&sc->Users[i]);
1077 }
1078
1079
1080
1081 /*
1082  * It's ok if these directories already exist.  Just fail silently.
1083  */
1084 void create_spool_dirs(void) {
1085         if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
1086                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
1087         if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
1088                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
1089         if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
1090                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
1091         if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
1092                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
1093         if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
1094                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
1095         if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
1096                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
1097         if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
1098                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
1099         if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
1100                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
1101 }
1102
1103 /*
1104  * Module entry point
1105  */
1106 CTDL_MODULE_INIT(network_spool)
1107 {
1108         if (!threading)
1109         {
1110                 CtdlREGISTERRoomCfgType(subpending,       ParseSubPendingLine,   0, 5, SerializeGeneric,  DeleteGenericCfgLine); /// todo: move this to mailinglist manager
1111                 CtdlREGISTERRoomCfgType(unsubpending,     ParseUnSubPendingLine, 0, 4, SerializeGeneric,  DeleteGenericCfgLine); /// todo: move this to mailinglist manager
1112                 CtdlREGISTERRoomCfgType(lastsent,         ParseLastSent,         1, 1, SerializeLastSent, DeleteLastSent);
1113                 CtdlREGISTERRoomCfgType(ignet_push_share, ParseGeneric,          0, 2, SerializeGeneric,  DeleteGenericCfgLine); // [remotenode|remoteroomname (optional)]// todo: move this to the ignet client
1114                 CtdlREGISTERRoomCfgType(listrecp,         ParseGeneric,          0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1115                 CtdlREGISTERRoomCfgType(digestrecp,       ParseGeneric,          0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1116                 CtdlREGISTERRoomCfgType(participate,      ParseGeneric,          0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1117                 CtdlREGISTERRoomCfgType(roommailalias,    ParseRoomAlias,        0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1118
1119                 create_spool_dirs();
1120 //////todo              CtdlRegisterCleanupHook(destroy_network_queue_room);
1121         }
1122         return "network_spool";
1123 }