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