697ca62c095a844477a4c71402aa8c1ac3f9305e
[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-2016 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, "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, "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, "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, "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, "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, "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         const char *err;
329         int fd;
330         struct CitContext *CCC = CC;
331         char filename[PATH_MAX];
332 #define MAX_LISTIDLENGTH 150
333
334         assoc_file_name(filename, sizeof filename, &sc->room, ctdl_info_dir);
335         fd = open(filename, 0);
336
337         if (fd > 0) {
338                 struct stat stbuf;
339
340                 if ((fstat(fd, &stbuf) == 0) &&
341                     (stbuf.st_size > 0))
342                 {
343                         sc->RoomInfo = NewStrBufPlain(NULL, stbuf.st_size + 1);
344                         StrBufReadBLOB(sc->RoomInfo, &fd, 0, stbuf.st_size, &err);
345                 }
346                 close(fd);
347         }
348
349         sc->ListID = NewStrBufPlain(NULL, 1024);
350         if (StrLength(sc->RoomInfo) > 0)
351         {
352                 const char *Pos = NULL;
353                 StrBufSipLine(sc->ListID, sc->RoomInfo, &Pos);
354
355                 if (StrLength(sc->ListID) > MAX_LISTIDLENGTH)
356                 {
357                         StrBufCutAt(sc->ListID, MAX_LISTIDLENGTH, NULL);
358                         StrBufAppendBufPlain(sc->ListID, HKEY("..."), 0);
359                 }
360                 StrBufAsciify(sc->ListID, ' ');
361         }
362         else
363         {
364                 StrBufAppendBufPlain(sc->ListID, CCC->room.QRname, -1, 0);
365         }
366
367         StrBufAppendBufPlain(sc->ListID, HKEY("<"), 0);
368         RoomName = NewStrBufPlain (sc->room.QRname, -1);
369         StrBufAsciify(RoomName, '_');
370         StrBufReplaceChars(RoomName, ' ', '_');
371
372         if (StrLength(sc->Users[roommailalias]) > 0)
373         {
374                 long Pos;
375                 const char *AtPos;
376
377                 Pos = StrLength(sc->ListID);
378                 StrBufAppendBuf(sc->ListID, sc->Users[roommailalias], 0);
379                 AtPos = strchr(ChrPtr(sc->ListID) + Pos, '@');
380
381                 if (AtPos != NULL)
382                 {
383                         StrBufPeek(sc->ListID, AtPos, 0, '.');
384                 }
385         }
386         else
387         {
388                 StrBufAppendBufPlain(sc->ListID, HKEY("room_"), 0);
389                 StrBufAppendBuf(sc->ListID, RoomName, 0);
390                 StrBufAppendBufPlain(sc->ListID, HKEY("."), 0);
391                 StrBufAppendBufPlain(sc->ListID, CtdlGetConfigStr("c_fqdn"), -1, 0);
392                 /*
393                  * this used to be:
394                  * roomname <Room-Number.list-id.fqdn>
395                  * according to rfc2919.txt it only has to be a uniq identifier
396                  * under the domain of the system; 
397                  * in general MUAs use it to calculate the reply address nowadays.
398                  */
399         }
400         StrBufAppendBufPlain(sc->ListID, HKEY(">"), 0);
401
402         if (StrLength(sc->Users[roommailalias]) == 0)
403         {
404                 sc->Users[roommailalias] = NewStrBuf();
405                 
406                 StrBufAppendBufPlain(sc->Users[roommailalias], HKEY("room_"), 0);
407                 StrBufAppendBuf(sc->Users[roommailalias], RoomName, 0);
408                 StrBufAppendBufPlain(sc->Users[roommailalias], HKEY("@"), 0);
409                 StrBufAppendBufPlain(sc->Users[roommailalias], CtdlGetConfigStr("c_fqdn"), -1, 0);
410
411                 StrBufLowerCase(sc->Users[roommailalias]);
412         }
413
414         FreeStrBuf(&RoomName);
415 }
416
417 static time_t last_digest_delivery = 0;
418
419 /*
420  * Batch up and send all outbound traffic from the current room
421  */
422 void network_spoolout_room(SpoolControl *sc)
423 {
424         struct CitContext *CCC = CC;
425         char buf[SIZ];
426         int i;
427         long lastsent;
428
429         /*
430          * If the room doesn't exist, don't try to perform its networking tasks.
431          * Normally this should never happen, but once in a while maybe a room gets
432          * queued for networking and then deleted before it can happen.
433          */
434         memcpy (&CCC->room, &sc->room, sizeof(ctdlroom));
435
436         syslog(LOG_INFO, "network_spoolout_room(room=%s, lastsent=%ld)", CCC->room.QRname, sc->lastsent);
437
438         CalcListID(sc);
439
440         /* remember where we started... */
441         lastsent = sc->lastsent;
442
443         /* Fetch the messages we ought to send & prepare them. */
444         CtdlForEachMessage(MSGS_GT, sc->lastsent, NULL, NULL, NULL, network_spool_msg, sc);
445
446         if (StrLength(sc->Users[roommailalias]) > 0)
447         {
448                 long len;
449                 len = StrLength(sc->Users[roommailalias]);
450                 if (len + 1 > sizeof(buf))
451                         len = sizeof(buf) - 1;
452                 memcpy(buf, ChrPtr(sc->Users[roommailalias]), len);
453                 buf[len] = '\0';
454         }
455         else
456         {
457                 snprintf(buf, sizeof buf, "room_%s@%s",
458                          CCC->room.QRname, CtdlGetConfigStr("c_fqdn"));
459         }
460
461         for (i=0; buf[i]; ++i) {
462                 buf[i] = tolower(buf[i]);
463                 if (isspace(buf[i])) buf[i] = '_';
464         }
465
466
467         /* If we wrote a digest, deliver it and then close it */
468         if (sc->Users[digestrecp] != NULL) {
469                 time_t now = time(NULL);
470                 time_t secs_today = now % (24 * 60 * 60);
471                 long delta = 0;
472
473                 if (last_digest_delivery != 0) {
474                         delta = now - last_digest_delivery;
475                         delta = (24 * 60 * 60) - delta;
476                 }
477
478                 if ((secs_today < 300) && 
479                     (delta < 300))
480                 {
481                         if (sc->digestfp == NULL) {
482                                 sc->digestfp = create_digest_file(&sc->room, 0);
483                         }
484                         if (sc->digestfp != NULL) {
485                                 last_digest_delivery = now;
486                                 fprintf(sc->digestfp,
487                                         " -----------------------------------"
488                                         "------------------------------------"
489                                         "-------\n"
490                                         "You are subscribed to the '%s' "
491                                         "list.\n"
492                                         "To post to the list: %s\n",
493                                         CCC->room.QRname, buf
494                                         );
495                                 network_deliver_digest(sc);     /* deliver */
496                                 remove_digest_file(&sc->room);
497                         }
498                 }
499         }
500         if (sc->digestfp != NULL) {
501                 fclose(sc->digestfp);
502                 sc->digestfp = NULL;
503         }
504
505         /* Now rewrite the netconfig */
506         syslog(LOG_DEBUG, "lastsent was %ld , now it is %ld", lastsent, sc->lastsent);
507         if (sc->lastsent != lastsent)
508         {
509                 OneRoomNetCfg *r;
510
511                 begin_critical_section(S_NETCONFIGS);
512                 r = CtdlGetNetCfgForRoom(sc->room.QRnumber);
513                 r->lastsent = sc->lastsent;
514                 SaveRoomNetConfigFile(r, sc->room.QRnumber);
515                 FreeRoomNetworkStruct(&r);
516                 end_critical_section(S_NETCONFIGS);
517         }
518 }
519
520
521 /*
522  * Check the use table.  This is a list of messages which have recently
523  * arrived on the system.  It is maintained and queried to prevent the same
524  * message from being entered into the database multiple times if it happens
525  * to arrive multiple times by accident.
526  */
527 int network_usetable(struct CtdlMessage *msg)
528 {
529         StrBuf *msgid;
530         struct CitContext *CCC = CC;
531         time_t now;
532
533         /* Bail out if we can't generate a message ID */
534         if ((msg == NULL) || CM_IsEmpty(msg, emessageId))
535         {
536                 return(0);
537         }
538
539         /* Generate the message ID */
540         msgid = NewStrBufPlain(CM_KEY(msg, emessageId));
541         if (haschar(ChrPtr(msgid), '@') == 0) {
542                 StrBufAppendBufPlain(msgid, HKEY("@"), 0);
543                 if (!CM_IsEmpty(msg, eNodeName)) {
544                         StrBufAppendBufPlain(msgid, CM_KEY(msg, eNodeName), 0);
545                 }
546                 else {
547                         FreeStrBuf(&msgid);
548                         return(0);
549                 }
550         }
551         now = time(NULL);
552         if (CheckIfAlreadySeen("Networker Import",
553                                msgid,
554                                now, 0,
555                                eUpdate,
556                                CCC->cs_pid, 0) != 0)
557         {
558                 FreeStrBuf(&msgid);
559                 return(1);
560         }
561         FreeStrBuf(&msgid);
562
563         return(0);
564 }
565
566
567 /*
568  * Process a buffer containing a single message from a single file
569  * from the inbound queue 
570  */
571 void network_process_buffer(char *buffer, long size, HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
572 {
573         long len;
574         StrBuf *Buf = NULL;
575         struct CtdlMessage *msg = NULL;
576         long pos;
577         int field;
578         recptypes *recp = NULL;
579         char target_room[ROOMNAMELEN];
580         struct ser_ret sermsg;
581         char filename[PATH_MAX];
582         FILE *fp;
583         const StrBuf *nexthop = NULL;
584         unsigned char firstbyte;
585         unsigned char lastbyte;
586
587         syslog(LOG_DEBUG, "network_process_buffer() processing %ld bytes", size);
588
589         /* Validate just a little bit.  First byte should be FF and * last byte should be 00. */
590         firstbyte = buffer[0];
591         lastbyte = buffer[size-1];
592         if ( (firstbyte != 255) || (lastbyte != 0) ) {
593                 syslog(LOG_ERR, "Corrupt message ignored.  Length=%ld, firstbyte = %d, lastbyte = %d", size, firstbyte, lastbyte);
594                 return;
595         }
596
597         /* Set default target room to trash */
598         strcpy(target_room, TWITROOM);
599
600         /* Load the message into memory */
601         msg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
602         memset(msg, 0, sizeof(struct CtdlMessage));
603         msg->cm_magic = CTDLMESSAGE_MAGIC;
604         msg->cm_anon_type = buffer[1];
605         msg->cm_format_type = buffer[2];
606
607         for (pos = 3; pos < size; ++pos) {
608                 field = buffer[pos];
609                 len = strlen(buffer + pos + 1);
610                 CM_SetField(msg, field, buffer + pos + 1, len);
611                 pos = pos + len + 1;
612         }
613
614         /* Check for message routing */
615         if (!CM_IsEmpty(msg, eDestination)) {
616                 if (strcasecmp(msg->cm_fields[eDestination], CtdlGetConfigStr("c_nodename"))) {
617
618                         /* route the message */
619                         Buf = NewStrBufPlain(CM_KEY(msg,eDestination));
620                         if (CtdlIsValidNode(&nexthop, 
621                                             NULL, 
622                                             Buf, 
623                                             working_ignetcfg, 
624                                             the_netmap) == 0) 
625                         {
626                                 Netmap_AddMe(msg, HKEY("unknown_user"));
627
628                                 /* serialize the message */
629                                 CtdlSerializeMessage(&sermsg, msg);
630
631                                 /* now send it */
632                                 if (StrLength(nexthop) == 0) {
633                                         nexthop = Buf;
634                                 }
635                                 snprintf(filename,
636                                          sizeof filename,
637                                          "%s/%s@%lx%x",
638                                          ctdl_netout_dir,
639                                          ChrPtr(nexthop),
640                                          time(NULL),
641                                          rand()
642                                 );
643                                 syslog(LOG_DEBUG, "Appending to %s", filename);
644                                 fp = fopen(filename, "ab");
645                                 if (fp != NULL) {
646                                         fwrite(sermsg.ser, sermsg.len, 1, fp);
647                                         fclose(fp);
648                                 }
649                                 else {
650                                         syslog(LOG_ERR, "%s: %s", filename, strerror(errno));
651                                 }
652                                 free(sermsg.ser);
653                                 CM_Free(msg);
654                                 FreeStrBuf(&Buf);
655                                 return;
656                         }
657                         
658                         else {  /* invalid destination node name */
659                                 FreeStrBuf(&Buf);
660
661                                 network_bounce(&msg,
662 "A message you sent could not be delivered due to an invalid destination node"
663 " name.  Please check the address and try sending the message again.\n");
664                                 return;
665
666                         }
667                 }
668         }
669
670         /*
671          * Check to see if we already have a copy of this message, and
672          * abort its processing if so.  (We used to post a warning to Aide>
673          * every time this happened, but the network is now so densely
674          * connected that it's inevitable.)
675          */
676         if (network_usetable(msg) != 0) {
677                 CM_Free(msg);
678                 return;
679         }
680
681         /* Learn network topology from the path */
682         if (!CM_IsEmpty(msg, eNodeName) && !CM_IsEmpty(msg, eMessagePath)) {
683                 NetworkLearnTopology(msg->cm_fields[eNodeName], 
684                                      msg->cm_fields[eMessagePath], 
685                                      the_netmap, 
686                                      netmap_changed);
687         }
688
689         /* Is the sending node giving us a very persuasive suggestion about
690          * which room this message should be saved in?  If so, go with that.
691          */
692         if (!CM_IsEmpty(msg, eRemoteRoom)) {
693                 safestrncpy(target_room, msg->cm_fields[eRemoteRoom], sizeof target_room);
694         }
695
696         /* Otherwise, does it have a recipient?  If so, validate it... */
697         else if (!CM_IsEmpty(msg, eRecipient)) {
698                 recp = validate_recipients(msg->cm_fields[eRecipient], NULL, 0);
699                 if (recp != NULL) if (recp->num_error != 0) {
700                         network_bounce(&msg,
701                                 "A message you sent could not be delivered due to an invalid address.\n"
702                                 "Please check the address and try sending the message again.\n");
703                         free_recipients(recp);
704                         syslog(LOG_DEBUG, "Bouncing message due to invalid recipient address.");
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         FILE *fp;
773         long msgstart = (-1L);
774         long msgend = (-1L);
775         long msgcur = 0L;
776         int ch;
777         int nMessages = 0;
778
779         fp = fopen(filename, "rb");
780         if (fp == NULL) {
781                 syslog(LOG_CRIT, "Error opening %s: %s", filename, strerror(errno));
782                 return;
783         }
784
785         fseek(fp, 0L, SEEK_END);
786         syslog(LOG_INFO, "network: processing %ld bytes from %s", ftell(fp), filename);
787         rewind(fp);
788
789         /* Look for messages in the data stream and break them out */
790         while (ch = getc(fp), ch >= 0) {
791         
792                 if (ch == 255) {
793                         if (msgstart >= 0L) {
794                                 msgend = msgcur - 1;
795                                 network_process_message(fp,
796                                                         msgstart,
797                                                         msgend,
798                                                         working_ignetcfg,
799                                                         the_netmap,
800                                                         netmap_changed);
801                         }
802                         msgstart = msgcur;
803                 }
804
805                 ++msgcur;
806                 nMessages ++;
807         }
808
809         msgend = msgcur - 1;
810         if (msgstart >= 0L) {
811                 network_process_message(fp,
812                                         msgstart,
813                                         msgend,
814                                         working_ignetcfg,
815                                         the_netmap,
816                                         netmap_changed);
817                 nMessages ++;
818         }
819
820         if (nMessages > 0)
821                 syslog(LOG_INFO, "network: processed %d messages in %s", nMessages, filename);
822
823         fclose(fp);
824         unlink(filename);
825 }
826
827
828 /*
829  * Process anything in the inbound queue
830  */
831 void network_do_spoolin(HashList *working_ignetcfg, HashList *the_netmap, int *netmap_changed)
832 {
833         DIR *dp;
834         struct dirent *d;
835         struct dirent *filedir_entry;
836         struct stat statbuf;
837         char filename[PATH_MAX];
838         static time_t last_spoolin_mtime = 0L;
839         int d_type = 0;
840         int d_namelen;
841
842         /*
843          * Check the spoolin directory's modification time.  If it hasn't
844          * been touched, we don't need to scan it.
845          */
846         if (stat(ctdl_netin_dir, &statbuf)) return;
847         if (statbuf.st_mtime == last_spoolin_mtime) {
848                 syslog(LOG_DEBUG, "network: nothing in inbound queue");
849                 return;
850         }
851         last_spoolin_mtime = statbuf.st_mtime;
852         syslog(LOG_DEBUG, "network: processing inbound queue");
853
854         /*
855          * Ok, there's something interesting in there, so scan it.
856          */
857         dp = opendir(ctdl_netin_dir);
858         if (dp == NULL) return;
859
860         d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
861         if (d == NULL) {
862                 closedir(dp);
863                 return;
864         }
865
866         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
867                (filedir_entry != NULL))
868         {
869 #ifdef _DIRENT_HAVE_D_NAMLEN
870                 d_namelen = filedir_entry->d_namlen;
871
872 #else
873                 d_namelen = strlen(filedir_entry->d_name);
874 #endif
875
876 #ifdef _DIRENT_HAVE_D_TYPE
877                 d_type = filedir_entry->d_type;
878 #else
879                 d_type = DT_UNKNOWN;
880 #endif
881                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
882                         continue; /* Ignore backup files... */
883
884                 if ((d_namelen == 1) && 
885                     (filedir_entry->d_name[0] == '.'))
886                         continue;
887
888                 if ((d_namelen == 2) && 
889                     (filedir_entry->d_name[0] == '.') &&
890                     (filedir_entry->d_name[1] == '.'))
891                         continue;
892
893                 if (d_type == DT_UNKNOWN) {
894                         struct stat s;
895                         char path[PATH_MAX];
896
897                         snprintf(path,
898                                  PATH_MAX,
899                                  "%s/%s", 
900                                  ctdl_netin_dir,
901                                  filedir_entry->d_name);
902
903                         if (lstat(path, &s) == 0) {
904                                 d_type = IFTODT(s.st_mode);
905                         }
906                 }
907
908                 switch (d_type)
909                 {
910                 case DT_DIR:
911                         break;
912                 case DT_LNK: /* TODO: check whether its a file or a directory */
913                 case DT_REG:
914                         snprintf(filename, 
915                                 sizeof filename,
916                                 "%s/%s",
917                                 ctdl_netin_dir,
918                                 d->d_name
919                         );
920                         network_process_file(filename,
921                                              working_ignetcfg,
922                                              the_netmap,
923                                              netmap_changed);
924                 }
925         }
926
927         closedir(dp);
928         free(d);
929 }
930
931 /*
932  * Step 1: consolidate files in the outbound queue into one file per neighbor node
933  * Step 2: delete any files in the outbound queue that were for neighbors who no longer exist.
934  */
935 void network_consolidate_spoolout(HashList *working_ignetcfg, HashList *the_netmap)
936 {
937         IOBuffer IOB;
938         FDIOBuffer FDIO;
939         int d_namelen;
940         DIR *dp;
941         struct dirent *d;
942         struct dirent *filedir_entry;
943         const char *pch;
944         char spooloutfilename[PATH_MAX];
945         char filename[PATH_MAX];
946         const StrBuf *nexthop;
947         StrBuf *NextHop;
948         int i;
949         struct stat statbuf;
950         int nFailed = 0;
951         int d_type = 0;
952
953
954         /* Step 1: consolidate files in the outbound queue into one file per neighbor node */
955         d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
956         if (d == NULL)  return;
957
958         dp = opendir(ctdl_netout_dir);
959         if (dp == NULL) {
960                 free(d);
961                 return;
962         }
963
964         NextHop = NewStrBuf();
965         memset(&IOB, 0, sizeof(IOBuffer));
966         memset(&FDIO, 0, sizeof(FDIOBuffer));
967         FDIO.IOB = &IOB;
968
969         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
970                (filedir_entry != NULL))
971         {
972 #ifdef _DIRENT_HAVE_D_NAMLEN
973                 d_namelen = filedir_entry->d_namlen;
974
975 #else
976                 d_namelen = strlen(filedir_entry->d_name);
977 #endif
978
979 #ifdef _DIRENT_HAVE_D_TYPE
980                 d_type = filedir_entry->d_type;
981 #else
982                 d_type = DT_UNKNOWN;
983 #endif
984                 if (d_type == DT_DIR)
985                         continue;
986
987                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
988                         continue; /* Ignore backup files... */
989
990                 if ((d_namelen == 1) && 
991                     (filedir_entry->d_name[0] == '.'))
992                         continue;
993
994                 if ((d_namelen == 2) && 
995                     (filedir_entry->d_name[0] == '.') &&
996                     (filedir_entry->d_name[1] == '.'))
997                         continue;
998
999                 pch = strchr(filedir_entry->d_name, '@');
1000                 if (pch == NULL)
1001                         continue;
1002
1003                 snprintf(filename, 
1004                          sizeof filename,
1005                          "%s/%s",
1006                          ctdl_netout_dir,
1007                          filedir_entry->d_name);
1008
1009                 StrBufPlain(NextHop,
1010                             filedir_entry->d_name,
1011                             pch - filedir_entry->d_name);
1012
1013                 snprintf(spooloutfilename,
1014                          sizeof spooloutfilename,
1015                          "%s/%s",
1016                          ctdl_netout_dir,
1017                          ChrPtr(NextHop));
1018
1019                 syslog(LOG_DEBUG, "Consolidate %s to %s", filename, ChrPtr(NextHop));
1020                 if (CtdlNetworkTalkingTo(SKEY(NextHop), NTT_CHECK)) {
1021                         nFailed++;
1022                         syslog(LOG_DEBUG, "Currently online with %s - skipping for now", ChrPtr(NextHop));
1023                 }
1024                 else {
1025                         size_t dsize;
1026                         size_t fsize;
1027                         int infd, outfd;
1028                         const char *err = NULL;
1029                         CtdlNetworkTalkingTo(SKEY(NextHop), NTT_ADD);
1030
1031                         infd = open(filename, O_RDONLY);
1032                         if (infd == -1) {
1033                                 nFailed++;
1034                                 syslog(LOG_ERR,
1035                                           "failed to open %s for reading due to %s; skipping.",
1036                                           filename, strerror(errno)
1037                                 );
1038                                 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
1039                                 continue;                               
1040                         }
1041                         
1042                         outfd = open(spooloutfilename,
1043                                   O_EXCL|O_CREAT|O_NONBLOCK|O_WRONLY, 
1044                                   S_IRUSR|S_IWUSR);
1045                         if (outfd == -1)
1046                         {
1047                                 outfd = open(spooloutfilename,
1048                                              O_EXCL|O_NONBLOCK|O_WRONLY, 
1049                                              S_IRUSR | S_IWUSR);
1050                         }
1051                         if (outfd == -1) {
1052                                 nFailed++;
1053                                 syslog(LOG_ERR,
1054                                           "failed to open %s for reading due to %s; skipping.",
1055                                           spooloutfilename, strerror(errno)
1056                                 );
1057                                 close(infd);
1058                                 CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
1059                                 continue;
1060                         }
1061
1062                         dsize = lseek(outfd, 0, SEEK_END);
1063                         lseek(outfd, -dsize, SEEK_SET);
1064
1065                         fstat(infd, &statbuf);
1066                         fsize = statbuf.st_size;
1067 /*
1068                         fsize = lseek(infd, 0, SEEK_END);
1069 */                      
1070                         IOB.fd = infd;
1071                         FDIOBufferInit(&FDIO, &IOB, outfd, fsize + dsize);
1072                         FDIO.ChunkSendRemain = fsize;
1073                         FDIO.TotalSentAlready = dsize;
1074                         err = NULL;
1075                         errno = 0;
1076                         do {} while ((FileMoveChunked(&FDIO, &err) > 0) && (err == NULL));
1077                         if (err == NULL) {
1078                                 unlink(filename);
1079                                 syslog(LOG_DEBUG, "Spoolfile %s now "SIZE_T_FMT" KB", spooloutfilename, (dsize + fsize)/1024);
1080                         }
1081                         else {
1082                                 nFailed++;
1083                                 syslog(LOG_ERR, "failed to append to %s [%s]; rolling back..", spooloutfilename, strerror(errno));
1084                                 /* whoops partial append?? truncate spooloutfilename again! */
1085                                 ftruncate(outfd, dsize);
1086                         }
1087                         FDIOBufferDelete(&FDIO);
1088                         close(infd);
1089                         close(outfd);
1090                         CtdlNetworkTalkingTo(SKEY(NextHop), NTT_REMOVE);
1091                 }
1092         }
1093         closedir(dp);
1094
1095         if (nFailed > 0) {
1096                 FreeStrBuf(&NextHop);
1097                 syslog(LOG_INFO, "skipping Spoolcleanup because of %d files unprocessed.", nFailed);
1098
1099                 return;
1100         }
1101
1102         /* Step 2: delete any files in the outbound queue that were for neighbors who no longer exist */
1103         dp = opendir(ctdl_netout_dir);
1104         if (dp == NULL) {
1105                 FreeStrBuf(&NextHop);
1106                 free(d);
1107                 return;
1108         }
1109
1110         while ((readdir_r(dp, d, &filedir_entry) == 0) &&
1111                (filedir_entry != NULL))
1112         {
1113 #ifdef _DIRENT_HAVE_D_NAMLEN
1114                 d_namelen = filedir_entry->d_namlen;
1115
1116 #else
1117                 d_namelen = strlen(filedir_entry->d_name);
1118 #endif
1119
1120 #ifdef _DIRENT_HAVE_D_TYPE
1121                 d_type = filedir_entry->d_type;
1122 #else
1123                 d_type = DT_UNKNOWN;
1124 #endif
1125                 if (d_type == DT_DIR)
1126                         continue;
1127
1128                 if ((d_namelen == 1) && 
1129                     (filedir_entry->d_name[0] == '.'))
1130                         continue;
1131
1132                 if ((d_namelen == 2) && 
1133                     (filedir_entry->d_name[0] == '.') &&
1134                     (filedir_entry->d_name[1] == '.'))
1135                         continue;
1136
1137                 pch = strchr(filedir_entry->d_name, '@');
1138                 if (pch == NULL) /* no @ in name? consolidated file. */
1139                         continue;
1140
1141                 StrBufPlain(NextHop,
1142                             filedir_entry->d_name,
1143                             pch - filedir_entry->d_name);
1144
1145                 snprintf(filename, 
1146                         sizeof filename,
1147                         "%s/%s",
1148                         ctdl_netout_dir,
1149                         filedir_entry->d_name
1150                 );
1151
1152                 i = CtdlIsValidNode(&nexthop,
1153                                     NULL,
1154                                     NextHop,
1155                                     working_ignetcfg,
1156                                     the_netmap);
1157         
1158                 if ( (i != 0) || (StrLength(nexthop) > 0) ) {
1159                         unlink(filename);
1160                 }
1161         }
1162         FreeStrBuf(&NextHop);
1163         free(d);
1164         closedir(dp);
1165 }
1166
1167 void free_spoolcontrol_struct(SpoolControl **sc)
1168 {
1169         free_spoolcontrol_struct_members(*sc);
1170         free(*sc);
1171         *sc = NULL;
1172 }
1173
1174 void free_spoolcontrol_struct_members(SpoolControl *sc)
1175 {
1176         int i;
1177         FreeStrBuf(&sc->RoomInfo);
1178         FreeStrBuf(&sc->ListID);
1179         for (i = 0; i < maxRoomNetCfg; i++)
1180                 FreeStrBuf(&sc->Users[i]);
1181 }
1182
1183
1184
1185 /*
1186  * It's ok if these directories already exist.  Just fail silently.
1187  */
1188 void create_spool_dirs(void) {
1189         if ((mkdir(ctdl_spool_dir, 0700) != 0) && (errno != EEXIST))
1190                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_spool_dir, strerror(errno));
1191         if (chown(ctdl_spool_dir, CTDLUID, (-1)) != 0)
1192                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_spool_dir, strerror(errno));
1193         if ((mkdir(ctdl_netin_dir, 0700) != 0) && (errno != EEXIST))
1194                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netin_dir, strerror(errno));
1195         if (chown(ctdl_netin_dir, CTDLUID, (-1)) != 0)
1196                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netin_dir, strerror(errno));
1197         if ((mkdir(ctdl_nettmp_dir, 0700) != 0) && (errno != EEXIST))
1198                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_nettmp_dir, strerror(errno));
1199         if (chown(ctdl_nettmp_dir, CTDLUID, (-1)) != 0)
1200                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_nettmp_dir, strerror(errno));
1201         if ((mkdir(ctdl_netout_dir, 0700) != 0) && (errno != EEXIST))
1202                 syslog(LOG_EMERG, "unable to create directory [%s]: %s", ctdl_netout_dir, strerror(errno));
1203         if (chown(ctdl_netout_dir, CTDLUID, (-1)) != 0)
1204                 syslog(LOG_EMERG, "unable to set the access rights for [%s]: %s", ctdl_netout_dir, strerror(errno));
1205 }
1206
1207 /*
1208  * Module entry point
1209  */
1210 CTDL_MODULE_INIT(network_spool)
1211 {
1212         if (!threading)
1213         {
1214                 CtdlREGISTERRoomCfgType(subpending,       ParseSubPendingLine,   0, 5, SerializeGeneric,  DeleteGenericCfgLine); /// todo: move this to mailinglist manager
1215                 CtdlREGISTERRoomCfgType(unsubpending,     ParseUnSubPendingLine, 0, 4, SerializeGeneric,  DeleteGenericCfgLine); /// todo: move this to mailinglist manager
1216                 CtdlREGISTERRoomCfgType(lastsent,         ParseLastSent,         1, 1, SerializeLastSent, DeleteLastSent);
1217                 CtdlREGISTERRoomCfgType(ignet_push_share, ParseGeneric,          0, 2, SerializeGeneric,  DeleteGenericCfgLine); // [remotenode|remoteroomname (optional)]// todo: move this to the ignet client
1218                 CtdlREGISTERRoomCfgType(listrecp,         ParseGeneric,          0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1219                 CtdlREGISTERRoomCfgType(digestrecp,       ParseGeneric,          0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1220                 CtdlREGISTERRoomCfgType(participate,      ParseGeneric,          0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1221                 CtdlREGISTERRoomCfgType(roommailalias,    ParseRoomAlias,        0, 1, SerializeGeneric,  DeleteGenericCfgLine);
1222
1223                 create_spool_dirs();
1224 //////todo              CtdlRegisterCleanupHook(destroy_network_queue_room);
1225         }
1226         return "network_spool";
1227 }