don't call curl_multi_add_handle() from outside of the event queue
[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 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 <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 "citadel_dirs.h"
40 #include "clientsocket.h"
41 #include "sysdep.h"
42 #include "config.h"
43 #include "sysdep_decls.h"
44 #include "msgbase.h"
45 #include "ctdl_module.h"
46
47 #include "event_client.h"
48 #include "extnotify.h"
49
50 eNextState EvaluateResult(AsyncIO *IO);
51 eNextState ExtNotifyTerminate(AsyncIO *IO);
52
53 /*
54 * \brief Sends a message to the Funambol server notifying 
55 * of new mail for a user
56 * Returns 0 if unsuccessful
57 */
58 int notify_http_server(char *remoteurl, 
59                        const char* template, long tlen, 
60                        char *user,
61                        char *msgid, 
62                        long MsgNum, 
63                        NotifyContext *Ctx) 
64 {
65         CURLcode sta;
66         char msgnumstr[128];
67         char *buf = NULL;
68         char *SOAPMessage = NULL;
69         char *contenttype = NULL;
70         StrBuf *ReplyBuf;
71         StrBuf *Buf;
72         CURL *chnd;
73         AsyncIO *IO;
74
75         IO = (AsyncIO*) malloc(sizeof(AsyncIO));
76         memset(IO, 0, sizeof(AsyncIO));
77         IO->CitContext = CloneContext(CC);
78
79         snprintf(msgnumstr, 128, "%ld", MsgNum);
80
81         if (tlen > 0) {
82                 /* Load the template message. Get mallocs done too */
83                 FILE *Ftemplate = NULL;
84                 const char *mimetype;
85
86                 Ftemplate = fopen(template, "r");
87                 if (Ftemplate == NULL) {
88                         char buf[SIZ];
89
90                         snprintf(buf, SIZ, 
91                                  "Cannot load template file %s [%s]won't send notification\r\n", 
92                                  file_funambol_msg, strerror(errno));
93                         syslog(LOG_ERR, "%s", buf);
94
95                         CtdlAideMessage(buf, "External notifier unable to find message template!");
96                         goto abort;
97                 }
98                 mimetype = GuessMimeByFilename(template, tlen);
99
100                 buf = malloc(SIZ);
101                 memset(buf, 0, SIZ);
102                 SOAPMessage = malloc(3072);
103                 memset(SOAPMessage, 0, 3072);
104         
105                 while(fgets(buf, SIZ, Ftemplate) != NULL) {
106                         strcat(SOAPMessage, buf);
107                 }
108                 fclose(Ftemplate);
109         
110                 if (strlen(SOAPMessage) < 0) {
111                         char buf[SIZ];
112
113                         snprintf(buf, SIZ, 
114                                  "Cannot load template file %s; won't send notification\r\n", 
115                                  file_funambol_msg);
116                         syslog(LOG_ERR, "%s", buf);
117
118                         CtdlAideMessage(buf, "External notifier unable to load message template!");
119                         goto abort;
120                 }
121                 // Do substitutions
122                 help_subst(SOAPMessage, "^notifyuser", user);
123                 help_subst(SOAPMessage, "^syncsource", config.c_funambol_source);
124                 help_subst(SOAPMessage, "^msgid", msgid);
125                 help_subst(SOAPMessage, "^msgnum", msgnumstr);
126
127                 /* pass our list of custom made headers */
128
129                 contenttype=(char*) malloc(40+strlen(mimetype));
130                 sprintf(contenttype,"Content-Type: %s; charset=utf-8", mimetype);
131
132                 IO->HttpReq.headers = curl_slist_append(IO->HttpReq.headers, "SOAPAction: \"\"");
133                 IO->HttpReq.headers = curl_slist_append(IO->HttpReq.headers, contenttype);
134                 IO->HttpReq.headers = curl_slist_append(IO->HttpReq.headers, "Accept: application/soap+xml, application/mime, multipart/related, text/*");
135                 IO->HttpReq.headers = curl_slist_append(IO->HttpReq.headers, "Pragma: no-cache");
136
137                 /* Now specify the POST binary data */
138                 IO->HttpReq.PlainPostData = SOAPMessage;
139                 IO->HttpReq.PlainPostDataLen = strlen(SOAPMessage);
140         }
141         else {
142                 help_subst(remoteurl, "^notifyuser", user);
143                 help_subst(remoteurl, "^syncsource", config.c_funambol_source);
144                 help_subst(remoteurl, "^msgid", msgid);
145                 help_subst(remoteurl, "^msgnum", msgnumstr);
146                 IO->HttpReq.headers = curl_slist_append(IO->HttpReq.headers, "Accept: application/soap+xml, application/mime, multipart/related, text/*");
147                 IO->HttpReq.headers = curl_slist_append(IO->HttpReq.headers, "Pragma: no-cache");
148         }
149
150         Buf = NewStrBufPlain (remoteurl, -1);
151         ParseURL(&IO->ConnectMe, Buf, 80);
152         FreeStrBuf(&Buf); /* TODO: this is uncool... */
153         CurlPrepareURL(IO->ConnectMe);
154         if (! evcurl_init(IO, 
155 //                        Ctx, 
156                           NULL,
157                           "Citadel ExtNotify",
158                           EvaluateResult, 
159                           ExtNotifyTerminate))
160         {
161                 syslog(LOG_ALERT, "Unable to initialize libcurl.\n");
162                 goto abort;
163         }
164         chnd = IO->HttpReq.chnd;
165         OPT(SSL_VERIFYPEER, 0);
166         OPT(SSL_VERIFYHOST, 0);
167 /*
168         ReplyBuf = NewStrBuf();
169         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
170         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
171 */
172         if (
173                 (!IsEmptyStr(config.c_ip_addr))
174                 && (strcmp(config.c_ip_addr, "*"))
175                 && (strcmp(config.c_ip_addr, "::"))
176                 && (strcmp(config.c_ip_addr, "0.0.0.0"))
177         ) {
178                 OPT(INTERFACE, config.c_ip_addr);
179         }
180
181         QueueCurlContext(IO);
182
183         return 0;
184 abort:
185 ///     curl_slist_free_all (headers);
186 ///     curl_easy_cleanup(curl);
187         if (contenttype) free(contenttype);
188         if (SOAPMessage != NULL) free(SOAPMessage);
189         if (buf != NULL) free(buf);
190         FreeStrBuf (&ReplyBuf);
191         return 1;
192 }
193
194
195 eNextState EvaluateResult(AsyncIO *IO)
196 {
197
198         if (IO->HttpReq.httpcode != 200) {
199                 StrBuf *ErrMsg;
200
201                 syslog(LOG_ALERT, "libcurl error %ld: %s\n", 
202                               IO->HttpReq.httpcode, 
203                               IO->HttpReq.errdesc);
204
205                 ErrMsg = NewStrBufPlain(HKEY("Error sending your Notification\n"));
206                 StrBufAppendPrintf(ErrMsg, "\nlibcurl error %ld: \n\t\t%s\n", 
207                                    IO->HttpReq.httpcode, 
208                                    IO->HttpReq.errdesc);
209                 StrBufAppendBufPlain(ErrMsg, HKEY("\nWas Trying to send: \n"), 0);
210                 StrBufAppendBufPlain(ErrMsg, IO->ConnectMe->PlainUrl, -1, 0);
211                 if (IO->HttpReq.PlainPostDataLen > 0) {
212                         StrBufAppendBufPlain(ErrMsg, HKEY("\nThe Post document was: \n"), 0);
213                         StrBufAppendBufPlain(ErrMsg, 
214                                              IO->HttpReq.PlainPostData, 
215                                              IO->HttpReq.PlainPostDataLen, 0);
216                         StrBufAppendBufPlain(ErrMsg, HKEY("\n\n"), 0);                  
217                 }
218                 if (StrLength(IO->HttpReq.ReplyData) > 0) {                     
219                         StrBufAppendBufPlain(ErrMsg, HKEY("\n\nThe Serverreply was: \n\n"), 0);
220                         StrBufAppendBuf(ErrMsg, IO->HttpReq.ReplyData, 0);
221                 }
222                 else 
223                         StrBufAppendBufPlain(ErrMsg, HKEY("\n\nThere was no Serverreply.\n\n"), 0);
224                 ///ExtNotify_PutErrorMessage(Ctx, ErrMsg);
225                 CtdlAideMessage(ChrPtr(ErrMsg), "External notifier unable to load message template!");
226         }
227
228         syslog(LOG_DEBUG, "Funambol notified\n");
229 /*
230         while ((Ctx.NotifyHostList != NULL) && (Ctx.NotifyHostList[i] != NULL))
231                 FreeStrBuf(&Ctx.NotifyHostList[i]);
232
233         if (Ctx.NotifyErrors != NULL)
234         {
235                 long len;
236                 const char *Key;
237                 HashPos *It;
238                 void *vErr;
239                 StrBuf *ErrMsg;
240
241                 It = GetNewHashPos(Ctx.NotifyErrors, 0);
242                 while (GetNextHashPos(Ctx.NotifyErrors, It, &len, &Key, &vErr) && 
243                        (vErr != NULL)) {
244                         ErrMsg = (StrBuf*) vErr;
245                         quickie_message("Citadel", NULL, NULL, AIDEROOM, ChrPtr(ErrMsg), FMT_FIXED, 
246                                         "Failed to notify external service about inbound mail");
247                 }
248
249                 DeleteHashPos(&It);
250                 DeleteHash(&Ctx.NotifyErrors);
251         }
252 */
253
254 ////    curl_slist_free_all (headers);
255 ///     curl_easy_cleanup(curl);
256         ///if (contenttype) free(contenttype);
257         ///if (SOAPMessage != NULL) free(SOAPMessage);
258         ///if (buf != NULL) free(buf);
259         ///FreeStrBuf (&ReplyBuf);
260         return 0;
261 }
262
263 eNextState ExtNotifyTerminate(AsyncIO *IO)
264 {
265         free(IO);
266         return eAbort;
267 }