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