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