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