38b6ef1fa19cd1e65ac25dc16f9be541255d5aff
[citadel.git] / citadel / modules / extnotify / extnotify_main.c
1 /*
2  * extnotify_main.c
3  * Mathew McBride
4  *
5  * This module implements an external pager hook for when notifcation
6  * of a new email is wanted.
7  *
8  * Based on bits of serv_funambol
9  * Contact: <matt@mcbridematt.dhs.org> / <matt@comalies>
10  *
11  * Copyright (c) 2008-2015
12  *
13  * This program is open source software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 3 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  */
23
24
25 #include "sysdep.h"
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <stdio.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <pwd.h>
32 #include <errno.h>
33 #include <sys/types.h>
34
35 #if TIME_WITH_SYS_TIME
36 # include <sys/time.h>
37 # include <time.h>
38 #else
39 # if HAVE_SYS_TIME_H
40 #  include <sys/time.h>
41 # else
42 #  include <time.h>
43 # endif
44 #endif
45
46 #include <sys/wait.h>
47 #include <string.h>
48 #include <limits.h>
49 #include <sys/socket.h>
50 #include <libcitadel.h>
51 #include "citadel.h"
52 #include "server.h"
53 #include "citserver.h"
54 #include "support.h"
55 #include "config.h"
56 #include "control.h"
57 #include "user_ops.h"
58 #include "database.h"
59 #include "msgbase.h"
60 #include "internet_addressing.h"
61 #include "domain.h"
62 #include "clientsocket.h"
63 #include "event_client.h"
64 #include "extnotify.h"
65 #include "ctdl_module.h"
66
67 struct CitContext extnotify_queue_CC;
68
69 void ExtNotify_PutErrorMessage(NotifyContext *Ctx, StrBuf *ErrMsg)
70 {
71         int nNext;
72         if (Ctx->NotifyErrors == NULL)
73                 Ctx->NotifyErrors = NewHash(1, Flathash);
74
75         nNext = GetCount(Ctx->NotifyErrors) + 1;
76         Put(Ctx->NotifyErrors,
77             (char*)&nNext,
78             sizeof(int),
79             ErrMsg,
80             HFreeStrBuf);
81 }
82
83 StrBuf* GetNHBuf(int i, int allocit, StrBuf **NotifyHostList)
84 {
85         if ((NotifyHostList[i] == NULL) && (allocit != 0))
86                 NotifyHostList[i] = NewStrBuf();
87         return NotifyHostList[i];
88 }
89
90
91 int GetNotifyHosts(NotifyContext *Ctx)
92 {
93         char NotifyHostsBuf[SIZ];
94         StrBuf *Host;
95         StrBuf *File;
96         StrBuf *NotifyBuf;
97         int notify;
98         const char *pchs, *pche;
99         const char *NextHost = NULL;
100
101         /* See if we have any Notification Hosts configured */
102         Ctx->nNotifyHosts = get_hosts(NotifyHostsBuf, "notify");
103         if (Ctx->nNotifyHosts < 1)
104                 return 0;
105
106         Ctx->NotifyHostList = malloc(sizeof(StrBuf*) *
107                                      2 *
108                                      (Ctx->nNotifyHosts + 1));
109         memset(Ctx->NotifyHostList, 0,
110                sizeof(StrBuf*) * 2 * (Ctx->nNotifyHosts + 1));
111
112         NotifyBuf = NewStrBufPlain(NotifyHostsBuf, -1);
113         /* get all configured notifiers's */
114         for (notify=0; notify<Ctx->nNotifyHosts; notify++) {
115
116                 Host = GetNHBuf(notify * 2, 1, Ctx->NotifyHostList);
117                 StrBufExtract_NextToken(Host, NotifyBuf, &NextHost, '|');
118                 pchs = ChrPtr(Host);
119                 pche = strchr(pchs, ':');
120                 if (pche == NULL) {
121                         syslog(LOG_ERR,
122                                "extnotify: filename of notification "
123                                "template not found in %s.\n",
124                                pchs);
125                         continue;
126                 }
127                 File = GetNHBuf(notify * 2 + 1, 1, Ctx->NotifyHostList);
128                 StrBufPlain(File, pchs, pche - pchs);
129                 StrBufCutLeft(Host, pche - pchs + 1);
130         }
131         FreeStrBuf(&NotifyBuf);
132         return Ctx->nNotifyHosts;
133 }
134
135
136
137 /*! \brief Get configuration message for pager/funambol system from the
138  *                      users "My Citadel Config" room
139  */
140 eNotifyType extNotify_getConfigMessage(char *username,
141                                        char **PagerNumber,
142                                        char **FreeMe)
143 {
144         struct ctdlroom qrbuf; // scratch for room
145         struct ctdluser user; // ctdl user instance
146         char configRoomName[ROOMNAMELEN];
147         struct CtdlMessage *msg = NULL;
148         struct cdbdata *cdbfr;
149         long *msglist = NULL;
150         int num_msgs = 0;
151         int a;
152         char *configMsg;
153         long clen;
154         char *pch;
155
156         // Get the user
157         CtdlGetUser(&user, username);
158
159         CtdlMailboxName(configRoomName,
160                         sizeof(configRoomName),
161                         &user,
162                         USERCONFIGROOM);
163         // Fill qrbuf
164         CtdlGetRoom(&qrbuf, configRoomName);
165         /* Do something really, really stoopid here. Raid the room on ourselves,
166          * loop through the messages manually and find it. I don't want
167          * to use a CtdlForEachMessage callback here, as we would be
168          * already in one */
169         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
170         if (cdbfr != NULL) {
171                 msglist = (long *) cdbfr->ptr;
172                 cdbfr->ptr = NULL;
173                         /* CtdlForEachMessage() now owns this memory */
174                 num_msgs = cdbfr->len / sizeof(long);
175                 cdb_free(cdbfr);
176         } else {
177                 syslog(LOG_DEBUG,
178                        "extNotify_getConfigMessage: "
179                        "No config messages found\n");
180                 return eNone;   /* No messages at all?  No further action. */
181         }
182         for (a = 0; a < num_msgs; ++a) {
183                 msg = CtdlFetchMessage(msglist[a], 1, 1);
184                 if (msg != NULL) {
185                         if (!CM_IsEmpty(msg, eMsgSubject) &&
186                             (strncasecmp(msg->cm_fields[eMsgSubject],
187                                          PAGER_CONFIG_MESSAGE,
188                                          strlen(PAGER_CONFIG_MESSAGE)) == 0))
189                         {
190                                 break;
191                         }
192                         CM_Free(msg);
193                         msg = NULL;
194                 }
195         }
196
197         free(msglist);
198         if (msg == NULL)
199                 return eNone;
200
201         // Do a simple string search to see if 'funambol' is selected as the
202         // type. This string would be at the very top of the message contents.
203
204         CM_GetAsField(msg, eMesageText, &configMsg, &clen);
205         CM_Free(msg);
206
207         /* here we would find the pager number... */
208         pch = strchr(configMsg, '\n');
209         if (pch != NULL)
210         {
211                 *pch = '\0';
212                 pch ++;
213         }
214
215         /* Check to see if:
216          * 1. The user has configured paging / They have and disabled it
217          * AND 2. There is an external pager program
218          * 3. A Funambol server has been entered
219          *
220          */
221         if (!strncasecmp(configMsg, "none", 4))
222         {
223                 free(configMsg);
224                 return eNone;
225         }
226
227         if (!strncasecmp(configMsg, HKEY(PAGER_CONFIG_HTTP)))
228         {
229                 free(configMsg);
230                 return eHttpMessages;
231         }
232         if (!strncasecmp(configMsg, HKEY(FUNAMBOL_CONFIG_TEXT)))
233         {
234                 free(configMsg);
235                 return eFunambol;
236         }
237         else if (!strncasecmp(configMsg, HKEY(PAGER_CONFIG_SYSTEM)))
238         {
239                 // whats the pager number?
240                 if (!pch || (*pch == '\0'))
241                 {
242                         free(configMsg);
243
244                         return eNone;
245                 }
246                 while (isspace(*pch))
247                         pch ++;
248                 *PagerNumber = pch;
249                 while (isdigit(*pch) || (*pch == '+'))
250                         pch++;
251                 *pch = '\0';
252                 *FreeMe = configMsg;
253                 return eTextMessage;
254         }
255
256         free(configMsg);
257         return eNone;
258 }
259
260
261 /*
262  * Process messages in the external notification queue
263  */
264 void process_notify(long NotifyMsgnum, void *usrdata)
265 {
266         NotifyContext *Ctx;
267         long msgnum = 0;
268         long todelete[1];
269         char *pch;
270         struct CtdlMessage *msg;
271         eNotifyType Type;
272         char remoteurl[SIZ];
273         char *FreeMe = NULL;
274         char *PagerNo;
275
276         Ctx = (NotifyContext*) usrdata;
277
278         msg = CtdlFetchMessage(NotifyMsgnum, 1, 1);
279         if (!CM_IsEmpty(msg, eExtnotify))
280         {
281                 Type = extNotify_getConfigMessage(
282                         msg->cm_fields[eExtnotify],
283                         &PagerNo,
284                         &FreeMe);
285
286                 pch = strstr(msg->cm_fields[eMesageText], "msgid|");
287                 if (pch != NULL)
288                         msgnum = atol(pch + sizeof("msgid"));
289
290                 switch (Type)
291                 {
292                 case eFunambol:
293                         snprintf(remoteurl, SIZ, "http://%s@%s:%d/%s",
294                                  CtdlGetConfigStr("c_funambol_auth"),
295                                  CtdlGetConfigStr("c_funambol_host"),
296                                  CtdlGetConfigInt("c_funambol_port"),
297                                  FUNAMBOL_WS);
298
299                         notify_http_server(remoteurl,
300                                            file_funambol_msg,
301                                            strlen(file_funambol_msg),/*GNA*/
302                                            msg->cm_fields[eExtnotify],
303                                            msg->cm_fields[emessageId],
304                                            msgnum,
305                                            NULL);
306                         break;
307                 case eHttpMessages:
308                 {
309                         int i = 0;
310                         StrBuf *URL;
311                         char URLBuf[SIZ];
312                         StrBuf *File;
313                         StrBuf *FileBuf = NewStrBuf();
314
315                         for (i = 0; i < Ctx->nNotifyHosts; i++)
316                         {
317
318                                 URL = GetNHBuf(i*2, 0, Ctx->NotifyHostList);
319                                 if (URL==NULL) break;
320                                 File = GetNHBuf(i*2 + 1, 0,
321                                                 Ctx->NotifyHostList);
322                                 if (File==NULL) break;
323
324                                 if (StrLength(File)>0)
325                                         StrBufPrintf(FileBuf, "%s/%s",
326                                                      ctdl_shared_dir,
327                                                      ChrPtr(File));
328                                 else
329                                         FlushStrBuf(FileBuf);
330                                 memcpy(URLBuf, ChrPtr(URL), StrLength(URL) + 1);
331
332                                 notify_http_server(URLBuf,
333                                                    ChrPtr(FileBuf),
334                                                    StrLength(FileBuf),
335                                                    msg->cm_fields[eExtnotify],
336                                                    msg->cm_fields[emessageId],
337                                                    msgnum,
338                                                    NULL);
339                         }
340                         FreeStrBuf(&FileBuf);
341                 }
342                 break;
343                 case eTextMessage:
344                 {
345                         int commandSiz;
346                         char *command;
347
348                         commandSiz = sizeof(CtdlGetConfigStr("c_pager_program")) +
349                                 strlen(PagerNo) +
350                                 msg->cm_lengths[eExtnotify] + 5;
351
352                         command = malloc(commandSiz);
353
354                         snprintf(command,
355                                  commandSiz,
356                                  "%s %s -u %s",
357                                  CtdlGetConfigStr("c_pager_program"),
358                                  PagerNo,
359                                  msg->cm_fields[eExtnotify]);
360
361                         system(command);
362                         free(command);
363                 }
364                 break;
365                 case eNone:
366                         break;
367                 }
368         }
369         if (FreeMe != NULL)
370                 free(FreeMe);
371         CM_Free(msg);
372         todelete[0] = NotifyMsgnum;
373         CtdlDeleteMessages(FNBL_QUEUE_ROOM, todelete, 1, "");
374 }
375
376 /*!
377  * \brief Run through the pager room queue
378  * Checks to see what notification option the user has set
379  */
380 void do_extnotify_queue(void)
381 {
382         NotifyContext Ctx;
383         static int doing_queue = 0;
384         int i = 0;
385
386         /*
387          * This is a simple concurrency check to make sure only one queue run
388          * is done at a time.  We could do this with a mutex, but since we
389          * don't really require extremely fine granularity here, we'll do it
390          * with a static variable instead.
391          */
392         if (IsEmptyStr(CtdlGetConfigStr("c_pager_program")) &&
393             IsEmptyStr(CtdlGetConfigStr("c_funambol_host")))
394         {
395                 syslog(LOG_ERR,
396                        "No external notifiers configured on system/user\n");
397                 return;
398         }
399
400         if (doing_queue)
401                 return;
402
403         doing_queue = 1;
404
405         become_session(&extnotify_queue_CC);
406
407         pthread_setspecific(MyConKey, (void *)&extnotify_queue_CC);
408
409         /*
410          * Go ahead and run the queue
411          */
412         syslog(LOG_DEBUG, "serv_extnotify: processing notify queue\n");
413
414         memset(&Ctx, 0, sizeof(NotifyContext));
415         if ((GetNotifyHosts(&Ctx) > 0) &&
416             (CtdlGetRoom(&CC->room, FNBL_QUEUE_ROOM) != 0))
417         {
418                 syslog(LOG_ERR, "Cannot find room <%s>\n", FNBL_QUEUE_ROOM);
419                 if (Ctx.nNotifyHosts > 0)
420                 {
421                         for (i = 0; i < Ctx.nNotifyHosts * 2; i++)
422                                 FreeStrBuf(&Ctx.NotifyHostList[i]);
423                         free(Ctx.NotifyHostList);
424                 }
425                 return;
426         }
427         CtdlForEachMessage(MSGS_ALL, 0L, NULL,
428                            SPOOLMIME, NULL, process_notify, &Ctx);
429         syslog(LOG_DEBUG, "serv_extnotify: queue run completed\n");
430         doing_queue = 0;
431         if (Ctx.nNotifyHosts > 0)
432         {
433                 for (i = 0; i < Ctx.nNotifyHosts * 2; i++)
434                         FreeStrBuf(&Ctx.NotifyHostList[i]);
435                 free(Ctx.NotifyHostList);
436         }
437 }
438
439
440
441 /* Create the notify message queue. We use the exact same room
442  * as the Funambol module.
443  *
444  * Run at server startup, creates FNBL_QUEUE_ROOM if it doesn't exist
445  * and sets as system room.
446  */
447 void create_extnotify_queue(void) {
448         struct ctdlroom qrbuf;
449
450         CtdlCreateRoom(FNBL_QUEUE_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
451
452         CtdlFillSystemContext(&extnotify_queue_CC, "Extnotify");
453
454         /*
455          * Make sure it's set to be a "system room" so it doesn't show up
456          * in the <K>nown rooms list for Aides.
457          */
458         if (CtdlGetRoomLock(&qrbuf, FNBL_QUEUE_ROOM) == 0) {
459                 qrbuf.QRflags2 |= QR2_SYSTEM;
460                 CtdlPutRoomLock(&qrbuf);
461         }
462 }
463
464 int extnotify_after_mbox_save(struct CtdlMessage *msg,
465                               recptypes *recps)
466
467 {
468         /* If this is private, local mail, make a copy in the
469          * recipient's mailbox and bump the reference count.
470          */
471         if (!IsEmptyStr(CtdlGetConfigStr("c_funambol_host")) || !IsEmptyStr(CtdlGetConfigStr("c_pager_program")))
472         {
473                 /* Generate a instruction message for the Funambol notification
474                  * server, in the same style as the SMTP queue
475                  */
476                 StrBuf *instr;
477                 struct CtdlMessage *imsg;
478
479                 instr = NewStrBufPlain(NULL, 1024);
480                 StrBufPrintf(instr,
481                              "Content-type: "SPOOLMIME"\n"
482                              "\n"
483                              "msgid|%s\n"
484                              "submitted|%ld\n"
485                              "bounceto|%s\n",
486                              msg->cm_fields[eVltMsgNum],
487                              (long)time(NULL), //todo: time() is expensive!
488                              recps->bounce_to
489                         );
490                                 
491                 imsg = malloc(sizeof(struct CtdlMessage));
492                 memset(imsg, 0, sizeof(struct CtdlMessage));
493                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
494                 imsg->cm_anon_type = MES_NORMAL;
495                 imsg->cm_format_type = FMT_RFC822;
496                 CM_SetField(imsg, eMsgSubject, HKEY("QMSG"));
497                 CM_SetField(imsg, eAuthor, HKEY("Citadel"));
498                 CM_SetField(imsg, eJournal, HKEY("do not journal"));
499                 CM_SetAsFieldSB(imsg, eMesageText, &instr);
500                 CM_SetField(imsg, eExtnotify, recps->recp_local, strlen(recps->recp_local));
501                 CtdlSubmitMsg(imsg, NULL, FNBL_QUEUE_ROOM, 0);
502                 CM_Free(imsg);
503         }
504         return 0;
505 }
506
507 CTDL_MODULE_INIT(extnotify)
508 {
509         if (!threading)
510         {
511                 create_extnotify_queue();
512                 CtdlRegisterMessageHook(extnotify_after_mbox_save, EVT_AFTERUSRMBOXSAVE);
513
514                 CtdlRegisterSessionHook(do_extnotify_queue, EVT_TIMER, PRIO_SEND + 10);
515         }
516         /* return our module name for the log */
517         return "extnotify";
518 }