0c90b46cfdd952da6e5bf88f2abc188f3d3e240f
[citadel.git] / citadel / modules / network / serv_netmail.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 <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 #include "ctdl_module.h"
79 #include "netspool.h"
80 #include "netmail.h"
81
82 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc, const char *RoomName);
83
84 void aggregate_recipients(StrBuf **recps, RoomNetCfg Which, OneRoomNetCfg *OneRNCfg, long nSegments)
85 {
86         int i;
87         size_t recps_len = 0;
88         RoomNetCfgLine *nptr;
89         struct CitContext *CCC = CC;
90
91         *recps = NULL;
92         /*
93          * Figure out how big a buffer we need to allocate
94          */
95         for (nptr = OneRNCfg->NetConfigs[Which]; nptr != NULL; nptr = nptr->next) {
96                 recps_len = recps_len + StrLength(nptr->Value[0]) + 2;
97         }
98
99         /* Nothing todo... */
100         if (recps_len == 0)
101                 return;
102
103         *recps = NewStrBufPlain(NULL, recps_len);
104
105         if (*recps == NULL) {
106                 QN_syslog(LOG_EMERG,
107                           "Cannot allocate %ld bytes for recps...\n",
108                           (long)recps_len);
109                 abort();
110         }
111
112         /* Each recipient */
113         for (nptr = OneRNCfg->NetConfigs[Which]; nptr != NULL; nptr = nptr->next) {
114                 if (nptr != OneRNCfg->NetConfigs[Which]) {
115                         for (i = 0; i < nSegments; i++)
116                                 StrBufAppendBufPlain(*recps, HKEY(","), i);
117                 }
118                 StrBufAppendBuf(*recps, nptr->Value[0], 0);
119                 if (Which == ignet_push_share)
120                 {
121                         StrBufAppendBufPlain(*recps, HKEY(","), 0);
122                         StrBufAppendBuf(*recps, nptr->Value[1], 0);
123
124                 }
125         }
126 }
127
128 static void ListCalculateSubject(struct CtdlMessage *msg)
129 {
130         struct CitContext *CCC = CC;
131         StrBuf *Subject, *FlatSubject;
132         int rlen;
133         char *pCh;
134
135         if (CM_IsEmpty(msg, eMsgSubject)) {
136                 Subject = NewStrBufPlain(HKEY("(no subject)"));
137         }
138         else {
139                 Subject = NewStrBufPlain(CM_KEY(msg, eMsgSubject));
140         }
141         FlatSubject = NewStrBufPlain(NULL, StrLength(Subject));
142         StrBuf_RFC822_to_Utf8(FlatSubject, Subject, NULL, NULL);
143
144         rlen = strlen(CCC->room.QRname);
145         pCh  = strstr(ChrPtr(FlatSubject), CCC->room.QRname);
146         if ((pCh == NULL) ||
147             (*(pCh + rlen) != ']') ||
148             (pCh == ChrPtr(FlatSubject)) ||
149             (*(pCh - 1) != '[')
150                 )
151         {
152                 StrBuf *tmp;
153                 StrBufPlain(Subject, HKEY("["));
154                 StrBufAppendBufPlain(Subject,
155                                      CCC->room.QRname,
156                                      rlen, 0);
157                 StrBufAppendBufPlain(Subject, HKEY("] "), 0);
158                 StrBufAppendBuf(Subject, FlatSubject, 0);
159                 /* so we can free the right one swap them */
160                 tmp = Subject;
161                 Subject = FlatSubject;
162                 FlatSubject = tmp;
163                 StrBufRFC2047encode(&Subject, FlatSubject);
164         }
165
166         CM_SetAsFieldSB(msg, eMsgSubject, &Subject);
167
168         FreeStrBuf(&FlatSubject);
169 }
170
171 /*
172  * Deliver digest messages
173  */
174 void network_deliver_digest(SpoolControl *sc)
175 {
176         struct CitContext *CCC = CC;
177         long len;
178         char buf[SIZ];
179         char *pbuf;
180         struct CtdlMessage *msg = NULL;
181         long msglen;
182         recptypes *valid;
183         char bounce_to[256];
184
185         if (sc->Users[digestrecp] == NULL)
186                 return;
187
188         msg = malloc(sizeof(struct CtdlMessage));
189         memset(msg, 0, sizeof(struct CtdlMessage));
190         msg->cm_magic = CTDLMESSAGE_MAGIC;
191         msg->cm_format_type = FMT_RFC822;
192         msg->cm_anon_type = MES_NORMAL;
193
194         CM_SetFieldLONG(msg, eTimestamp, time(NULL));
195         CM_SetField(msg, eAuthor, CCC->room.QRname, strlen(CCC->room.QRname));
196         len = snprintf(buf, sizeof buf, "[%s]", CCC->room.QRname);
197         CM_SetField(msg, eMsgSubject, buf, len);
198
199         CM_SetField(msg, erFc822Addr, SKEY(sc->Users[roommailalias]));
200         CM_SetField(msg, eRecipient, SKEY(sc->Users[roommailalias]));
201
202         /* Set the 'List-ID' header */
203         CM_SetField(msg, eListID, SKEY(sc->ListID));
204
205         /*
206          * Go fetch the contents of the digest
207          */
208         fseek(sc->digestfp, 0L, SEEK_END);
209         msglen = ftell(sc->digestfp);
210
211         pbuf = malloc(msglen + 1);
212         fseek(sc->digestfp, 0L, SEEK_SET);
213         fread(pbuf, (size_t)msglen, 1, sc->digestfp);
214         pbuf[msglen] = '\0';
215         CM_SetAsField(msg, eMesageText, &pbuf, msglen);
216
217         /* Now generate the delivery instructions */
218
219         /* Where do we want bounces and other noise to be heard?
220          * Surely not the list members! */
221         snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", CtdlGetConfigStr("c_fqdn"));
222
223         /* Now submit the message */
224         valid = validate_recipients(ChrPtr(sc->Users[digestrecp]), NULL, 0);
225         if (valid != NULL) {
226                 valid->bounce_to = strdup(bounce_to);
227                 valid->envelope_from = strdup(bounce_to);
228                 CtdlSubmitMsg(msg, valid, NULL, 0);
229         }
230         CM_Free(msg);
231         free_recipients(valid);
232 }
233
234
235 void network_process_digest(SpoolControl *sc, struct CtdlMessage *omsg, long *delete_after_send)
236 {
237
238         struct CtdlMessage *msg = NULL;
239
240         if (sc->Users[digestrecp] == NULL)
241                 return;
242
243         /* If there are digest recipients, we have to build a digest */
244         if (sc->digestfp == NULL) {
245                 
246                 sc->digestfp = create_digest_file(&sc->room, 1);
247
248                 if (sc->digestfp == NULL)
249                         return;
250
251                 sc->haveDigest = ftell(sc->digestfp) > 0;
252                 if (!sc->haveDigest) {
253                         fprintf(sc->digestfp, "Content-type: text/plain\n\n");
254                 }
255                 sc->haveDigest = 1;
256         }
257
258         msg = CM_Duplicate(omsg);
259         if (msg != NULL) {
260                 sc->haveDigest = 1;
261                 fprintf(sc->digestfp,
262                         " -----------------------------------"
263                         "------------------------------------"
264                         "-------\n");
265                 fprintf(sc->digestfp, "From: ");
266                 if (!CM_IsEmpty(msg, eAuthor)) {
267                         fprintf(sc->digestfp,
268                                 "%s ",
269                                 msg->cm_fields[eAuthor]);
270                 }
271                 if (!CM_IsEmpty(msg, erFc822Addr)) {
272                         fprintf(sc->digestfp,
273                                 "<%s> ",
274                                 msg->cm_fields[erFc822Addr]);
275                 }
276                 else if (!CM_IsEmpty(msg, eNodeName)) {
277                         fprintf(sc->digestfp,
278                                 "@%s ",
279                                 msg->cm_fields[eNodeName]);
280                 }
281                 fprintf(sc->digestfp, "\n");
282                 if (!CM_IsEmpty(msg, eMsgSubject)) {
283                         fprintf(sc->digestfp,
284                                 "Subject: %s\n",
285                                 msg->cm_fields[eMsgSubject]);
286                 }
287
288                 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
289
290                 safestrncpy(CC->preferred_formats,
291                             "text/plain",
292                             sizeof CC->preferred_formats);
293
294                 CtdlOutputPreLoadedMsg(msg,
295                                        MT_CITADEL,
296                                        HEADERS_NONE,
297                                        0, 0, 0);
298
299                 StrBufTrim(CC->redirect_buffer);
300                 fwrite(HKEY("\n"), 1, sc->digestfp);
301                 fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
302                 fwrite(HKEY("\n"), 1, sc->digestfp);
303
304                 FreeStrBuf(&CC->redirect_buffer);
305
306                 sc->num_msgs_spooled += 1;
307                 CM_Free(msg);
308         }
309 }
310
311
312 void network_process_list(SpoolControl *sc, struct CtdlMessage *omsg, long *delete_after_send)
313 {
314         struct CtdlMessage *msg = NULL;
315
316         /*
317          * Process mailing list recipients
318          */
319         if (sc->Users[listrecp] == NULL)
320                 return;
321
322         /* create our own copy of the message.
323          *  We're going to need to modify it
324          * in order to insert the [list name] in it, etc.
325          */
326
327         msg = CM_Duplicate(omsg);
328
329
330         CM_SetField(msg, eReplyTo, SKEY(sc->Users[roommailalias]));
331
332         /* if there is no other recipient, Set the recipient
333          * of the list message to the email address of the
334          * room itself.
335          */
336         if (CM_IsEmpty(msg, eRecipient))
337         {
338                 CM_SetField(msg, eRecipient, SKEY(sc->Users[roommailalias]));
339         }
340
341         /* Set the 'List-ID' header */
342         CM_SetField(msg, eListID, SKEY(sc->ListID));
343
344
345         /* Prepend "[List name]" to the subject */
346         ListCalculateSubject(msg);
347
348         /* Handle delivery */
349         network_deliver_list(msg, sc, CC->room.QRname);
350         CM_Free(msg);
351 }
352
353 /*
354  * Deliver list messages to everyone on the list ... efficiently
355  */
356 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc, const char *RoomName)
357 {
358         recptypes *valid;
359         char bounce_to[256];
360
361         /* Don't do this if there were no recipients! */
362         if (sc->Users[listrecp] == NULL)
363                 return;
364
365         /* Now generate the delivery instructions */
366
367         /* Where do we want bounces and other noise to be heard?
368          *  Surely not the list members! */
369         snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", CtdlGetConfigStr("c_fqdn"));
370
371         /* Now submit the message */
372         valid = validate_recipients(ChrPtr(sc->Users[listrecp]), NULL, 0);
373         if (valid != NULL) {
374                 valid->bounce_to = strdup(bounce_to);
375                 valid->envelope_from = strdup(bounce_to);
376                 valid->sending_room = strdup(RoomName);
377                 CtdlSubmitMsg(msg, valid, NULL, 0);
378                 free_recipients(valid);
379         }
380         /* Do not call CM_Free(msg) here; the caller will free it. */
381 }
382
383
384 void network_process_participate(SpoolControl *sc, struct CtdlMessage *omsg, long *delete_after_send)
385 {
386         struct CtdlMessage *msg = NULL;
387         int ok_to_participate = 0;
388         StrBuf *Buf = NULL;
389         recptypes *valid;
390
391         /*
392          * Process client-side list participations for this room
393          */
394         if (sc->Users[participate] == NULL)
395                 return;
396
397         msg = CM_Duplicate(omsg);
398
399         /* Only send messages which originated on our own
400          * Citadel network, otherwise we'll end up sending the
401          * remote mailing list's messages back to it, which
402          * is rude...
403          */
404         ok_to_participate = 0;
405         if (!CM_IsEmpty(msg, eNodeName)) {
406                 if (!strcasecmp(msg->cm_fields[eNodeName], CtdlGetConfigStr("c_nodename")))
407                 {
408                         ok_to_participate = 1;
409                 }
410                 
411                 Buf = NewStrBufPlain(CM_KEY(msg, eNodeName));
412                 if (CtdlIsValidNode(NULL,
413                                     NULL,
414                                     Buf,
415                                     sc->working_ignetcfg,
416                                     sc->the_netmap) == 0)
417                 {
418                         ok_to_participate = 1;
419                 }
420         }
421         if (ok_to_participate)
422         {
423                 /* Replace the Internet email address of the
424                  * actual author with the email address of the
425                  * room itself, so the remote listserv doesn't
426                  * reject us.
427                  */
428                 CM_SetField(msg, erFc822Addr, SKEY(sc->Users[roommailalias]));
429
430                 valid = validate_recipients(ChrPtr(sc->Users[participate]) , NULL, 0);
431
432                 CM_SetField(msg, eRecipient, SKEY(sc->Users[roommailalias]));
433                 CtdlSubmitMsg(msg, valid, "", 0);
434                 free_recipients(valid);
435         }
436         FreeStrBuf(&Buf);
437         CM_Free(msg);
438 }
439
440 void network_process_ignetpush(SpoolControl *sc, struct CtdlMessage *omsg, long *delete_after_send)
441 {
442         StrBuf *Recipient;
443         StrBuf *RemoteRoom;
444         const char *Pos = NULL;
445         struct CtdlMessage *msg = NULL;
446         struct CitContext *CCC = CC;
447         struct ser_ret sermsg;
448         char buf[SIZ];
449         char filename[PATH_MAX];
450         FILE *fp;
451         StrBuf *Buf = NULL;
452         int i;
453         int bang = 0;
454         int send = 1;
455
456         if (sc->Users[ignet_push_share] == NULL)
457                 return;
458
459         /*
460          * Process IGnet push shares
461          */
462         msg = CM_Duplicate(omsg);
463
464         /* Prepend our node name to the Path field whenever
465          * sending a message to another IGnet node
466          */
467         Netmap_AddMe(msg, HKEY("username"));
468
469         /*
470          * Determine if this message is set to be deleted
471          * after sending out on the network
472          */
473         if (!CM_IsEmpty(msg, eSpecialField)) {
474                 if (!strcasecmp(msg->cm_fields[eSpecialField], "CANCEL")) {
475                         *delete_after_send = 1;
476                 }
477         }
478
479         /* Now send it to every node */
480         Recipient = NewStrBufPlain(NULL, StrLength(sc->Users[ignet_push_share]));
481         RemoteRoom = NewStrBufPlain(NULL, StrLength(sc->Users[ignet_push_share]));
482         while ((Pos != StrBufNOTNULL) &&
483                StrBufExtract_NextToken(Recipient, sc->Users[ignet_push_share], &Pos, ','))
484         {
485                 StrBufExtract_NextToken(RemoteRoom, sc->Users[ignet_push_share], &Pos, ',');
486                 send = 1;
487                 NewStrBufDupAppendFlush(&Buf, Recipient, NULL, 1);
488                         
489                 /* Check for valid node name */
490                 if (CtdlIsValidNode(NULL,
491                                     NULL,
492                                     Buf,
493                                     sc->working_ignetcfg,
494                                     sc->the_netmap) != 0)
495                 {
496                         QN_syslog(LOG_ERR,
497                                   "Invalid node <%s>\n",
498                                   ChrPtr(Recipient));
499                         
500                         send = 0;
501                 }
502                 
503                 /* Check for split horizon */
504                 QN_syslog(LOG_DEBUG, "Path is %s\n", msg->cm_fields[eMessagePath]);
505                 bang = num_tokens(msg->cm_fields[eMessagePath], '!');
506                 if (bang > 1) {
507                         for (i=0; i<(bang-1); ++i) {
508                                 extract_token(buf,
509                                               msg->cm_fields[eMessagePath],
510                                               i, '!',
511                                               sizeof buf);
512
513                                 QN_syslog(LOG_DEBUG, "Compare <%s> to <%s>\n",
514                                           buf, ChrPtr(Recipient)) ;
515                                 if (!strcasecmp(buf, ChrPtr(Recipient))) {
516                                         send = 0;
517                                         break;
518                                 }
519                         }
520                         
521                         QN_syslog(LOG_INFO,
522                                   " %sSending to %s\n",
523                                   (send)?"":"Not ",
524                                   ChrPtr(Recipient));
525                 }
526                 
527                 /* Send the message */
528                 if (send == 1)
529                 {
530                         /*
531                          * Force the message to appear in the correct
532                          * room on the far end by setting the C field
533                          * correctly
534                          */
535                         if (StrLength(RemoteRoom) > 0) {
536                                 CM_SetField(msg, eRemoteRoom, SKEY(RemoteRoom));
537                         }
538                         else {
539                                 CM_SetField(msg, eRemoteRoom, CCC->room.QRname, strlen(CCC->room.QRname));
540                         }
541                         
542                         /* serialize it for transmission */
543                         CtdlSerializeMessage(&sermsg, msg);
544                         if (sermsg.len > 0) {
545                                 
546                                 /* write it to a spool file */
547                                 snprintf(filename,
548                                          sizeof(filename),
549                                          "%s/%s@%lx%x",
550                                          ctdl_netout_dir,
551                                          ChrPtr(Recipient),
552                                          time(NULL),
553                                          rand()
554                                         );
555                                         
556                                 QN_syslog(LOG_DEBUG,
557                                           "Appending to %s\n",
558                                           filename);
559                                 
560                                 fp = fopen(filename, "ab");
561                                 if (fp != NULL) {
562                                         fwrite(sermsg.ser,
563                                                sermsg.len, 1, fp);
564                                         fclose(fp);
565                                 }
566                                 else {
567                                         QN_syslog(LOG_ERR,
568                                                   "%s: %s\n",
569                                                   filename,
570                                                   strerror(errno));
571                                 }
572
573                                 /* free the serialized version */
574                                 free(sermsg.ser);
575                         }
576                 }
577         }
578         FreeStrBuf(&Buf);
579         FreeStrBuf(&Recipient);
580         FreeStrBuf(&RemoteRoom);
581         CM_Free(msg);
582 }
583
584
585 /*
586  * Spools out one message from the list.
587  */
588 void network_spool_msg(long msgnum, void *userdata)
589 {
590         struct CtdlMessage *msg = NULL;
591         long delete_after_send = 0;     /* Set to 1 to delete after spooling */
592         SpoolControl *sc;
593
594         sc = (SpoolControl *)userdata;
595         msg = CtdlFetchMessage(msgnum, 1, 1);
596
597         if (msg == NULL)
598         {
599                 syslog(LOG_ERR, "failed to load Message <%ld> from disk\n", msgnum);
600                 return;
601         }
602         network_process_list(sc, msg, &delete_after_send);
603         network_process_digest(sc, msg, &delete_after_send);
604         network_process_participate(sc, msg, &delete_after_send);
605         network_process_ignetpush(sc, msg, &delete_after_send);
606         
607         CM_Free(msg);
608
609         /* update lastsent */
610         sc->lastsent = msgnum;
611
612         /* Delete this message if delete-after-send is set */
613         if (delete_after_send) {
614                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
615         }
616 }