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