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