And a few more things comply with the coding style.
[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 "policy.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
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 /*! \brief 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         NotifyContext Ctx;
166         static int doing_queue = 0;
167         int i = 0;
168     
169         /*
170          * This is a simple concurrency check to make sure only one queue run
171          * is done at a time.  We could do this with a mutex, but since we
172          * don't really require extremely fine granularity here, we'll do it
173          * with a static variable instead.
174          */
175         if (doing_queue) return;
176         doing_queue = 1;
177     
178         /*
179          * Go ahead and run the queue
180          */
181         CtdlLogPrintf(CTDL_DEBUG, "serv_extnotify: processing notify queue\n");
182     
183         memset(&Ctx, 0, sizeof(NotifyContext));
184         Ctx.NotifyHostList = GetNotifyHosts();
185         if (CtdlGetRoom(&CC->room, FNBL_QUEUE_ROOM) != 0) {
186                 CtdlLogPrintf(CTDL_ERR, "Cannot find room <%s>\n", FNBL_QUEUE_ROOM);
187                 return;
188         }
189         CtdlForEachMessage(MSGS_ALL, 0L, NULL,
190                            SPOOLMIME, NULL, process_notify, &Ctx);
191
192         while ((Ctx.NotifyHostList != NULL) && (Ctx.NotifyHostList[i] != NULL))
193                 FreeStrBuf(&Ctx.NotifyHostList[i]);
194
195         if (Ctx.NotifyErrors != NULL)
196         {
197                 long len;
198                 const char *Key;
199                 HashPos *It;
200                 void *vErr;
201                 StrBuf *ErrMsg;
202
203                 It = GetNewHashPos(Ctx.NotifyErrors, 0);
204                 while (GetNextHashPos(Ctx.NotifyErrors, It, &len, &Key, &vErr) && 
205                        (vErr != NULL)) {
206                         ErrMsg = (StrBuf*) vErr;
207                         quickie_message("Citadel", NULL, NULL, AIDEROOM, ChrPtr(ErrMsg), FMT_FIXED, 
208                                         "Failed to notify external service about inbound mail");
209                 }
210
211                 DeleteHashPos(&It);
212                 DeleteHash(&Ctx.NotifyErrors);
213         }
214
215         CtdlLogPrintf(CTDL_DEBUG, "serv_extnotify: queue run completed\n");
216         doing_queue = 0;
217 }
218 /*!
219  * \brief Process messages in the external notification queue
220  */
221 void process_notify(long NotifyMsgnum, void *usrdata) 
222 {
223         NotifyContext *Ctx;
224         long msgnum = 0;
225         long todelete[1];
226         int fnblAllowed;
227         int extPagerAllowedHttp;
228         int extPagerAllowedSystem;
229         char *pch;
230         long configMsgNum;
231         char configMsg[SIZ];
232         struct CtdlMessage *msg;
233
234         Ctx = (NotifyContext*) usrdata;
235
236         msg = CtdlFetchMessage(NotifyMsgnum, 1);
237         if ( msg->cm_fields['W'] == NULL) {
238                 goto nuke;
239         }
240     
241         configMsgNum = extNotify_getConfigMessage(msg->cm_fields['W']);
242     
243         extNotify_getPrefs(configMsgNum, &configMsg[0]);
244         
245         /* Check to see if:
246          * 1. The user has configured paging / They have and disabled it
247          * AND 2. There is an external pager program
248          * 3. A Funambol server has been entered
249          *
250          */
251         if ((configMsgNum == -1) || 
252             ((strncasecmp(configMsg, "none", 4) == 0) &&
253              IsEmptyStr(config.c_pager_program) && 
254              IsEmptyStr(config.c_funambol_host))) {
255                 CtdlLogPrintf(CTDL_DEBUG, "No external notifiers configured on system/user");
256                 goto nuke;
257         }
258
259         // Can Funambol take the message?
260         pch = strchr(configMsg, '\n');
261         if (*pch == '\n')
262             *pch = '\0';
263         fnblAllowed = strncasecmp(configMsg, HKEY(FUNAMBOL_CONFIG_TEXT));
264         extPagerAllowedHttp = strncasecmp(configMsg, HKEY(PAGER_CONFIG_HTTP)); 
265         extPagerAllowedSystem = strncasecmp(configMsg, HKEY(PAGER_CONFIG_SYSTEM));
266         pch = strstr(msg->cm_fields['M'], "msgid|");
267         if (pch != NULL) 
268                 msgnum = atol(pch + sizeof("msgid"));
269         if (fnblAllowed == 0) {
270                 char remoteurl[SIZ];
271                 snprintf(remoteurl, SIZ, "http://%s@%s:%d/%s",
272                          config.c_funambol_auth,
273                          config.c_funambol_host,
274                          config.c_funambol_port,
275                          FUNAMBOL_WS);
276                 notify_http_server(remoteurl, 
277                                    file_funambol_msg,
278                                    strlen(file_funambol_msg),/*GNA*/
279                                    msg->cm_fields['W'], 
280                                    msg->cm_fields['I'],
281                                    msgnum, 
282                                    Ctx);
283         } else if (extPagerAllowedHttp == 0) {
284                 int i = 0;
285                 StrBuf *URL;
286                 char URLBuf[SIZ];
287                 StrBuf *File;
288                 StrBuf *FileBuf = NewStrBuf();
289                 
290                 while(1)
291                 {
292
293                         URL = GetNHBuf(i*2, 0, Ctx->NotifyHostList);
294                         if (URL==NULL) break;
295                         File = GetNHBuf(i*2 + 1, 0, Ctx->NotifyHostList);
296                         if (File==NULL) break;
297
298                         if (StrLength(File)>0)
299                                 StrBufPrintf(FileBuf, "%s/%s", 
300                                              ctdl_shared_dir, 
301                                              ChrPtr(File));
302                         else
303                                 FlushStrBuf(FileBuf);
304                         memcpy(URLBuf, ChrPtr(URL), StrLength(URL) + 1);
305
306                         notify_http_server(URLBuf, 
307                                            ChrPtr(FileBuf),
308                                            StrLength(FileBuf),
309                                            msg->cm_fields['W'], 
310                                            msg->cm_fields['I'],
311                                            msgnum, 
312                                            Ctx);
313                         i++;
314                 }
315                 FreeStrBuf(&FileBuf);
316         } 
317         else if (extPagerAllowedSystem == 0) {
318                 char *number;
319                 int commandSiz;
320                 char *command;
321
322                 number = strtok(configMsg, "textmessage\n");
323                 commandSiz = sizeof(config.c_pager_program) + strlen(number) + strlen(msg->cm_fields['W']) + 5;
324                 command = malloc(commandSiz);
325                 snprintf(command, commandSiz, "%s %s -u %s", config.c_pager_program, number, msg->cm_fields['W']);
326                 system(command);
327                 free(command);
328         }
329 nuke:
330         CtdlFreeMessage(msg);
331         memset(configMsg, 0, sizeof(configMsg));
332         todelete[0] = NotifyMsgnum;
333         CtdlDeleteMessages(FNBL_QUEUE_ROOM, todelete, 1, "");
334 }
335
336 /*! \brief Checks to see what notification option the user has set
337  *
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                 CtdlLogPrintf(CTDL_ERR, "extNotify_isAllowedByPrefs was passed a non-existant config message id\n");
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 /*! \brief Get configuration message for pager/funambol system from the
354  *                      users "My Citadel Config" room
355  */
356 long extNotify_getConfigMessage(char *username) {
357         struct ctdlroom qrbuf; // scratch for room
358         struct ctdluser user; // ctdl user instance
359         char configRoomName[ROOMNAMELEN];
360         struct CtdlMessage *msg;
361         struct cdbdata *cdbfr;
362         long *msglist = NULL;
363         int num_msgs = 0;
364         long confMsgNum = -1;
365         int a;
366
367         // Get the user
368         CtdlGetUser(&user, username);
369     
370         CtdlMailboxName(configRoomName, sizeof configRoomName, &user, USERCONFIGROOM);
371         // Fill qrbuf
372         CtdlGetRoom(&qrbuf, configRoomName);
373         /* Do something really, really stoopid here. Raid the room on ourselves,
374          * loop through the messages manually and find it. I don't want
375          * to use a CtdlForEachMessage callback here, as we would be
376          * already in one */
377         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
378         if (cdbfr != NULL) {
379                 msglist = (long *) cdbfr->ptr;
380                 cdbfr->ptr = NULL;      /* CtdlForEachMessage() now owns this memory */
381                 num_msgs = cdbfr->len / sizeof(long);
382                 cdb_free(cdbfr);
383         } else {
384                 CtdlLogPrintf(CTDL_DEBUG, "extNotify_getConfigMessage: No config messages found\n");
385                 return -1;      /* No messages at all?  No further action. */
386         }
387         for (a = 0; a < num_msgs; ++a) {
388                 msg = CtdlFetchMessage(msglist[a], 1);
389                 if (msg != NULL) {
390                         if ((msg->cm_fields['U'] != NULL) && 
391                             (strncasecmp(msg->cm_fields['U'], PAGER_CONFIG_MESSAGE,
392                                          strlen(PAGER_CONFIG_MESSAGE)) == 0)) {
393                                 confMsgNum = msglist[a];
394                         }
395                         CtdlFreeMessage(msg);
396                 }
397         }
398         return confMsgNum;
399     
400 }
401
402 CTDL_MODULE_INIT(extnotify)
403 {
404         if (!threading)
405         {
406                 create_extnotify_queue();
407                 CtdlRegisterSessionHook(do_extnotify_queue, EVT_TIMER);
408         }
409         /* return our Subversion id for the Log */
410         return "$Id$";
411 }