File: CurlDownloader.cpp

package info (click to toggle)
pinot 1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 6,308 kB
  • sloc: cpp: 39,057; sh: 10,481; ansic: 4,174; makefile: 612; xml: 372
file content (311 lines) | stat: -rw-r--r-- 7,787 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/*
 *  Copyright 2005-2009 Fabrice Colin
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdarg.h>
#ifdef HAVE_REGEX_H
#include <regex.h>
#endif
#include <stdlib.h>
#include <iostream>

#include <curl/curl.h>

#include "Url.h"
#include "CurlDownloader.h"

using namespace std;

struct ContentInfo
{
	char *m_pContent;
	size_t m_contentLen;
	string m_lastModified;
};

static void freeContentInfo(struct ContentInfo *pInfo)
{
	if (pInfo == NULL)
	{
		return;
	}

	if (pInfo->m_pContent != NULL)
	{
		free(pInfo->m_pContent);
		pInfo->m_pContent = NULL;
		pInfo->m_contentLen = 0;
	}
}

static size_t writeCallback(void *pData, size_t dataSize, size_t elementsCount, void *pStream)
{
	ContentInfo *pInfo = NULL;
	size_t totalSize = elementsCount * dataSize;

	if (pStream == NULL)
	{
		return 0;
	}
	pInfo = (ContentInfo *)pStream;

	char *pNewContent = (char*)realloc(pInfo->m_pContent, pInfo->m_contentLen + totalSize + 1);
	if (pNewContent == NULL)
	{
#ifdef DEBUG
		clog << "writeCallback: failed to enlarge buffer" << endl;
#endif
		freeContentInfo(pInfo);
		return 0;
	}

	pInfo->m_pContent = pNewContent;
	memcpy(pInfo->m_pContent + pInfo->m_contentLen, pData, totalSize);
	pInfo->m_contentLen += totalSize;
	pInfo->m_pContent[pInfo->m_contentLen] = '\0';

	if (totalSize < strlen((const char*)pData))
	{
		void *pBadChar = NULL;

		// There's a NULL character in the buffer ? Replace it
		while ((pBadChar = memchr((void*)pInfo->m_pContent, '\0', pInfo->m_contentLen)) != NULL)
		{
			((char*)pBadChar)[0] = ' ';
#ifdef DEBUG
			clog << "writeCallback: bad character" << endl;
#endif
		}
	}

	return totalSize;
}

static size_t headerCallback(void *pData, size_t dataSize, size_t elementsCount, void *pStream)
{
	ContentInfo *pInfo = NULL;
	size_t totalSize = elementsCount * dataSize;

	if ((pStream == NULL) ||
		(pData == NULL) ||
		(totalSize == 0))
	{
		return 0;
	}
	pInfo = (ContentInfo *)pStream;

	string header((const char*)pData, totalSize);

	string::size_type pos = header.find("Last-Modified: ");
	if (pos != string::npos)
	{
		pInfo->m_lastModified = header.substr(15);
#ifdef DEBUG
		clog << "headerCallback: Last-Modified " << pInfo->m_lastModified << endl;
#endif
	}

	return totalSize;
}

unsigned int CurlDownloader::m_initialized = 0;

CurlDownloader::CurlDownloader() :
	DownloaderInterface()
{
	if (m_initialized == 0)
	{
		// Initialize
		curl_global_init(CURL_GLOBAL_ALL);

		++m_initialized;
	}
}

CurlDownloader::~CurlDownloader()
{
	--m_initialized;
	if (m_initialized == 0)
	{
		// Shutdown
		curl_global_cleanup();
	}
}

//
// Implementation of DownloaderInterface
//

/// Retrieves the specified document; NULL if error.
Document *CurlDownloader::retrieveUrl(const DocumentInfo &docInfo)
{
	Document *pDocument = NULL;
	string url(Url::escapeUrl(docInfo.getLocation()));
	unsigned int redirectionsCount = 0;

	if (url.empty() == true)
	{
#ifdef DEBUG
		clog << "CurlDownloader::retrieveUrl: no URL specified !" << endl;
#endif
		return NULL;
	}

	// Create a session
	CURL *pCurlHandler = curl_easy_init();
	if (pCurlHandler != NULL)
	{
		ContentInfo *pContentInfo = new ContentInfo;

		pContentInfo->m_pContent = NULL;
		pContentInfo->m_contentLen = 0;

		curl_easy_setopt(pCurlHandler, CURLOPT_AUTOREFERER, 1);
		curl_easy_setopt(pCurlHandler, CURLOPT_FOLLOWLOCATION, 1);
		curl_easy_setopt(pCurlHandler, CURLOPT_MAXREDIRS, 10);
		curl_easy_setopt(pCurlHandler, CURLOPT_USERAGENT, m_userAgent.c_str());
		curl_easy_setopt(pCurlHandler, CURLOPT_NOSIGNAL, (long)1);
		curl_easy_setopt(pCurlHandler, CURLOPT_TIMEOUT, (long)m_timeout);
#ifndef DEBUG
		curl_easy_setopt(pCurlHandler, CURLOPT_NOPROGRESS, 1);
#endif
		curl_easy_setopt(pCurlHandler, CURLOPT_WRITEFUNCTION, writeCallback);
		curl_easy_setopt(pCurlHandler, CURLOPT_WRITEDATA, pContentInfo);
		curl_easy_setopt(pCurlHandler, CURLOPT_HEADERFUNCTION, headerCallback);
		curl_easy_setopt(pCurlHandler, CURLOPT_HEADERDATA, pContentInfo);

		// Is a proxy defined ?
		// Curl automatically checks and makes use of the *_proxy environment variables 
		if ((m_proxyAddress.empty() == false) &&
			(m_proxyPort > 0))
		{
			curl_proxytype proxyType = CURLPROXY_HTTP;

			curl_easy_setopt(pCurlHandler, CURLOPT_PROXY, m_proxyAddress.c_str());
			curl_easy_setopt(pCurlHandler, CURLOPT_PROXYPORT, m_proxyPort);
			// Type defaults to HTTP
			if (m_proxyType.empty() == false)
			{
				if (m_proxyType == "SOCKS4")
				{
					proxyType = CURLPROXY_SOCKS4;
				}
				else if (m_proxyType == "SOCKS5")
				{
					proxyType = CURLPROXY_SOCKS5;
				}
			}
			curl_easy_setopt(pCurlHandler, CURLOPT_PROXYTYPE, proxyType);
		}

#ifdef DEBUG
		clog << "CurlDownloader::retrieveUrl: URL is " << url << endl;
#endif
		while (redirectionsCount < 10)
		{
			curl_easy_setopt(pCurlHandler, CURLOPT_URL, url.c_str());

			if (m_method == "POST")
			{
				curl_easy_setopt(pCurlHandler, CURLOPT_POST, 1);
				if (m_postFields.empty() == false)
				{
					curl_easy_setopt(pCurlHandler, CURLOPT_POSTFIELDS, m_postFields.c_str());
				}
			}

			CURLcode res = curl_easy_perform(pCurlHandler);
			if ((res == CURLE_OK) &&
				(pContentInfo->m_pContent != NULL) &&
				(pContentInfo->m_contentLen > 0))
			{
				char *pContentType = NULL;

				// Copy the document content
				pDocument = new Document(docInfo);
				pDocument->setData(pContentInfo->m_pContent, pContentInfo->m_contentLen);
				pDocument->setLocation(url);
				pDocument->setSize((off_t )pContentInfo->m_contentLen);

				// What's the Content-Type ?
				res = curl_easy_getinfo(pCurlHandler, CURLINFO_CONTENT_TYPE, &pContentType);
				if ((res == CURLE_OK) &&
					(pContentType != NULL))
				{
					pDocument->setType(pContentType);
				}

				// The Last-Modified date ?
				if (pContentInfo->m_lastModified.empty() == false)
				{
					pDocument->setTimestamp(pContentInfo->m_lastModified);
				}

#ifdef HAVE_REGEX_H
				regex_t refreshRegex;
				regmatch_t pMatches[2];

				// Any REFRESH META tag ?
				// Look for <meta http-equiv="refresh" content="SECS;url=URL">
				if (regcomp(&refreshRegex,
					"<meta http-equiv=\"refresh\" content=\"([0-9]*);url=([^\"]*)\">"
					REG_EXTENDED|REG_ICASE) == 0)
				{
					if (regexec(&refreshRegex, pContentInfo->m_pContent, 2,
						pMatches, REG_NOTBOL|REG_NOTEOL) == 0)
					{
						url = pMatches[1];
#ifdef DEBUG
						clog << "CurlDownloader::retrieveUrl: redirected to URL " << url << endl;
#endif
						delete pDocument;
						pDocument = NULL;
						freeContentInfo(pContentInfo);
						++redirectionsCount;
						continue;
					}
#ifdef DEBUG
					else clog << "CurlDownloader::retrieveUrl: no REFRESH META tag" << endl;
#endif

					regfree(&refreshRegex);
				}
#ifdef DEBUG
				else clog << "CurlDownloader::retrieveUrl: couldn't look for a REFRESH META tag" << endl;
#endif
#endif
			}
			else
			{
				clog << "Couldn't download " << url << ": " << curl_easy_strerror(res) << endl;
			}

			break;
		}

		freeContentInfo(pContentInfo);
		delete pContentInfo;

		// Cleanup
		curl_easy_cleanup(pCurlHandler);
	}

	return pDocument;
}