* More license declarations
[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 "room_ops.h"
61 #include "user_ops.h"
62 #include "policy.h"
63 #include "database.h"
64 #include "msgbase.h"
65 #include "internet_addressing.h"
66 #include "domain.h"
67 #include "clientsocket.h"
68 #include "extnotify.h"
69
70 #include "ctdl_module.h"
71
72
73
74 void ExtNotify_PutErrorMessage(NotifyContext *Ctx, StrBuf *ErrMsg)
75 {
76         int nNext;
77         if (Ctx->NotifyErrors == NULL)
78                 Ctx->NotifyErrors = NewHash(1, Flathash);
79
80         nNext = GetCount(Ctx->NotifyErrors) + 1;
81         Put(Ctx->NotifyErrors, 
82             (char*)&nNext, 
83             sizeof(int), 
84             ErrMsg, 
85             HFreeStrBuf);
86 }
87
88
89
90
91 StrBuf* GetNHBuf(int i, int allocit, StrBuf **NotifyHostList)
92 {
93         if ((NotifyHostList[i] == NULL) && (allocit != 0))
94                 NotifyHostList[i] = NewStrBuf();
95         return NotifyHostList[i];
96 }
97
98
99 StrBuf** GetNotifyHosts(void)
100 {
101         char NotifyHostsBuf[SIZ];
102         StrBuf *Host;
103         StrBuf *File;
104         StrBuf *NotifyBuf;
105         int notify;
106         const char *pchs, *pche;
107         const char *NextHost = NULL;
108         StrBuf **NotifyHostList;
109         int num_notify;
110
111         /* See if we have any Notification Hosts configured */
112         num_notify = get_hosts(NotifyHostsBuf, "notify");
113         if (num_notify < 1)
114                 return(NULL);
115
116         NotifyHostList = malloc(sizeof(StrBuf*) * 2 * (num_notify + 1));
117         memset(NotifyHostList, 0, sizeof(StrBuf*) * 2 * (num_notify + 1));
118         
119         NotifyBuf = NewStrBufPlain(NotifyHostsBuf, -1);
120         /* get all configured notifiers's */
121         for (notify=0; notify<num_notify; notify++) {
122                 
123                 Host = GetNHBuf(notify * 2, 1, NotifyHostList);
124                 StrBufExtract_NextToken(Host, NotifyBuf, &NextHost, '|');
125                 pchs = ChrPtr(Host);
126                 pche = strchr(pchs, ':');
127                 if (pche == NULL) {
128                         CtdlLogPrintf(CTDL_ERR, 
129                                       __FILE__": filename not found in %s.\n", 
130                                       pchs);
131                         continue;
132                 }
133                 File = GetNHBuf(notify * 2 + 1, 1, NotifyHostList);
134                 StrBufPlain(File, pchs, pche - pchs);
135                 StrBufCutLeft(Host, pche - pchs + 1);
136         }
137         return NotifyHostList;
138 }
139
140
141 /*! \brief Create the notify message queue. We use the exact same room
142  *                      as the Funambol module.
143  *
144  *      Run at server startup, creates FNBL_QUEUE_ROOM if it doesn't exist
145  *      and sets as system room.
146  */
147 void create_extnotify_queue(void) {
148         struct ctdlroom qrbuf;
149     
150         create_room(FNBL_QUEUE_ROOM, 3, "", 0, 1, 0, VIEW_MAILBOX);
151     
152         /*
153          * Make sure it's set to be a "system room" so it doesn't show up
154          * in the <K>nown rooms list for Aides.
155          */
156         if (lgetroom(&qrbuf, FNBL_QUEUE_ROOM) == 0) {
157                 qrbuf.QRflags2 |= QR2_SYSTEM;
158                 lputroom(&qrbuf);
159         }
160 }
161 /*!
162  * \brief Run through the pager room queue
163  */
164 void do_extnotify_queue(void) 
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 (getroom(&CC->room, FNBL_QUEUE_ROOM) != 0) {
187                 CtdlLogPrintf(CTDL_ERR, "Cannot find room <%s>\n", FNBL_QUEUE_ROOM);
188                 return;
189         }
190         CtdlForEachMessage(MSGS_ALL, 0L, NULL,
191                            SPOOLMIME, NULL, process_notify, &Ctx);
192
193         while ((Ctx.NotifyHostList != NULL) && (Ctx.NotifyHostList[i] != NULL))
194                 FreeStrBuf(&Ctx.NotifyHostList[i]);
195
196         if (Ctx.NotifyErrors != NULL)
197         {
198                 long len;
199                 const char *Key;
200                 HashPos *It;
201                 void *vErr;
202                 StrBuf *ErrMsg;
203
204                 It = GetNewHashPos(Ctx.NotifyErrors, 0);
205                 while (GetNextHashPos(Ctx.NotifyErrors, It, &len, &Key, &vErr) && 
206                        (vErr != NULL)) {
207                         ErrMsg = (StrBuf*) vErr;
208                         quickie_message("Citadel", NULL, NULL, AIDEROOM, ChrPtr(ErrMsg), FMT_FIXED, 
209                                         "Failed to notify external service about inbound mail");
210                 }
211
212                 DeleteHashPos(&It);
213                 DeleteHash(&Ctx.NotifyErrors);
214         }
215
216         CtdlLogPrintf(CTDL_DEBUG, "serv_extnotify: queue run completed\n");
217         doing_queue = 0;
218 }
219 /*!
220  * \brief Process messages in the external notification queue
221  */
222 void process_notify(long NotifyMsgnum, void *usrdata) 
223 {
224         NotifyContext *Ctx;
225         long msgnum = 0;
226         long todelete[1];
227         int fnblAllowed;
228         int extPagerAllowedHttp;
229         int extPagerAllowedSystem;
230         char *pch;
231         long configMsgNum;
232         char configMsg[SIZ];
233         struct CtdlMessage *msg;
234
235         Ctx = (NotifyContext*) usrdata;
236
237         msg = CtdlFetchMessage(NotifyMsgnum, 1);
238         if ( msg->cm_fields['W'] == NULL) {
239                 goto nuke;
240         }
241     
242         configMsgNum = extNotify_getConfigMessage(msg->cm_fields['W']);
243     
244         extNotify_getPrefs(configMsgNum, &configMsg[0]);
245         
246         /* Check to see if:
247          * 1. The user has configured paging / They have and disabled it
248          * AND 2. There is an external pager program
249          * 3. A Funambol server has been entered
250          *
251          */
252         if ((configMsgNum == -1) || 
253             ((strncasecmp(configMsg, "none", 4) == 0) &&
254              IsEmptyStr(config.c_pager_program) && 
255              IsEmptyStr(config.c_funambol_host))) {
256                 CtdlLogPrintf(CTDL_DEBUG, "No external notifiers configured on system/user");
257                 goto nuke;
258         }
259
260         // Can Funambol take the message?
261         pch = strchr(configMsg, '\n');
262         if (*pch == '\n')
263             *pch = '\0';
264         fnblAllowed = strncasecmp(configMsg, HKEY(FUNAMBOL_CONFIG_TEXT));
265         extPagerAllowedHttp = strncasecmp(configMsg, HKEY(PAGER_CONFIG_HTTP)); 
266         extPagerAllowedSystem = strncasecmp(configMsg, HKEY(PAGER_CONFIG_SYSTEM));
267         pch = strstr(msg->cm_fields['M'], "msgid|");
268         if (pch != NULL) 
269                 msgnum = atol(pch + sizeof("msgid"));
270         if (fnblAllowed == 0) {
271                 char remoteurl[SIZ];
272                 snprintf(remoteurl, SIZ, "http://%s@%s:%d/%s",
273                          config.c_funambol_auth,
274                          config.c_funambol_host,
275                          config.c_funambol_port,
276                          FUNAMBOL_WS);
277                 notify_http_server(remoteurl, 
278                                    file_funambol_msg,
279                                    strlen(file_funambol_msg),/*GNA*/
280                                    msg->cm_fields['W'], 
281                                    msg->cm_fields['I'],
282                                    msgnum, 
283                                    Ctx);
284         } else if (extPagerAllowedHttp == 0) {
285                 int i = 0;
286                 StrBuf *URL;
287                 char URLBuf[SIZ];
288                 StrBuf *File;
289                 StrBuf *FileBuf = NewStrBuf();
290                 
291                 while(1)
292                 {
293
294                         URL = GetNHBuf(i*2, 0, Ctx->NotifyHostList);
295                         if (URL==NULL) break;
296                         File = GetNHBuf(i*2 + 1, 0, Ctx->NotifyHostList);
297                         if (File==NULL) break;
298
299                         if (StrLength(File)>0)
300                                 StrBufPrintf(FileBuf, "%s/%s", 
301                                              ctdl_shared_dir, 
302                                              ChrPtr(File));
303                         else
304                                 FlushStrBuf(FileBuf);
305                         memcpy(URLBuf, ChrPtr(URL), StrLength(URL) + 1);
306
307                         notify_http_server(URLBuf, 
308                                            ChrPtr(FileBuf),
309                                            StrLength(FileBuf),
310                                            msg->cm_fields['W'], 
311                                            msg->cm_fields['I'],
312                                            msgnum, 
313                                            Ctx);
314                         i++;
315                 }
316                 FreeStrBuf(&FileBuf);
317         } 
318         else if (extPagerAllowedSystem == 0) {
319                 char *number;
320                 int commandSiz;
321                 char *command;
322
323                 number = strtok(configMsg, "textmessage\n");
324                 commandSiz = sizeof(config.c_pager_program) + strlen(number) + strlen(msg->cm_fields['W']) + 5;
325                 command = malloc(commandSiz);
326                 snprintf(command, commandSiz, "%s %s -u %s", config.c_pager_program, number, msg->cm_fields['W']);
327                 system(command);
328                 free(command);
329         }
330 nuke:
331         CtdlFreeMessage(msg);
332         memset(configMsg, 0, sizeof(configMsg));
333         todelete[0] = NotifyMsgnum;
334         CtdlDeleteMessages(FNBL_QUEUE_ROOM, todelete, 1, "");
335 }
336
337 /*! \brief Checks to see what notification option the user has set
338  *
339  */
340 void extNotify_getPrefs(long configMsgNum, char *configMsg) 
341 {
342         struct CtdlMessage *prefMsg;
343         // Do a simple string search to see if 'funambol' is selected as the
344         // type. This string would be at the very top of the message contents.
345         if (configMsgNum == -1) {
346                 CtdlLogPrintf(CTDL_ERR, "extNotify_isAllowedByPrefs was passed a non-existant config message id\n");
347                 return;
348         }
349         prefMsg = CtdlFetchMessage(configMsgNum, 1);
350         strncpy(configMsg, prefMsg->cm_fields['M'], strlen(prefMsg->cm_fields['M']));
351         CtdlFreeMessage(prefMsg);
352 }
353
354 /*! \brief Get configuration message for pager/funambol system from the
355  *                      users "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         getuser(&user, username);
370     
371         MailboxName(configRoomName, sizeof configRoomName, &user, USERCONFIGROOM);
372         // Fill qrbuf
373         getroom(&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                 CtdlLogPrintf(CTDL_DEBUG, "extNotify_getConfigMessage: No config messages found\n");
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 CTDL_MODULE_INIT(extnotify)
404 {
405         if (!threading)
406         {
407                 create_extnotify_queue();
408                 CtdlRegisterSessionHook(do_extnotify_queue, EVT_TIMER);
409         }
410         /* return our Subversion id for the Log */
411         return "$Id$";
412 }