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