Removed the logging facility from citserver, use syslog instead
[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 int GetNotifyHosts(NotifyContext *Ctx)
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
105         /* See if we have any Notification Hosts configured */
106         Ctx->nNotifyHosts = get_hosts(NotifyHostsBuf, "notify");
107         if (Ctx->nNotifyHosts < 1)
108                 return 0;
109
110         Ctx->NotifyHostList = malloc(sizeof(StrBuf*) * 2 * (Ctx->nNotifyHosts + 1));
111         memset(Ctx->NotifyHostList, 0, sizeof(StrBuf*) * 2 * (Ctx->nNotifyHosts + 1));
112         
113         NotifyBuf = NewStrBufPlain(NotifyHostsBuf, -1);
114         /* get all configured notifiers's */
115         for (notify=0; notify<Ctx->nNotifyHosts; notify++) {
116                 
117                 Host = GetNHBuf(notify * 2, 1, Ctx->NotifyHostList);
118                 StrBufExtract_NextToken(Host, NotifyBuf, &NextHost, '|');
119                 pchs = ChrPtr(Host);
120                 pche = strchr(pchs, ':');
121                 if (pche == NULL) {
122                         syslog(LOG_ERR, 
123                                       "extnotify: filename of notification template not found in %s.\n", 
124                                       pchs);
125                         continue;
126                 }
127                 File = GetNHBuf(notify * 2 + 1, 1, Ctx->NotifyHostList);
128                 StrBufPlain(File, pchs, pche - pchs);
129                 StrBufCutLeft(Host, pche - pchs + 1);
130         }
131         FreeStrBuf(&NotifyBuf);
132         return Ctx->nNotifyHosts;
133 }
134
135
136 /*! \brief Get configuration message for pager/funambol system from the
137  *                      users "My Citadel Config" room
138  */
139 eNotifyType extNotify_getConfigMessage(char *username, char **PagerNumber, char **FreeMe) 
140 {
141         struct ctdlroom qrbuf; // scratch for room
142         struct ctdluser user; // ctdl user instance
143         char configRoomName[ROOMNAMELEN];
144         struct CtdlMessage *msg = NULL;
145         struct cdbdata *cdbfr;
146         long *msglist = NULL;
147         int num_msgs = 0;
148         int a;
149         char *configMsg;
150         char *pch;
151
152         // Get the user
153         CtdlGetUser(&user, username);
154     
155         CtdlMailboxName(configRoomName, sizeof configRoomName, &user, USERCONFIGROOM);
156         // Fill qrbuf
157         CtdlGetRoom(&qrbuf, configRoomName);
158         /* Do something really, really stoopid here. Raid the room on ourselves,
159          * loop through the messages manually and find it. I don't want
160          * to use a CtdlForEachMessage callback here, as we would be
161          * already in one */
162         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
163         if (cdbfr != NULL) {
164                 msglist = (long *) cdbfr->ptr;
165                 cdbfr->ptr = NULL;      /* CtdlForEachMessage() now owns this memory */
166                 num_msgs = cdbfr->len / sizeof(long);
167                 cdb_free(cdbfr);
168         } else {
169                 syslog(LOG_DEBUG, "extNotify_getConfigMessage: No config messages found\n");
170                 return eNone;   /* No messages at all?  No further action. */
171         }
172         for (a = 0; a < num_msgs; ++a) {
173                 msg = CtdlFetchMessage(msglist[a], 1);
174                 if (msg != NULL) {
175                         if ((msg->cm_fields['U'] != NULL) && 
176                             (strncasecmp(msg->cm_fields['U'], PAGER_CONFIG_MESSAGE,
177                                          strlen(PAGER_CONFIG_MESSAGE)) == 0)) {
178                                 break;
179                         }
180                         CtdlFreeMessage(msg);
181                         msg = NULL;
182                 }
183         }
184        
185         free(msglist);
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                         for (i = 0; i < Ctx->nNotifyHosts; i++)
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                         }
331                         FreeStrBuf(&FileBuf);
332                 } 
333                 break;
334                 case eTextMessage:
335                 {
336                         int commandSiz;
337                         char *command;
338
339                         commandSiz = sizeof(config.c_pager_program) + strlen(PagerNo) + strlen(msg->cm_fields['W']) + 5;
340                         command = malloc(commandSiz);
341                         snprintf(command, commandSiz, "%s %s -u %s", config.c_pager_program, PagerNo, msg->cm_fields['W']);
342                         system(command);
343                         free(command);
344                 }
345                 break;
346                 case eNone:
347                         break;
348                 }
349         }
350         if (FreeMe != NULL)
351                 free(FreeMe);
352         CtdlFreeMessage(msg);
353         todelete[0] = NotifyMsgnum;
354         CtdlDeleteMessages(FNBL_QUEUE_ROOM, todelete, 1, "");
355 }
356
357
358
359
360
361
362 /*!
363  * \brief Run through the pager room queue
364  */
365 void do_extnotify_queue(void) 
366 {
367         NotifyContext Ctx;
368         static int doing_queue = 0;
369         int i = 0;
370     
371         /*
372          * This is a simple concurrency check to make sure only one queue run
373          * is done at a time.  We could do this with a mutex, but since we
374          * don't really require extremely fine granularity here, we'll do it
375          * with a static variable instead.
376          */
377
378         if (IsEmptyStr(config.c_pager_program) && 
379             IsEmptyStr(config.c_funambol_host))
380         {
381                 syslog(LOG_ERR, "No external notifiers configured on system/user\n");
382                 return;
383         }
384
385         if (doing_queue) return;
386         doing_queue = 1;
387
388         citthread_setspecific(MyConKey, (void *)&extnotify_queue_CC);
389
390         /*
391          * Go ahead and run the queue
392          */
393         syslog(LOG_DEBUG, "serv_extnotify: processing notify queue\n");
394
395         memset(&Ctx, 0, sizeof(NotifyContext));
396         if ((GetNotifyHosts(&Ctx) > 0) && 
397             (CtdlGetRoom(&CC->room, FNBL_QUEUE_ROOM) != 0))
398         {
399                 syslog(LOG_ERR, "Cannot find room <%s>\n", FNBL_QUEUE_ROOM);
400                 CtdlClearSystemContext();
401                 if (Ctx.nNotifyHosts > 0)
402                 {
403                         for (i = 0; i < Ctx.nNotifyHosts * 2; i++)
404                                 FreeStrBuf(&Ctx.NotifyHostList[i]);
405                         free(Ctx.NotifyHostList);
406                 }
407                 return;
408         }
409         CtdlForEachMessage(MSGS_ALL, 0L, NULL,
410                            SPOOLMIME, NULL, process_notify, &Ctx);
411         syslog(LOG_DEBUG, "serv_extnotify: queue run completed\n");
412         doing_queue = 0;
413         if (Ctx.nNotifyHosts > 0)
414         {
415                 for (i = 0; i < Ctx.nNotifyHosts * 2; i++)
416                         FreeStrBuf(&Ctx.NotifyHostList[i]);
417                 free(Ctx.NotifyHostList);
418         }
419 }
420
421
422
423 /* Create the notify message queue. We use the exact same room
424  * as the Funambol module.
425  *
426  * Run at server startup, creates FNBL_QUEUE_ROOM if it doesn't exist
427  * and sets as system room.
428  */
429 void create_extnotify_queue(void) {
430         struct ctdlroom qrbuf;
431     
432         CtdlCreateRoom(FNBL_QUEUE_ROOM, 3, "", 0, 1, 0, VIEW_MAILBOX);
433
434         CtdlFillSystemContext(&extnotify_queue_CC, "Extnotify");
435     
436         /*
437          * Make sure it's set to be a "system room" so it doesn't show up
438          * in the <K>nown rooms list for Aides.
439          */
440         if (CtdlGetRoomLock(&qrbuf, FNBL_QUEUE_ROOM) == 0) {
441                 qrbuf.QRflags2 |= QR2_SYSTEM;
442                 CtdlPutRoomLock(&qrbuf);
443         }
444 }
445
446 CTDL_MODULE_INIT(extnotify)
447 {
448         if (!threading)
449         {
450                 create_extnotify_queue();
451                 CtdlRegisterSessionHook(do_extnotify_queue, EVT_TIMER);
452         }
453         /* return our Subversion id for the Log */
454         return "extnotify";
455 }