0f85dfc77ca93162180a6062265c705c311bfa65
[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 msgnum, void *usrdata) 
165 {
166         long todelete[1];
167         int fnblAllowed;
168         int extPagerAllowedHttp;
169         int extPagerAllowedSystem;
170         char *pch;
171         long configMsgNum;
172         char configMsg[SIZ];
173         StrBuf **NotifyHostList;        
174         struct CtdlMessage *msg;
175
176
177         NotifyHostList = (StrBuf**) usrdata;
178         msg = CtdlFetchMessage(msgnum, 1);
179         if ( msg->cm_fields['W'] == NULL) {
180                 goto nuke;
181         }
182     
183         configMsgNum = extNotify_getConfigMessage(msg->cm_fields['W']);
184     
185         extNotify_getPrefs(configMsgNum, &configMsg[0]);
186         
187         /* Check to see if:
188          * 1. The user has configured paging / They have and disabled it
189          * AND 2. There is an external pager program
190          * 3. A Funambol server has been entered
191          *
192          */
193         if ((configMsgNum == -1) || 
194             ((strncasecmp(configMsg, "none", 4) == 0) &&
195              IsEmptyStr(config.c_pager_program) && 
196              IsEmptyStr(config.c_funambol_host))) {
197                 CtdlLogPrintf(CTDL_DEBUG, "No external notifiers configured on system/user");
198                 goto nuke;
199         }
200
201         // Can Funambol take the message?
202         pch = strchr(configMsg, '\n');
203         if (*pch == '\n')
204             *pch = '\0';
205         fnblAllowed = strncasecmp(configMsg, HKEY(FUNAMBOL_CONFIG_TEXT));
206         extPagerAllowedHttp = strncasecmp(configMsg, HKEY(PAGER_CONFIG_HTTP)); 
207         extPagerAllowedSystem = strncasecmp(configMsg, HKEY(PAGER_CONFIG_SYSTEM));
208
209         if (fnblAllowed == 0) {
210                 char remoteurl[SIZ];
211                 snprintf(remoteurl, SIZ, "http://%s@%s:%d/%s",
212                          config.c_funambol_auth,
213                          config.c_funambol_host,
214                          config.c_funambol_port,
215                          FUNAMBOL_WS);
216                 notify_http_server(remoteurl, 
217                                    file_funambol_msg,
218                                    strlen(file_funambol_msg),/*GNA*/
219                                    msg->cm_fields['W'], 
220                                    msg->cm_fields['I'],
221                                    msgnum);
222         } else if (extPagerAllowedHttp == 0) {
223                 int i = 0;
224                 StrBuf *URL;
225                 char URLBuf[SIZ];
226                 StrBuf *File;
227                 StrBuf *FileBuf = NewStrBuf();
228                 
229                 while(1)
230                 {
231
232                         URL = GetNHBuf(i*2, 0, NotifyHostList);
233                         if (URL==NULL) break;
234                         File = GetNHBuf(i*2 + 1, 0, NotifyHostList);
235                         if (File==NULL) break;
236
237                         if (StrLength(File)>0)
238                                 StrBufPrintf(FileBuf, "%s/%s", 
239                                              ctdl_shared_dir, 
240                                              ChrPtr(File));
241                         else
242                                 FlushStrBuf(FileBuf);
243                         memcpy(URLBuf, ChrPtr(URL), StrLength(URL) + 1);
244
245                         notify_http_server(URLBuf, 
246                                            ChrPtr(FileBuf),
247                                            StrLength(FileBuf),
248                                            msg->cm_fields['W'], 
249                                            msg->cm_fields['I'],
250                                            msgnum);
251                         i++;
252                 }
253                 FreeStrBuf(&FileBuf);
254         } 
255         else if (extPagerAllowedSystem == 0) {
256                 char *number;
257                 int commandSiz;
258                 char *command;
259
260                 number = strtok(configMsg, "textmessage\n");
261                 commandSiz = sizeof(config.c_pager_program) + strlen(number) + strlen(msg->cm_fields['W']) + 5;
262                 command = malloc(commandSiz);
263                 snprintf(command, commandSiz, "%s %s -u %s", config.c_pager_program, number, msg->cm_fields['W']);
264                 system(command);
265                 free(command);
266         }
267 nuke:
268         CtdlFreeMessage(msg);
269         memset(configMsg, 0, sizeof(configMsg));
270         todelete[0] = msgnum;
271         CtdlDeleteMessages(FNBL_QUEUE_ROOM, todelete, 1, "");
272 }
273
274 /*! \brief Checks to see what notification option the user has set
275  *
276  */
277 void extNotify_getPrefs(long configMsgNum, char *configMsg) 
278 {
279         struct CtdlMessage *prefMsg;
280         // Do a simple string search to see if 'funambol' is selected as the
281         // type. This string would be at the very top of the message contents.
282         if (configMsgNum == -1) {
283                 CtdlLogPrintf(CTDL_ERR, "extNotify_isAllowedByPrefs was passed a non-existant config message id\n");
284                 return;
285         }
286         prefMsg = CtdlFetchMessage(configMsgNum, 1);
287         strncpy(configMsg, prefMsg->cm_fields['M'], strlen(prefMsg->cm_fields['M']));
288         CtdlFreeMessage(prefMsg);
289 }
290
291 /*! \brief Get configuration message for pager/funambol system from the
292  *                      users "My Citadel Config" room
293  */
294 long extNotify_getConfigMessage(char *username) {
295         struct ctdlroom qrbuf; // scratch for room
296         struct ctdluser user; // ctdl user instance
297         char configRoomName[ROOMNAMELEN];
298         struct CtdlMessage *msg;
299         struct cdbdata *cdbfr;
300         long *msglist = NULL;
301         int num_msgs = 0;
302         long confMsgNum = -1;
303         int a;
304
305         // Get the user
306         getuser(&user, username);
307     
308         MailboxName(configRoomName, sizeof configRoomName, &user, USERCONFIGROOM);
309         // Fill qrbuf
310         getroom(&qrbuf, configRoomName);
311         /* Do something really, really stoopid here. Raid the room on ourselves,
312          * loop through the messages manually and find it. I don't want
313          * to use a CtdlForEachMessage callback here, as we would be
314          * already in one */
315         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
316         if (cdbfr != NULL) {
317                 msglist = (long *) cdbfr->ptr;
318                 cdbfr->ptr = NULL;      /* CtdlForEachMessage() now owns this memory */
319                 num_msgs = cdbfr->len / sizeof(long);
320                 cdb_free(cdbfr);
321         } else {
322                 CtdlLogPrintf(CTDL_DEBUG, "extNotify_getConfigMessage: No config messages found\n");
323                 return -1;      /* No messages at all?  No further action. */
324         }
325         for (a = 0; a < num_msgs; ++a) {
326                 msg = CtdlFetchMessage(msglist[a], 1);
327                 if (msg != NULL) {
328                         if ((msg->cm_fields['U'] != NULL) && 
329                             (strncasecmp(msg->cm_fields['U'], PAGER_CONFIG_MESSAGE,
330                                          strlen(PAGER_CONFIG_MESSAGE)) == 0)) {
331                                 confMsgNum = msglist[a];
332                         }
333                         CtdlFreeMessage(msg);
334                 }
335         }
336         return confMsgNum;
337     
338 }
339
340 CTDL_MODULE_INIT(extnotify)
341 {
342         if (!threading)
343         {
344                 create_extnotify_queue();
345                 CtdlRegisterSessionHook(do_extnotify_queue, EVT_TIMER);
346         }
347         /* return our Subversion id for the Log */
348         return "$Id$";
349 }