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