20246c90d02a38ac25193743a01440340b5fca48
[citadel.git] / citadel / modules / extnotify / funambol65.c
1 /*
2  * funambol65.c
3  * Author: Mathew McBride
4  *
5  * This module facilitates notifications to a Funambol server
6  * for push email
7  *
8  * Based on bits of the previous serv_funambol
9  * Contact: <matt@mcbridematt.dhs.org> / <matt@comalies>
10  *
11  * Copyright (c) 2008-2010
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 version 3.
15  * 
16  * 
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  * 
24  * 
25  * 
26  */
27
28 #include <stdio.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <sys/socket.h>
32 #include <time.h>
33 #include <libcitadel.h>
34 #include <errno.h>
35 #include <unistd.h>
36 #include <curl/curl.h>
37
38 #include "citadel.h"
39 #include "citserver.h"
40 #include "citadel_dirs.h"
41 #include "clientsocket.h"
42 #include "sysdep.h"
43 #include "config.h"
44 #include "sysdep_decls.h"
45 #include "msgbase.h"
46 #include "ctdl_module.h"
47
48 #include "event_client.h"
49 #include "extnotify.h"
50
51 eNextState EvaluateResult(AsyncIO *IO);
52 eNextState ExtNotifyTerminate(AsyncIO *IO);
53 eNextState ExtNotifyTerminateDB(AsyncIO *IO);
54 eNextState ExtNotifyShutdownAbort(AsyncIO *IO);
55
56 /*
57 * \brief Sends a message to the Funambol server notifying
58 * of new mail for a user
59 * Returns 0 if unsuccessful
60 */
61 int notify_http_server(char *remoteurl,
62                        const char* template, long tlen,
63                        char *user,
64                        char *msgid,
65                        long MsgNum,
66                        NotifyContext *Ctx)
67 {
68         CURLcode sta;
69         char msgnumstr[128];
70         char *buf = NULL;
71         char *SOAPMessage = NULL;
72         char *contenttype = NULL;
73         StrBuf *ReplyBuf;
74         StrBuf *Buf;
75         CURL *chnd;
76         AsyncIO *IO;
77
78         IO = (AsyncIO*) malloc(sizeof(AsyncIO));
79         memset(IO, 0, sizeof(AsyncIO));
80
81         if (! InitcURLIOStruct(IO,
82                                NULL, /* we don't have personal data anymore. */
83                                "Citadel ExtNotify",
84                                EvaluateResult,
85                                ExtNotifyTerminate,
86                                ExtNotifyTerminateDB,
87                                ExtNotifyShutdownAbort))
88         {
89                 syslog(LOG_ALERT, "Unable to initialize libcurl.\n");
90                 goto abort;
91         }
92
93         snprintf(msgnumstr, 128, "%ld", MsgNum);
94
95         if (tlen > 0) {
96                 /* Load the template message. Get mallocs done too */
97                 int fd;
98                 struct stat statbuf;
99                 const char *mimetype;
100                 const char *Err = NULL;
101
102                 fd = open(template, O_RDONLY);
103                 if ((fd < 0) ||
104                     (fstat(fd, &statbuf) == -1))
105                 {
106                         char buf[SIZ];
107
108                         snprintf(buf, SIZ,
109                                  "Cannot load template file %s [%s] "
110                                  "won't send notification\r\n",
111                                  file_funambol_msg,
112                                  strerror(errno));
113                         syslog(LOG_ERR, "%s", buf);
114                         // TODO: once an hour!
115                         CtdlAideMessage(
116                                 buf,
117                                 "External notifier: "
118                                 "unable to find/stat message template!");
119                         goto abort;
120                 }
121
122                 Buf = NewStrBufPlain(NULL, statbuf.st_size + 1);
123                 if (StrBufReadBLOB(Buf, &fd, 1, statbuf.st_size, &Err) < 0) {
124                         char buf[SIZ];
125
126                         close(fd);
127
128                         snprintf(buf, SIZ,
129                                  "Cannot load template file %s [%s] "
130                                  "won't send notification\r\n",
131                                  file_funambol_msg,
132                                  Err);
133                         syslog(LOG_ERR, "%s", buf);
134                         // TODO: once an hour!
135                         CtdlAideMessage(
136                                 buf,
137                                 "External notifier: "
138                                 "unable to load message template!");
139                         goto abort;
140                 }
141                 close(fd);
142
143                 mimetype = GuessMimeByFilename(template, tlen);
144
145                 SOAPMessage = SmashStrBuf(&Buf);
146
147                 // Do substitutions
148                 help_subst(SOAPMessage, "^notifyuser", user);
149                 help_subst(SOAPMessage, "^syncsource",
150                            config.c_funambol_source);
151                 help_subst(SOAPMessage, "^msgid", msgid);
152                 help_subst(SOAPMessage, "^msgnum", msgnumstr);
153
154                 /* pass our list of custom made headers */
155
156                 contenttype=(char*) malloc(40+strlen(mimetype));
157                 sprintf(contenttype,
158                         "Content-Type: %s; charset=utf-8",
159                         mimetype);
160
161                 IO->HttpReq.headers = curl_slist_append(
162                         IO->HttpReq.headers,
163                         "SOAPAction: \"\"");
164
165                 IO->HttpReq.headers = curl_slist_append(
166                         IO->HttpReq.headers,
167                         contenttype);
168                 free(contenttype);
169                 contenttype = NULL;
170                 IO->HttpReq.headers = curl_slist_append(
171                         IO->HttpReq.headers,
172                         "Accept: application/soap+xml, "
173                         "application/mime, multipart/related, text/*");
174
175                 IO->HttpReq.headers = curl_slist_append(
176                         IO->HttpReq.headers,
177                         "Pragma: no-cache");
178
179                 /* Now specify the POST binary data */
180                 IO->HttpReq.PlainPostData = SOAPMessage;
181                 IO->HttpReq.PlainPostDataLen = strlen(SOAPMessage);
182         }
183         else {
184                 help_subst(remoteurl, "^notifyuser", user);
185                 help_subst(remoteurl, "^syncsource", config.c_funambol_source);
186                 help_subst(remoteurl, "^msgid", msgid);
187                 help_subst(remoteurl, "^msgnum", msgnumstr);
188
189                 IO->HttpReq.headers = curl_slist_append(
190                         IO->HttpReq.headers,
191                         "Accept: application/soap+xml, "
192                         "application/mime, multipart/related, text/*");
193
194                 IO->HttpReq.headers = curl_slist_append(
195                         IO->HttpReq.headers,
196                         "Pragma: no-cache");
197         }
198
199         Buf = NewStrBufPlain (remoteurl, -1);
200         ParseURL(&IO->ConnectMe, Buf, 80);
201         FreeStrBuf(&Buf); /* TODO: this is uncool... */
202         CurlPrepareURL(IO->ConnectMe);
203
204         chnd = IO->HttpReq.chnd;
205         OPT(SSL_VERIFYPEER, 0);
206         OPT(SSL_VERIFYHOST, 0);
207
208         QueueCurlContext(IO);
209
210         return 0;
211 abort:
212
213         if (contenttype) free(contenttype);
214         if (SOAPMessage != NULL) free(SOAPMessage);
215         if (buf != NULL) free(buf);
216         FreeStrBuf (&ReplyBuf);
217         return 1;
218 }
219
220
221 eNextState EvaluateResult(AsyncIO *IO)
222 {
223
224         if (IO->HttpReq.httpcode != 200) {
225                 StrBuf *ErrMsg;
226
227                 syslog(LOG_ALERT, "libcurl error %ld: %s\n",
228                               IO->HttpReq.httpcode,
229                               IO->HttpReq.errdesc);
230
231                 ErrMsg = NewStrBufPlain(
232                         HKEY("Error sending your Notification\n"));
233                 StrBufAppendPrintf(ErrMsg, "\nlibcurl error %ld: \n\t\t%s\n",
234                                    IO->HttpReq.httpcode,
235                                    IO->HttpReq.errdesc);
236
237                 StrBufAppendBufPlain(ErrMsg,
238                                      HKEY("\nWas Trying to send: \n"),
239                                      0);
240
241                 StrBufAppendBufPlain(ErrMsg, IO->ConnectMe->PlainUrl, -1, 0);
242                 if (IO->HttpReq.PlainPostDataLen > 0) {
243                         StrBufAppendBufPlain(
244                                 ErrMsg,
245                                 HKEY("\nThe Post document was: \n"),
246                                 0);
247                         StrBufAppendBufPlain(ErrMsg,
248                                              IO->HttpReq.PlainPostData,
249                                              IO->HttpReq.PlainPostDataLen, 0);
250                         StrBufAppendBufPlain(ErrMsg, HKEY("\n\n"), 0);
251                 }
252                 if (StrLength(IO->HttpReq.ReplyData) > 0) {
253                         StrBufAppendBufPlain(
254                                 ErrMsg,
255                                 HKEY("\n\nThe Serverreply was: \n\n"),
256                                 0);
257                         StrBufAppendBuf(ErrMsg, IO->HttpReq.ReplyData, 0);
258                 }
259                 else
260                         StrBufAppendBufPlain(
261                                 ErrMsg,
262                                 HKEY("\n\nThere was no Serverreply.\n\n"),
263                                 0);
264                 ///ExtNotify_PutErrorMessage(Ctx, ErrMsg);
265                 CtdlAideMessage(ChrPtr(ErrMsg),
266                                 "External notifier: "
267                                 "unable to contact notification host!");
268                 FreeStrBuf(&ErrMsg);
269         }
270
271         syslog(LOG_DEBUG, "Funambol notified\n");
272 /*
273         while ((Ctx.NotifyHostList != NULL) && (Ctx.NotifyHostList[i] != NULL))
274                 FreeStrBuf(&Ctx.NotifyHostList[i]);
275
276         if (Ctx.NotifyErrors != NULL)
277         {
278                 long len;
279                 const char *Key;
280                 HashPos *It;
281                 void *vErr;
282                 StrBuf *ErrMsg;
283
284                 It = GetNewHashPos(Ctx.NotifyErrors, 0);
285                 while (GetNextHashPos(Ctx.NotifyErrors,
286                 It, &len, &Key, &vErr) &&
287                        (vErr != NULL)) {
288                         ErrMsg = (StrBuf*) vErr;
289                         quickie_message("Citadel", NULL, NULL,
290                         AIDEROOM, ChrPtr(ErrMsg), FMT_FIXED,
291                         "Failed to notify external service about inbound mail");
292                 }
293
294                 DeleteHashPos(&It);
295                 DeleteHash(&Ctx.NotifyErrors);
296         }
297 */
298
299 ////    curl_slist_free_all (headers);
300 ///     curl_easy_cleanup(curl);
301         ///if (contenttype) free(contenttype);
302         ///if (SOAPMessage != NULL) free(SOAPMessage);
303         ///if (buf != NULL) free(buf);
304         ///FreeStrBuf (&ReplyBuf);
305         return eTerminateConnection;
306 }
307
308 eNextState ExtNotifyTerminateDB(AsyncIO *IO)
309 {
310         free(IO);
311         return eAbort;
312 }
313 eNextState ExtNotifyTerminate(AsyncIO *IO)
314 {
315         free(IO);
316         return eAbort;
317 }
318 eNextState ExtNotifyShutdownAbort(AsyncIO *IO)
319 {
320         free(IO);
321         return eAbort;
322 }