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