don't call curl_multi_add_handle() from outside of the event queue
[citadel.git] / citadel / modules / urldeshortener / serv_expand_shorter_urls.c
1
2 /*
3  *
4  * Copyright (c) 1998-2009 by the citadel.org team
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 3 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "sysdep.h"
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <stdio.h>
25 #include <termios.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <pwd.h>
29 #include <errno.h>
30 #include <sys/types.h>
31 #include <syslog.h>
32
33 #if TIME_WITH_SYS_TIME
34 # include <sys/time.h>
35 # include <time.h>
36 #else
37 # if HAVE_SYS_TIME_H
38 #  include <sys/time.h>
39 # else
40 #  include <time.h>
41 # endif
42 #endif
43 #include <sys/wait.h>
44 #include <ctype.h>
45 #include <string.h>
46 #include <limits.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
50 #include <assert.h>
51
52 #include <libcitadel.h>
53 #include "citadel.h"
54 #include "server.h"
55 #include "citserver.h"
56 #include "support.h"
57 #include "config.h"
58 #include "control.h"
59 #include "user_ops.h"
60 #include "database.h"
61 #include "msgbase.h"
62 #include "internet_addressing.h"
63 #include "genstamp.h"
64 #include "domain.h"
65 #include "ctdl_module.h"
66 #include "locate_host.h"
67 #include "citadel_dirs.h"
68
69 #include "event_client.h"
70
71 HashList *UrlShorteners = NULL;
72
73 size_t GetLocationString( void *ptr, size_t size, size_t nmemb, void *userdata)
74 {
75 #define LOCATION "location"
76         if (strncasecmp((char*)ptr, LOCATION, sizeof(LOCATION) - 1) == 0)
77         {
78                 StrBuf *pURL = (StrBuf*) userdata;
79                 char *pch = (char*) ptr;
80                 char *pche;
81                 
82                 pche = pch + (size * nmemb);
83                 pch += sizeof(LOCATION);
84                 
85                 while (isspace(*pch) || (*pch == ':'))
86                         pch ++;
87
88                 while (isspace(*pche) || (*pche == '\0'))
89                         pche--;
90                 
91                 FlushStrBuf(pURL);
92                 StrBufPlain(pURL, pch, pche - pch + 1); 
93         }
94         return size * nmemb;
95 }
96
97 eNextState TerminateLookupUrl(AsyncIO *IO)
98 {
99 //TOOD
100         return eAbort;
101 }
102 eNextState LookupUrlResult(AsyncIO *IO)
103 {
104         return eTerminateConnection; /// /TODO
105 }
106
107 int LookupUrl(StrBuf *ShorterUrlStr)
108 {
109         CURLcode sta;
110         int rc = 0;
111         CURL *chnd;
112         AsyncIO *IO;
113
114
115         IO = (AsyncIO*) malloc(sizeof(AsyncIO));
116         memset(IO, 0, sizeof(AsyncIO));
117         IO->CitContext = CloneContext(CC);
118
119         ParseURL(&IO->ConnectMe, ShorterUrlStr, 80);
120         CurlPrepareURL(IO->ConnectMe);
121         if (! evcurl_init(IO, 
122 //                        Ctx, 
123                           NULL,
124                           "Citadel RSS ShorterURL Expander",
125                           LookupUrlResult, 
126                           TerminateLookupUrl))
127         {
128                 syslog(LOG_ALERT, "Unable to initialize libcurl.\n");
129                 goto shutdown;
130         }
131         chnd = IO->HttpReq.chnd;
132
133         OPT(SSL_VERIFYPEER, 0);
134         OPT(SSL_VERIFYHOST, 0);
135         OPT(FOLLOWLOCATION, 10);
136 #ifdef CURLOPT_HTTP_CONTENT_DECODING
137         OPT(HTTP_CONTENT_DECODING, 1);
138         OPT(ENCODING, "");
139 #endif 
140         OPT(HEADERFUNCTION , GetLocationString);
141         OPT(WRITEHEADER, ShorterUrlStr);
142
143
144         if (server_shutting_down)
145                 goto shutdown ;
146
147         QueueCurlContext(IO);
148
149 shutdown:
150
151         return rc;
152
153 }
154
155
156
157 void CrawlMessageForShorterUrls(HashList *pUrls, StrBuf *Message)
158 {
159         int nHits = 0;
160         void *pv;
161         int nShorter = 0;
162         const char *pch;
163         const char *pUrl;
164         ConstStr *pCUrl;
165
166         while (GetHash(UrlShorteners, IKEY(nShorter), &pv))
167         {
168                 nShorter++;
169                 pch = ChrPtr(Message);
170                 pUrl = strstr(pch, ChrPtr((StrBuf*)pv));
171                 while ((pUrl != NULL) && (nHits < 99))
172                 {
173                         pCUrl = malloc(sizeof(ConstStr));
174
175                         pCUrl->Key = pUrl;
176                         pch = pUrl + StrLength((StrBuf*)pv);
177                         while (isalnum(*pch)||(*pch == '-')||(*pch == '/'))
178                                 pch++;
179                         pCUrl->len = pch - pCUrl->Key;
180
181                         Put(pUrls, IKEY(nHits), pCUrl, NULL);
182                         nHits ++;
183                         pUrl = strstr(pch, ChrPtr((StrBuf*)pv));
184                 }
185         }
186 }
187
188 int SortConstStrByPosition(const void *Item1, const void *Item2)
189 {
190         const ConstStr *p1, *p2;
191         p1 = (const ConstStr*) Item1;
192         p2 = (const ConstStr*) Item2;
193         if (p1->Key == p2->Key)
194                 return 0;
195         if (p1->Key > p2->Key)
196                 return 1;
197         return -1;
198 }
199
200 HashList *GetShorterUrls(StrBuf *Message)
201 {
202         HashList *pUrls;
203         /* we just suspect URL shorteners to be inside of feeds from twitter
204          * or other short content messages, so don't crawl through real blogs.
205          */
206         if (StrLength(Message) > 500)
207                 return NULL;
208
209         pUrls = NewHash(1, Flathash);
210         CrawlMessageForShorterUrls(pUrls, Message);
211
212         if (GetCount(pUrls) > 0)
213                 return pUrls;
214         else 
215                 return NULL;
216
217 }
218
219 void ExpandShortUrls(StrBuf *Message, HashList *pUrls, int Callback)
220 {
221         StrBuf *Shadow;
222         ConstStr *pCUrl;
223         const char *pch;
224         const char *pche;
225
226         StrBuf *ShorterUrlStr;
227         HashPos *Pos;
228         const char *Key;
229         void *pv;
230         long len;
231         
232         Shadow = NewStrBufPlain(NULL, StrLength(Message));
233         SortByPayload (pUrls, SortConstStrByPosition);
234                 
235         ShorterUrlStr = NewStrBufPlain(NULL, StrLength(Message));
236                 
237         pch = ChrPtr(Message);
238         pche = pch + StrLength(Message);
239         Pos = GetNewHashPos(pUrls, 1);
240         while (GetNextHashPos(pUrls, Pos, &len, &Key, &pv))
241         {
242                 pCUrl = (ConstStr*) pv;
243
244                 if (pch != pCUrl->Key)
245                         StrBufAppendBufPlain(Shadow, pch, pCUrl->Key - pch, 0);
246                         
247                 StrBufPlain(ShorterUrlStr, CKEY(*pCUrl));
248                 if (LookupUrl(ShorterUrlStr))
249                 {
250                         StrBufAppendBufPlain(Shadow, HKEY("<a href=\""), 0);
251                         StrBufAppendBuf(Shadow, ShorterUrlStr, 0);
252                         StrBufAppendBufPlain(Shadow, HKEY("\">"), 0);
253                         StrBufAppendBuf(Shadow, ShorterUrlStr, 0);
254                         StrBufAppendBufPlain(Shadow, HKEY("["), 0);
255                         StrBufAppendBufPlain(Shadow, pCUrl->Key, pCUrl->len, 0);
256                         StrBufAppendBufPlain(Shadow, HKEY("]</a>"), 0);
257                 }
258                 else
259                 {
260                         StrBufAppendBufPlain(Shadow, HKEY("<a href=\""), 0);
261                         StrBufAppendBufPlain(Shadow, pCUrl->Key, pCUrl->len, 0);
262                         StrBufAppendBufPlain(Shadow, HKEY("\">"), 0);
263                         StrBufAppendBufPlain(Shadow, pCUrl->Key, pCUrl->len, 0);
264                         StrBufAppendBufPlain(Shadow, HKEY("</a>"), 0);
265                 }
266                 pch = pCUrl->Key + pCUrl->len + 1;
267
268         }
269         if (pch < pche)
270                 StrBufAppendBufPlain(Shadow, pch, pche - pch, 0);
271         FlushStrBuf(Message);
272         StrBufAppendBuf(Message, Shadow, 0);
273
274         FreeStrBuf(&ShorterUrlStr);
275         FreeStrBuf(&Shadow);
276         DeleteHashPos(&Pos);
277         
278
279         DeleteHash(&pUrls);
280 }
281
282 void LoadUrlShorteners(void)
283 {
284         int i = 0;
285         int fd;
286         const char *POS = NULL;
287         const char *Err = NULL;
288         StrBuf *Content, *Line;
289
290
291         UrlShorteners = NewHash(0, Flathash);
292
293         fd = open(file_citadel_urlshorteners, 0);
294
295         if (fd != 0)
296         {
297                 Content = NewStrBufPlain(NULL, SIZ);
298                 Line = NewStrBuf();
299                 while (POS != StrBufNOTNULL)
300                 {
301                         StrBufTCP_read_buffered_line_fast (Line, Content, &POS, &fd, 1, 1, &Err);
302                         StrBufTrim(Line);
303                         if ((*ChrPtr(Line) != '#') && (StrLength(Line) > 0))
304                         {
305                                 Put(UrlShorteners, IKEY(i), Line, HFreeStrBuf);
306                                 i++;
307                                 Line = NewStrBuf();
308                         }
309                         else
310                                 FlushStrBuf(Line);
311                         if (POS == NULL)
312                                 POS = StrBufNOTNULL;
313                 }
314                 FreeStrBuf(&Line);
315                 FreeStrBuf(&Content);
316         }
317         close(fd);
318 }
319
320 void shorter_url_cleanup(void)
321 {
322         DeleteHash(&UrlShorteners);
323 }
324
325
326 CTDL_MODULE_INIT(urldeshortener)
327 {
328         if (threading)
329         {
330                 syslog(LOG_INFO, "%s\n", curl_version());
331         }
332         else 
333         {
334                 LoadUrlShorteners ();
335                 CtdlRegisterCleanupHook(shorter_url_cleanup);
336         }
337         return "UrlShortener";
338 }