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