c649587f9a405a2ea34bbfeb8a627f65352092c6
[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-2009
12  *
13  *  This program is free 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 #include "sysdep.h"
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <stdio.h>
32 #include <fcntl.h>
33 #include <signal.h>
34 #include <pwd.h>
35 #include <errno.h>
36 #include <sys/types.h>
37
38 #if TIME_WITH_SYS_TIME
39 # include <sys/time.h>
40 # include <time.h>
41 #else
42 # if HAVE_SYS_TIME_H
43 #  include <sys/time.h>
44 # else
45 #  include <time.h>
46 # endif
47 #endif
48
49 #include <sys/wait.h>
50 #include <string.h>
51 #include <limits.h>
52 #include <sys/socket.h>
53 #include <libcitadel.h>
54 #include "citadel.h"
55 #include "server.h"
56 #include "citserver.h"
57 #include "support.h"
58 #include "config.h"
59 #include "control.h"
60 #include "user_ops.h"
61 #include "database.h"
62 #include "msgbase.h"
63 #include "internet_addressing.h"
64 #include "domain.h"
65 #include "clientsocket.h"
66 #include "extnotify.h"
67
68 #include "ctdl_module.h"
69
70
71
72 void ExtNotify_PutErrorMessage(NotifyContext *Ctx, StrBuf *ErrMsg)
73 {
74         int nNext;
75         if (Ctx->NotifyErrors == NULL)
76                 Ctx->NotifyErrors = NewHash(1, Flathash);
77
78         nNext = GetCount(Ctx->NotifyErrors) + 1;
79         Put(Ctx->NotifyErrors, 
80             (char*)&nNext, 
81             sizeof(int), 
82             ErrMsg, 
83             HFreeStrBuf);
84 }
85
86
87
88
89 StrBuf* GetNHBuf(int i, int allocit, StrBuf **NotifyHostList)
90 {
91         if ((NotifyHostList[i] == NULL) && (allocit != 0))
92                 NotifyHostList[i] = NewStrBuf();
93         return NotifyHostList[i];
94 }
95
96
97 StrBuf** GetNotifyHosts(void)
98 {
99         char NotifyHostsBuf[SIZ];
100         StrBuf *Host;
101         StrBuf *File;
102         StrBuf *NotifyBuf;
103         int notify;
104         const char *pchs, *pche;
105         const char *NextHost = NULL;
106         StrBuf **NotifyHostList;
107         int num_notify;
108
109         /* See if we have any Notification Hosts configured */
110         num_notify = get_hosts(NotifyHostsBuf, "notify");
111         if (num_notify < 1)
112                 return(NULL);
113
114         NotifyHostList = malloc(sizeof(StrBuf*) * 2 * (num_notify + 1));
115         memset(NotifyHostList, 0, sizeof(StrBuf*) * 2 * (num_notify + 1));
116         
117         NotifyBuf = NewStrBufPlain(NotifyHostsBuf, -1);
118         /* get all configured notifiers's */
119         for (notify=0; notify<num_notify; notify++) {
120                 
121                 Host = GetNHBuf(notify * 2, 1, NotifyHostList);
122                 StrBufExtract_NextToken(Host, NotifyBuf, &NextHost, '|');
123                 pchs = ChrPtr(Host);
124                 pche = strchr(pchs, ':');
125                 if (pche == NULL) {
126                         CtdlLogPrintf(CTDL_ERR, 
127                                       __FILE__": filename not found in %s.\n", 
128                                       pchs);
129                         continue;
130                 }
131                 File = GetNHBuf(notify * 2 + 1, 1, NotifyHostList);
132                 StrBufPlain(File, pchs, pche - pchs);
133                 StrBufCutLeft(Host, pche - pchs + 1);
134         }
135         return NotifyHostList;
136 }
137
138
139 /*! \brief Create the notify message queue. We use the exact same room
140  *                      as the Funambol module.
141  *
142  *      Run at server startup, creates FNBL_QUEUE_ROOM if it doesn't exist
143  *      and sets as system room.
144  */
145 void create_extnotify_queue(void) {
146         struct ctdlroom qrbuf;
147     
148         CtdlCreateRoom(FNBL_QUEUE_ROOM, 3, "", 0, 1, 0, VIEW_MAILBOX);
149     
150         /*
151          * Make sure it's set to be a "system room" so it doesn't show up
152          * in the <K>nown rooms list for Aides.
153          */
154         if (CtdlGetRoomLock(&qrbuf, FNBL_QUEUE_ROOM) == 0) {
155                 qrbuf.QRflags2 |= QR2_SYSTEM;
156                 CtdlPutRoomLock(&qrbuf);
157         }
158 }
159 /*!
160  * \brief Run through the pager room queue
161  */
162 void do_extnotify_queue(void) 
163 {
164
165         NotifyContext Ctx;
166         static int doing_queue = 0;
167         int i = 0;
168         CitContext extnotifyCC;
169     
170         /*
171          * This is a simple concurrency check to make sure only one queue run
172          * is done at a time.  We could do this with a mutex, but since we
173          * don't really require extremely fine granularity here, we'll do it
174          * with a static variable instead.
175          */
176         if (doing_queue) return;
177         doing_queue = 1;
178
179         /* Give this thread its own private CitContext */
180         CtdlFillSystemContext(&extnotifyCC, "extnotify");
181         citthread_setspecific(MyConKey, (void *)&extnotifyCC );
182     
183         /*
184          * Go ahead and run the queue
185          */
186         CtdlLogPrintf(CTDL_DEBUG, "serv_extnotify: processing notify queue\n");
187     
188         memset(&Ctx, 0, sizeof(NotifyContext));
189         Ctx.NotifyHostList = GetNotifyHosts();
190         if (CtdlGetRoom(&CC->room, FNBL_QUEUE_ROOM) != 0) {
191                 CtdlLogPrintf(CTDL_ERR, "Cannot find room <%s>\n", FNBL_QUEUE_ROOM);
192                 CtdlClearSystemContext();
193                 return;
194         }
195         CtdlForEachMessage(MSGS_ALL, 0L, NULL,
196                            SPOOLMIME, NULL, process_notify, &Ctx);
197
198         while ((Ctx.NotifyHostList != NULL) && (Ctx.NotifyHostList[i] != NULL))
199                 FreeStrBuf(&Ctx.NotifyHostList[i]);
200
201         if (Ctx.NotifyErrors != NULL)
202         {
203                 long len;
204                 const char *Key;
205                 HashPos *It;
206                 void *vErr;
207                 StrBuf *ErrMsg;
208
209                 It = GetNewHashPos(Ctx.NotifyErrors, 0);
210                 while (GetNextHashPos(Ctx.NotifyErrors, It, &len, &Key, &vErr) && 
211                        (vErr != NULL)) {
212                         ErrMsg = (StrBuf*) vErr;
213                         quickie_message("Citadel", NULL, NULL, AIDEROOM, ChrPtr(ErrMsg), FMT_FIXED, 
214                                         "Failed to notify external service about inbound mail");
215                 }
216
217                 DeleteHashPos(&It);
218                 DeleteHash(&Ctx.NotifyErrors);
219         }
220
221         CtdlLogPrintf(CTDL_DEBUG, "serv_extnotify: queue run completed\n");
222         doing_queue = 0;
223         CtdlClearSystemContext();
224 }
225 /*!
226  * \brief Process messages in the external notification queue
227  */
228 void process_notify(long NotifyMsgnum, void *usrdata) 
229 {
230         NotifyContext *Ctx;
231         long msgnum = 0;
232         long todelete[1];
233         int fnblAllowed;
234         int extPagerAllowedHttp;
235         int extPagerAllowedSystem;
236         char *pch;
237         long configMsgNum;
238         char configMsg[SIZ];
239         struct CtdlMessage *msg;
240
241         Ctx = (NotifyContext*) usrdata;
242
243         msg = CtdlFetchMessage(NotifyMsgnum, 1);
244         if ( msg->cm_fields['W'] == NULL) {
245                 goto nuke;
246         }
247     
248         configMsgNum = extNotify_getConfigMessage(msg->cm_fields['W']);
249     
250         extNotify_getPrefs(configMsgNum, &configMsg[0]);
251         
252         /* Check to see if:
253          * 1. The user has configured paging / They have and disabled it
254          * AND 2. There is an external pager program
255          * 3. A Funambol server has been entered
256          *
257          */
258         if ((configMsgNum == -1) || 
259             ((strncasecmp(configMsg, "none", 4) == 0) &&
260              IsEmptyStr(config.c_pager_program) && 
261              IsEmptyStr(config.c_funambol_host))) {
262                 CtdlLogPrintf(CTDL_DEBUG, "No external notifiers configured on system/user");
263                 goto nuke;
264         }
265
266         // Can Funambol take the message?
267         pch = strchr(configMsg, '\n');
268         if (*pch == '\n')
269             *pch = '\0';
270         fnblAllowed = strncasecmp(configMsg, HKEY(FUNAMBOL_CONFIG_TEXT));
271         extPagerAllowedHttp = strncasecmp(configMsg, HKEY(PAGER_CONFIG_HTTP)); 
272         extPagerAllowedSystem = strncasecmp(configMsg, HKEY(PAGER_CONFIG_SYSTEM));
273         pch = strstr(msg->cm_fields['M'], "msgid|");
274         if (pch != NULL) 
275                 msgnum = atol(pch + sizeof("msgid"));
276         if (fnblAllowed == 0) {
277                 char remoteurl[SIZ];
278                 snprintf(remoteurl, SIZ, "http://%s@%s:%d/%s",
279                          config.c_funambol_auth,
280                          config.c_funambol_host,
281                          config.c_funambol_port,
282                          FUNAMBOL_WS);
283                 notify_http_server(remoteurl, 
284                                    file_funambol_msg,
285                                    strlen(file_funambol_msg),/*GNA*/
286                                    msg->cm_fields['W'], 
287                                    msg->cm_fields['I'],
288                                    msgnum, 
289                                    Ctx);
290         } else if (extPagerAllowedHttp == 0) {
291                 int i = 0;
292                 StrBuf *URL;
293                 char URLBuf[SIZ];
294                 StrBuf *File;
295                 StrBuf *FileBuf = NewStrBuf();
296                 
297                 while(1)
298                 {
299
300                         URL = GetNHBuf(i*2, 0, Ctx->NotifyHostList);
301                         if (URL==NULL) break;
302                         File = GetNHBuf(i*2 + 1, 0, Ctx->NotifyHostList);
303                         if (File==NULL) break;
304
305                         if (StrLength(File)>0)
306                                 StrBufPrintf(FileBuf, "%s/%s", 
307                                              ctdl_shared_dir, 
308                                              ChrPtr(File));
309                         else
310                                 FlushStrBuf(FileBuf);
311                         memcpy(URLBuf, ChrPtr(URL), StrLength(URL) + 1);
312
313                         notify_http_server(URLBuf, 
314                                            ChrPtr(FileBuf),
315                                            StrLength(FileBuf),
316                                            msg->cm_fields['W'], 
317                                            msg->cm_fields['I'],
318                                            msgnum, 
319                                            Ctx);
320                         i++;
321                 }
322                 FreeStrBuf(&FileBuf);
323         } 
324         else if (extPagerAllowedSystem == 0) {
325                 char *number;
326                 int commandSiz;
327                 char *command;
328
329                 number = strtok(configMsg, "textmessage\n");
330                 commandSiz = sizeof(config.c_pager_program) + strlen(number) + strlen(msg->cm_fields['W']) + 5;
331                 command = malloc(commandSiz);
332                 snprintf(command, commandSiz, "%s %s -u %s", config.c_pager_program, number, msg->cm_fields['W']);
333                 system(command);
334                 free(command);
335         }
336 nuke:
337         CtdlFreeMessage(msg);
338         memset(configMsg, 0, sizeof(configMsg));
339         todelete[0] = NotifyMsgnum;
340         CtdlDeleteMessages(FNBL_QUEUE_ROOM, todelete, 1, "");
341 }
342
343 /*! \brief Checks to see what notification option the user has set
344  *
345  */
346 void extNotify_getPrefs(long configMsgNum, char *configMsg) 
347 {
348         struct CtdlMessage *prefMsg;
349         // Do a simple string search to see if 'funambol' is selected as the
350         // type. This string would be at the very top of the message contents.
351         if (configMsgNum == -1) {
352                 CtdlLogPrintf(CTDL_ERR, "extNotify_isAllowedByPrefs was passed a non-existant config message id\n");
353                 return;
354         }
355         prefMsg = CtdlFetchMessage(configMsgNum, 1);
356         strncpy(configMsg, prefMsg->cm_fields['M'], strlen(prefMsg->cm_fields['M']));
357         CtdlFreeMessage(prefMsg);
358 }
359
360 /*! \brief Get configuration message for pager/funambol system from the
361  *                      users "My Citadel Config" room
362  */
363 long extNotify_getConfigMessage(char *username) {
364         struct ctdlroom qrbuf; // scratch for room
365         struct ctdluser user; // ctdl user instance
366         char configRoomName[ROOMNAMELEN];
367         struct CtdlMessage *msg;
368         struct cdbdata *cdbfr;
369         long *msglist = NULL;
370         int num_msgs = 0;
371         long confMsgNum = -1;
372         int a;
373
374         // Get the user
375         CtdlGetUser(&user, username);
376     
377         CtdlMailboxName(configRoomName, sizeof configRoomName, &user, USERCONFIGROOM);
378         // Fill qrbuf
379         CtdlGetRoom(&qrbuf, configRoomName);
380         /* Do something really, really stoopid here. Raid the room on ourselves,
381          * loop through the messages manually and find it. I don't want
382          * to use a CtdlForEachMessage callback here, as we would be
383          * already in one */
384         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
385         if (cdbfr != NULL) {
386                 msglist = (long *) cdbfr->ptr;
387                 cdbfr->ptr = NULL;      /* CtdlForEachMessage() now owns this memory */
388                 num_msgs = cdbfr->len / sizeof(long);
389                 cdb_free(cdbfr);
390         } else {
391                 CtdlLogPrintf(CTDL_DEBUG, "extNotify_getConfigMessage: No config messages found\n");
392                 return -1;      /* No messages at all?  No further action. */
393         }
394         for (a = 0; a < num_msgs; ++a) {
395                 msg = CtdlFetchMessage(msglist[a], 1);
396                 if (msg != NULL) {
397                         if ((msg->cm_fields['U'] != NULL) && 
398                             (strncasecmp(msg->cm_fields['U'], PAGER_CONFIG_MESSAGE,
399                                          strlen(PAGER_CONFIG_MESSAGE)) == 0)) {
400                                 confMsgNum = msglist[a];
401                         }
402                         CtdlFreeMessage(msg);
403                 }
404         }
405         return confMsgNum;
406     
407 }
408
409 CTDL_MODULE_INIT(extnotify)
410 {
411         if (!threading)
412         {
413                 create_extnotify_queue();
414                 CtdlRegisterSessionHook(do_extnotify_queue, EVT_TIMER);
415         }
416         /* return our Subversion id for the Log */
417         return "$Id$";
418 }