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