Move all header parsing logic from CurlFile::CReadState::HeaderCallback to CHttpHeade...
[vuplus_xbmc] / xbmc / filesystem / CurlFile.cpp
1 /*
2  *      Copyright (C) 2005-2013 Team XBMC
3  *      http://xbmc.org
4  *
5  *  This Program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2, or (at your option)
8  *  any later version.
9  *
10  *  This Program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with XBMC; see the file COPYING.  If not, see
17  *  <http://www.gnu.org/licenses/>.
18  *
19  */
20
21 #include "CurlFile.h"
22 #include "utils/URIUtils.h"
23 #include "Util.h"
24 #include "URL.h"
25 #include "settings/AdvancedSettings.h"
26 #include "settings/Settings.h"
27 #include "File.h"
28
29 #include <vector>
30 #include <climits>
31
32 #ifdef TARGET_POSIX
33 #include <errno.h>
34 #include <inttypes.h>
35 #include "../linux/XFileUtils.h"
36 #include "../linux/XTimeUtils.h"
37 #include "../linux/ConvUtils.h"
38 #endif
39
40 #include "DllLibCurl.h"
41 #include "ShoutcastFile.h"
42 #include "SpecialProtocol.h"
43 #include "utils/CharsetConverter.h"
44 #include "utils/log.h"
45 #include "utils/StringUtils.h"
46
47 using namespace XFILE;
48 using namespace XCURL;
49
50 #define XMIN(a,b) ((a)<(b)?(a):(b))
51 #define FITS_INT(a) (((a) <= INT_MAX) && ((a) >= INT_MIN))
52
53 #define dllselect select
54
55
56 curl_proxytype proxyType2CUrlProxyType[] = {
57   CURLPROXY_HTTP,
58   CURLPROXY_SOCKS4,
59   CURLPROXY_SOCKS4A,
60   CURLPROXY_SOCKS5,
61   CURLPROXY_SOCKS5_HOSTNAME,
62 };
63
64 // curl calls this routine to debug
65 extern "C" int debug_callback(CURL_HANDLE *handle, curl_infotype info, char *output, size_t size, void *data)
66 {
67   if (info == CURLINFO_DATA_IN || info == CURLINFO_DATA_OUT)
68     return 0;
69
70   if ((g_advancedSettings.m_extraLogLevels & LOGCURL) == 0)
71     return 0;
72
73   CStdString strLine;
74   strLine.append(output, size);
75   std::vector<std::string> vecLines;
76   StringUtils::Tokenize(strLine, vecLines, "\r\n");
77   std::vector<std::string>::const_iterator it = vecLines.begin();
78
79   char *infotype;
80   switch(info)
81   {
82     case CURLINFO_TEXT         : infotype = (char *) "TEXT: "; break;
83     case CURLINFO_HEADER_IN    : infotype = (char *) "HEADER_IN: "; break;
84     case CURLINFO_HEADER_OUT   : infotype = (char *) "HEADER_OUT: "; break;
85     case CURLINFO_SSL_DATA_IN  : infotype = (char *) "SSL_DATA_IN: "; break;
86     case CURLINFO_SSL_DATA_OUT : infotype = (char *) "SSL_DATA_OUT: "; break;
87     case CURLINFO_END          : infotype = (char *) "END: "; break;
88     default                    : infotype = (char *) ""; break;
89   }
90
91   while (it != vecLines.end())
92   {
93     CLog::Log(LOGDEBUG, "Curl::Debug - %s%s", infotype, (*it).c_str());
94     it++;
95   }
96   return 0;
97 }
98
99 /* curl calls this routine to get more data */
100 extern "C" size_t write_callback(char *buffer,
101                size_t size,
102                size_t nitems,
103                void *userp)
104 {
105   if(userp == NULL) return 0;
106
107   CCurlFile::CReadState *state = (CCurlFile::CReadState *)userp;
108   return state->WriteCallback(buffer, size, nitems);
109 }
110
111 extern "C" size_t read_callback(char *buffer,
112                size_t size,
113                size_t nitems,
114                void *userp)
115 {
116   if(userp == NULL) return 0;
117
118   CCurlFile::CReadState *state = (CCurlFile::CReadState *)userp;
119   return state->ReadCallback(buffer, size, nitems);
120 }
121
122 extern "C" size_t header_callback(void *ptr, size_t size, size_t nmemb, void *stream)
123 {
124   CCurlFile::CReadState *state = (CCurlFile::CReadState *)stream;
125   return state->HeaderCallback(ptr, size, nmemb);
126 }
127
128 /* fix for silly behavior of realloc */
129 static inline void* realloc_simple(void *ptr, size_t size)
130 {
131   void *ptr2 = realloc(ptr, size);
132   if(ptr && !ptr2 && size > 0)
133   {
134     free(ptr);
135     return NULL;
136   }
137   else
138     return ptr2;
139 }
140
141 size_t CCurlFile::CReadState::HeaderCallback(void *ptr, size_t size, size_t nmemb)
142 {
143   std::string inString;
144   // libcurl doc says that this info is not always \0 terminated
145   const char* strBuf = (const char*)ptr;
146   const size_t iSize = size * nmemb;
147   if (strBuf[iSize - 1] == 0)
148     inString.assign(strBuf, iSize - 1); // skip last char if it's zero
149   else
150     inString.append(strBuf, iSize);
151
152   m_httpheader.Parse(inString);
153
154   return iSize;
155 }
156
157 size_t CCurlFile::CReadState::ReadCallback(char *buffer, size_t size, size_t nitems)
158 {
159   if (m_fileSize == 0)
160     return 0;
161
162   if (m_filePos >= m_fileSize)
163   {
164     m_isPaused = true;
165     return CURL_READFUNC_PAUSE;
166   }
167
168   int64_t retSize = XMIN(m_fileSize - m_filePos, int64_t(nitems * size));
169   memcpy(buffer, m_readBuffer + m_filePos, retSize);
170   m_filePos += retSize;
171
172   return retSize;
173 }
174
175 size_t CCurlFile::CReadState::WriteCallback(char *buffer, size_t size, size_t nitems)
176 {
177   unsigned int amount = size * nitems;
178 //  CLog::Log(LOGDEBUG, "CCurlFile::WriteCallback (%p) with %i bytes, readsize = %i, writesize = %i", this, amount, m_buffer.getMaxReadSize(), m_buffer.getMaxWriteSize() - m_overflowSize);
179   if (m_overflowSize)
180   {
181     // we have our overflow buffer - first get rid of as much as we can
182     unsigned int maxWriteable = XMIN((unsigned int)m_buffer.getMaxWriteSize(), m_overflowSize);
183     if (maxWriteable)
184     {
185       if (!m_buffer.WriteData(m_overflowBuffer, maxWriteable))
186         CLog::Log(LOGERROR, "CCurlFile::WriteCallback - Unable to write to buffer - what's up?");
187       if (m_overflowSize > maxWriteable)
188       { // still have some more - copy it down
189         memmove(m_overflowBuffer, m_overflowBuffer + maxWriteable, m_overflowSize - maxWriteable);
190       }
191       m_overflowSize -= maxWriteable;
192     }
193   }
194   // ok, now copy the data into our ring buffer
195   unsigned int maxWriteable = XMIN((unsigned int)m_buffer.getMaxWriteSize(), amount);
196   if (maxWriteable)
197   {
198     if (!m_buffer.WriteData(buffer, maxWriteable))
199     {
200       CLog::Log(LOGERROR, "CCurlFile::WriteCallback - Unable to write to buffer with %i bytes - what's up?", maxWriteable);
201     }
202     else
203     {
204       amount -= maxWriteable;
205       buffer += maxWriteable;
206     }
207   }
208   if (amount)
209   {
210 //    CLog::Log(LOGDEBUG, "CCurlFile::WriteCallback(%p) not enough free space for %i bytes", (void*)this,  amount);
211
212     m_overflowBuffer = (char*)realloc_simple(m_overflowBuffer, amount + m_overflowSize);
213     if(m_overflowBuffer == NULL)
214     {
215       CLog::Log(LOGWARNING, "CCurlFile::WriteCallback - Failed to grow overflow buffer from %i bytes to %i bytes", m_overflowSize, amount + m_overflowSize);
216       return 0;
217     }
218     memcpy(m_overflowBuffer + m_overflowSize, buffer, amount);
219     m_overflowSize += amount;
220   }
221   return size * nitems;
222 }
223
224 CCurlFile::CReadState::CReadState()
225 {
226   m_easyHandle = NULL;
227   m_multiHandle = NULL;
228   m_overflowBuffer = NULL;
229   m_overflowSize = 0;
230   m_filePos = 0;
231   m_fileSize = 0;
232   m_bufferSize = 0;
233   m_cancelled = false;
234   m_bFirstLoop = true;
235   m_sendRange = true;
236   m_readBuffer = 0;
237   m_isPaused = false;
238   m_curlHeaderList = NULL;
239   m_curlAliasList = NULL;
240 }
241
242 CCurlFile::CReadState::~CReadState()
243 {
244   Disconnect();
245
246   if(m_easyHandle)
247     g_curlInterface.easy_release(&m_easyHandle, &m_multiHandle);
248 }
249
250 bool CCurlFile::CReadState::Seek(int64_t pos)
251 {
252   if(pos == m_filePos)
253     return true;
254
255   if(FITS_INT(pos - m_filePos) && m_buffer.SkipBytes((int)(pos - m_filePos)))
256   {
257     m_filePos = pos;
258     return true;
259   }
260
261   if(pos > m_filePos && pos < m_filePos + m_bufferSize)
262   {
263     int len = m_buffer.getMaxReadSize();
264     m_filePos += len;
265     m_buffer.SkipBytes(len);
266     if(!FillBuffer(m_bufferSize))
267     {
268       if(!m_buffer.SkipBytes(-len))
269         CLog::Log(LOGERROR, "%s - Failed to restore position after failed fill", __FUNCTION__);
270       else
271         m_filePos -= len;
272       return false;
273     }
274
275     if(!FITS_INT(pos - m_filePos) || !m_buffer.SkipBytes((int)(pos - m_filePos)))
276     {
277       CLog::Log(LOGERROR, "%s - Failed to skip to position after having filled buffer", __FUNCTION__);
278       if(!m_buffer.SkipBytes(-len))
279         CLog::Log(LOGERROR, "%s - Failed to restore position after failed seek", __FUNCTION__);
280       else
281         m_filePos -= len;
282       return false;
283     }
284     m_filePos = pos;
285     return true;
286   }
287   return false;
288 }
289
290 void CCurlFile::CReadState::SetResume(void)
291 {
292   /*
293    * Explicitly set RANGE header when filepos=0 as some http servers require us to always send the range
294    * request header. If we don't the server may provide different content causing seeking to fail.
295    * This only affects HTTP-like items, for FTP it's a null operation.
296    */
297   if (m_sendRange && m_filePos == 0)
298     g_curlInterface.easy_setopt(m_easyHandle, CURLOPT_RANGE, "0-");
299   else
300   {
301     g_curlInterface.easy_setopt(m_easyHandle, CURLOPT_RANGE, NULL);
302     m_sendRange = false;
303   }
304
305   g_curlInterface.easy_setopt(m_easyHandle, CURLOPT_RESUME_FROM_LARGE, m_filePos);
306 }
307
308 long CCurlFile::CReadState::Connect(unsigned int size)
309 {
310   if (m_filePos != 0)
311     CLog::Log(LOGDEBUG,"CurlFile::CReadState::Connect - Resume from position %"PRId64, m_filePos);
312
313   SetResume();
314   g_curlInterface.multi_add_handle(m_multiHandle, m_easyHandle);
315
316   m_bufferSize = size;
317   m_buffer.Destroy();
318   m_buffer.Create(size * 3);
319   m_httpheader.Clear();
320
321   // read some data in to try and obtain the length
322   // maybe there's a better way to get this info??
323   m_stillRunning = 1;
324   if (!FillBuffer(1))
325   {
326     CLog::Log(LOGERROR, "CCurlFile::CReadState::Connect, didn't get any data from stream.");
327     return -1;
328   }
329
330   double length;
331   if (CURLE_OK == g_curlInterface.easy_getinfo(m_easyHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &length))
332   {
333     if (length < 0)
334       length = 0.0;
335     m_fileSize = m_filePos + (int64_t)length;
336   }
337
338   long response;
339   if (CURLE_OK == g_curlInterface.easy_getinfo(m_easyHandle, CURLINFO_RESPONSE_CODE, &response))
340     return response;
341
342   return -1;
343 }
344
345 void CCurlFile::CReadState::Disconnect()
346 {
347   if(m_multiHandle && m_easyHandle)
348     g_curlInterface.multi_remove_handle(m_multiHandle, m_easyHandle);
349
350   m_buffer.Clear();
351   free(m_overflowBuffer);
352   m_overflowBuffer = NULL;
353   m_overflowSize = 0;
354   m_filePos = 0;
355   m_fileSize = 0;
356   m_bufferSize = 0;
357   m_readBuffer = 0;
358
359   /* cleanup */
360   if( m_curlHeaderList )
361     g_curlInterface.slist_free_all(m_curlHeaderList);
362   m_curlHeaderList = NULL;
363
364   if( m_curlAliasList )
365     g_curlInterface.slist_free_all(m_curlAliasList);
366   m_curlAliasList = NULL;
367 }
368
369
370 CCurlFile::~CCurlFile()
371 {
372   Close();
373   delete m_state;
374   delete m_oldState;
375   g_curlInterface.Unload();
376 }
377
378 CCurlFile::CCurlFile()
379 {
380   g_curlInterface.Load(); // loads the curl dll and resolves exports etc.
381   m_opened = false;
382   m_forWrite = false;
383   m_inError = false;
384   m_multisession  = true;
385   m_seekable = true;
386   m_useOldHttpVersion = false;
387   m_connecttimeout = 0;
388   m_lowspeedtime = 0;
389   m_ftpauth = "";
390   m_ftpport = "";
391   m_ftppasvip = false;
392   m_bufferSize = 32768;
393   m_binary = true;
394   m_postdata = "";
395   m_postdataset = false;
396   m_username = "";
397   m_password = "";
398   m_httpauth = "";
399   m_proxytype = PROXY_HTTP;
400   m_state = new CReadState();
401   m_oldState = NULL;
402   m_skipshout = false;
403   m_httpresponse = -1;
404 }
405
406 //Has to be called before Open()
407 void CCurlFile::SetBufferSize(unsigned int size)
408 {
409   m_bufferSize = size;
410 }
411
412 void CCurlFile::Close()
413 {
414   if (m_opened && m_forWrite && !m_inError)
415       Write(NULL, 0);
416
417   m_state->Disconnect();
418   delete m_oldState;
419   m_oldState = NULL;
420
421   m_url.Empty();
422   m_referer.Empty();
423   m_cookie.Empty();
424
425   m_opened = false;
426   m_forWrite = false;
427   m_inError = false;
428 }
429
430 void CCurlFile::SetCommonOptions(CReadState* state)
431 {
432   CURL_HANDLE* h = state->m_easyHandle;
433
434   g_curlInterface.easy_reset(h);
435
436   g_curlInterface.easy_setopt(h, CURLOPT_DEBUGFUNCTION, debug_callback);
437
438   if( g_advancedSettings.m_logLevel >= LOG_LEVEL_DEBUG )
439     g_curlInterface.easy_setopt(h, CURLOPT_VERBOSE, TRUE);
440   else
441     g_curlInterface.easy_setopt(h, CURLOPT_VERBOSE, FALSE);
442
443   g_curlInterface.easy_setopt(h, CURLOPT_WRITEDATA, state);
444   g_curlInterface.easy_setopt(h, CURLOPT_WRITEFUNCTION, write_callback);
445
446   g_curlInterface.easy_setopt(h, CURLOPT_READDATA, state);
447   g_curlInterface.easy_setopt(h, CURLOPT_READFUNCTION, read_callback);
448
449   // set username and password for current handle
450   if (m_username.length() > 0 && m_password.length() > 0)
451   {
452     CStdString userpwd = m_username + ":" + m_password;
453     g_curlInterface.easy_setopt(h, CURLOPT_USERPWD, userpwd.c_str());
454   }
455
456   // make sure headers are seperated from the data stream
457   g_curlInterface.easy_setopt(h, CURLOPT_WRITEHEADER, state);
458   g_curlInterface.easy_setopt(h, CURLOPT_HEADERFUNCTION, header_callback);
459   g_curlInterface.easy_setopt(h, CURLOPT_HEADER, FALSE);
460
461   g_curlInterface.easy_setopt(h, CURLOPT_FTP_USE_EPSV, 0); // turn off epsv
462
463   // Allow us to follow two redirects
464   g_curlInterface.easy_setopt(h, CURLOPT_FOLLOWLOCATION, TRUE);
465   g_curlInterface.easy_setopt(h, CURLOPT_MAXREDIRS, 5);
466
467   // Enable cookie engine for current handle to re-use them in future requests
468   CStdString strCookieFile;
469   CStdString strTempPath = CSpecialProtocol::TranslatePath(g_advancedSettings.m_cachePath);
470   strCookieFile = URIUtils::AddFileToFolder(strTempPath, "cookies.dat");
471
472   g_curlInterface.easy_setopt(h, CURLOPT_COOKIEFILE, strCookieFile.c_str());
473   g_curlInterface.easy_setopt(h, CURLOPT_COOKIEJAR, strCookieFile.c_str());
474
475   // Set custom cookie if requested
476   if (!m_cookie.IsEmpty())
477     g_curlInterface.easy_setopt(h, CURLOPT_COOKIE, m_cookie.c_str());
478
479   g_curlInterface.easy_setopt(h, CURLOPT_COOKIELIST, "FLUSH");
480
481   // When using multiple threads you should set the CURLOPT_NOSIGNAL option to
482   // TRUE for all handles. Everything will work fine except that timeouts are not
483   // honored during the DNS lookup - which you can work around by building libcurl
484   // with c-ares support. c-ares is a library that provides asynchronous name
485   // resolves. Unfortunately, c-ares does not yet support IPv6.
486   g_curlInterface.easy_setopt(h, CURLOPT_NOSIGNAL, TRUE);
487
488   // not interested in failed requests
489   g_curlInterface.easy_setopt(h, CURLOPT_FAILONERROR, 1);
490
491   // enable support for icecast / shoutcast streams
492   if ( NULL == state->m_curlAliasList )
493     // m_curlAliasList is used only by this one place, but SetCommonOptions can
494     // be called multiple times, only append to list if it's empty.
495     state->m_curlAliasList = g_curlInterface.slist_append(state->m_curlAliasList, "ICY 200 OK");
496   g_curlInterface.easy_setopt(h, CURLOPT_HTTP200ALIASES, state->m_curlAliasList);
497
498   // never verify peer, we don't have any certificates to do this
499   g_curlInterface.easy_setopt(h, CURLOPT_SSL_VERIFYPEER, 0);
500   g_curlInterface.easy_setopt(h, CURLOPT_SSL_VERIFYHOST, 0);
501
502   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_URL, m_url.c_str());
503   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TRANSFERTEXT, FALSE);
504
505   // setup POST data if it is set (and it may be empty)
506   if (m_postdataset)
507   {
508     g_curlInterface.easy_setopt(h, CURLOPT_POST, 1 );
509     g_curlInterface.easy_setopt(h, CURLOPT_POSTFIELDSIZE, m_postdata.length());
510     g_curlInterface.easy_setopt(h, CURLOPT_POSTFIELDS, m_postdata.c_str());
511   }
512
513   // setup Referer header if needed
514   if (!m_referer.IsEmpty())
515     g_curlInterface.easy_setopt(h, CURLOPT_REFERER, m_referer.c_str());
516   else
517   {
518     g_curlInterface.easy_setopt(h, CURLOPT_REFERER, NULL);
519     g_curlInterface.easy_setopt(h, CURLOPT_AUTOREFERER, TRUE);
520   }
521
522   // setup any requested authentication
523   if( m_ftpauth.length() > 0 )
524   {
525     g_curlInterface.easy_setopt(h, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);
526     if( m_ftpauth.Equals("any") )
527       g_curlInterface.easy_setopt(h, CURLOPT_FTPSSLAUTH, CURLFTPAUTH_DEFAULT);
528     else if( m_ftpauth.Equals("ssl") )
529       g_curlInterface.easy_setopt(h, CURLOPT_FTPSSLAUTH, CURLFTPAUTH_SSL);
530     else if( m_ftpauth.Equals("tls") )
531       g_curlInterface.easy_setopt(h, CURLOPT_FTPSSLAUTH, CURLFTPAUTH_TLS);
532   }
533
534   // setup requested http authentication method
535   if(m_httpauth.length() > 0)
536   {
537     if( m_httpauth.Equals("any") )
538       g_curlInterface.easy_setopt(h, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
539     else if( m_httpauth.Equals("anysafe") )
540       g_curlInterface.easy_setopt(h, CURLOPT_HTTPAUTH, CURLAUTH_ANYSAFE);
541     else if( m_httpauth.Equals("digest") )
542       g_curlInterface.easy_setopt(h, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
543     else if( m_httpauth.Equals("ntlm") )
544       g_curlInterface.easy_setopt(h, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
545   }
546
547   // allow passive mode for ftp
548   if( m_ftpport.length() > 0 )
549     g_curlInterface.easy_setopt(h, CURLOPT_FTPPORT, m_ftpport.c_str());
550   else
551     g_curlInterface.easy_setopt(h, CURLOPT_FTPPORT, NULL);
552
553   // allow curl to not use the ip address in the returned pasv response
554   if( m_ftppasvip )
555     g_curlInterface.easy_setopt(h, CURLOPT_FTP_SKIP_PASV_IP, 0);
556   else
557     g_curlInterface.easy_setopt(h, CURLOPT_FTP_SKIP_PASV_IP, 1);
558
559   // setup Content-Encoding if requested
560   if( m_contentencoding.length() > 0 )
561     g_curlInterface.easy_setopt(h, CURLOPT_ENCODING, m_contentencoding.c_str());
562
563   if (m_userAgent.length() > 0)
564     g_curlInterface.easy_setopt(h, CURLOPT_USERAGENT, m_userAgent.c_str());
565   else /* set some default agent as shoutcast doesn't return proper stuff otherwise */
566     g_curlInterface.easy_setopt(h, CURLOPT_USERAGENT, g_advancedSettings.m_userAgent.c_str());
567
568   if (m_useOldHttpVersion)
569     g_curlInterface.easy_setopt(h, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
570   else
571     SetRequestHeader("Connection", "keep-alive");
572
573   if (g_advancedSettings.m_curlDisableIPV6)
574     g_curlInterface.easy_setopt(h, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
575
576   if (m_proxy.length() > 0)
577   {
578     g_curlInterface.easy_setopt(h, CURLOPT_PROXY, m_proxy.c_str());
579     g_curlInterface.easy_setopt(h, CURLOPT_PROXYTYPE, proxyType2CUrlProxyType[m_proxytype]);
580     if (m_proxyuserpass.length() > 0)
581       g_curlInterface.easy_setopt(h, CURLOPT_PROXYUSERPWD, m_proxyuserpass.c_str());
582
583   }
584   if (m_customrequest.length() > 0)
585     g_curlInterface.easy_setopt(h, CURLOPT_CUSTOMREQUEST, m_customrequest.c_str());
586
587   if (m_connecttimeout == 0)
588     m_connecttimeout = g_advancedSettings.m_curlconnecttimeout;
589
590   // set our timeouts, we abort connection after m_timeout, and reads after no data for m_timeout seconds
591   g_curlInterface.easy_setopt(h, CURLOPT_CONNECTTIMEOUT, m_connecttimeout);
592
593   // We abort in case we transfer less than 1byte/second
594   g_curlInterface.easy_setopt(h, CURLOPT_LOW_SPEED_LIMIT, 1);
595
596   if (m_lowspeedtime == 0)
597     m_lowspeedtime = g_advancedSettings.m_curllowspeedtime;
598
599   // Set the lowspeed time very low as it seems Curl takes much longer to detect a lowspeed condition
600   g_curlInterface.easy_setopt(h, CURLOPT_LOW_SPEED_TIME, m_lowspeedtime);
601
602   if (m_skipshout)
603     // For shoutcast file, content-length should not be set, and in libcurl there is a bug, if the
604     // cast file was 302 redirected then getinfo of CURLINFO_CONTENT_LENGTH_DOWNLOAD will return
605     // the 302 response's body length, which cause the next read request failed, so we ignore
606     // content-length for shoutcast file to workaround this.
607     g_curlInterface.easy_setopt(h, CURLOPT_IGNORE_CONTENT_LENGTH, 1);
608 }
609
610 void CCurlFile::SetRequestHeaders(CReadState* state)
611 {
612   if(state->m_curlHeaderList)
613   {
614     g_curlInterface.slist_free_all(state->m_curlHeaderList);
615     state->m_curlHeaderList = NULL;
616   }
617
618   MAPHTTPHEADERS::iterator it;
619   for(it = m_requestheaders.begin(); it != m_requestheaders.end(); it++)
620   {
621     CStdString buffer = it->first + ": " + it->second;
622     state->m_curlHeaderList = g_curlInterface.slist_append(state->m_curlHeaderList, buffer.c_str());
623   }
624
625   // add user defined headers
626   if (state->m_easyHandle)
627     g_curlInterface.easy_setopt(state->m_easyHandle, CURLOPT_HTTPHEADER, state->m_curlHeaderList);
628 }
629
630 void CCurlFile::SetCorrectHeaders(CReadState* state)
631 {
632   CHttpHeader& h = state->m_httpheader;
633   /* workaround for shoutcast server wich doesn't set content type on standard mp3 */
634   if( h.GetMimeType().empty() )
635   {
636     if( !h.GetValue("icy-notice1").empty()
637     || !h.GetValue("icy-name").empty()
638     || !h.GetValue("icy-br").empty() )
639       h.AddParam("Content-Type", "audio/mpeg");
640   }
641
642   /* hack for google video */
643   if (StringUtils::EqualsNoCase(h.GetMimeType(),"text/html")
644   &&  !h.GetValue("Content-Disposition").empty() )
645   {
646     CStdString strValue = h.GetValue("Content-Disposition");
647     if (strValue.Find("filename=") > -1 && strValue.Find(".flv") > -1)
648       h.AddParam("Content-Type", "video/flv");
649   }
650 }
651
652 void CCurlFile::ParseAndCorrectUrl(CURL &url2)
653 {
654   CStdString strProtocol = url2.GetTranslatedProtocol();
655   url2.SetProtocol(strProtocol);
656
657   if( strProtocol.Equals("ftp")
658   ||  strProtocol.Equals("ftps") )
659   {
660     // we was using url optons for urls, keep the old code work and warning
661     if (!url2.GetOptions().IsEmpty())
662     {
663       CLog::Log(LOGWARNING, "%s: ftp url option is deprecated, please switch to use protocol option (change '?' to '|'), url: [%s]", __FUNCTION__, url2.Get().c_str());
664       url2.SetProtocolOptions(url2.GetOptions().Mid(1));
665       /* ftp has no options */
666       url2.SetOptions("");
667     }
668
669     /* this is uggly, depending on from where   */
670     /* we get the link it may or may not be     */
671     /* url encoded. if handed from ftpdirectory */
672     /* it won't be so let's handle that case    */
673
674     CStdString partial, filename(url2.GetFileName());
675     std::vector<std::string> array;
676
677     // if server sent us the filename in non-utf8, we need send back with same encoding.
678     if (url2.GetProtocolOption("utf8") == "0")
679       g_charsetConverter.utf8ToStringCharset(filename);
680
681     /* TODO: create a tokenizer that doesn't skip empty's */
682     StringUtils::Tokenize(filename, array, "/");
683     filename.Empty();
684     for(std::vector<std::string>::iterator it = array.begin(); it != array.end(); it++)
685     {
686       if(it != array.begin())
687         filename += "/";
688
689       partial = *it;
690       CURL::Encode(partial);
691       filename += partial;
692     }
693
694     /* make sure we keep slashes */
695     if(url2.GetFileName().Right(1) == "/")
696       filename += "/";
697
698     url2.SetFileName(filename);
699
700     m_ftpauth = "";
701     if (url2.HasProtocolOption("auth"))
702     {
703       m_ftpauth = url2.GetProtocolOption("auth");
704       if(m_ftpauth.IsEmpty())
705         m_ftpauth = "any";
706     }
707     m_ftpport = "";
708     if (url2.HasProtocolOption("active"))
709     {
710       m_ftpport = url2.GetProtocolOption("active");
711       if(m_ftpport.IsEmpty())
712         m_ftpport = "-";
713     }
714     m_ftppasvip = url2.HasProtocolOption("pasvip") && url2.GetProtocolOption("pasvip") != "0";
715   }
716   else if( strProtocol.Equals("http")
717        ||  strProtocol.Equals("https"))
718   {
719     if (CSettings::Get().GetBool("network.usehttpproxy")
720         && !CSettings::Get().GetString("network.httpproxyserver").empty()
721         && CSettings::Get().GetInt("network.httpproxyport") > 0
722         && m_proxy.IsEmpty())
723     {
724       m_proxy = CSettings::Get().GetString("network.httpproxyserver");
725       m_proxy.AppendFormat(":%d", CSettings::Get().GetInt("network.httpproxyport"));
726       if (CSettings::Get().GetString("network.httpproxyusername").length() > 0 && m_proxyuserpass.IsEmpty())
727       {
728         m_proxyuserpass = CSettings::Get().GetString("network.httpproxyusername");
729         m_proxyuserpass += ":" + CSettings::Get().GetString("network.httpproxypassword");
730       }
731       m_proxytype = (ProxyType)CSettings::Get().GetInt("network.httpproxytype");
732       CLog::Log(LOGDEBUG, "Using proxy %s, type %d", m_proxy.c_str(), proxyType2CUrlProxyType[m_proxytype]);
733     }
734
735     // get username and password
736     m_username = url2.GetUserName();
737     m_password = url2.GetPassWord();
738
739     // handle any protocol options
740     std::map<CStdString, CStdString> options;
741     url2.GetProtocolOptions(options);
742     if (options.size() > 0)
743     {
744       // clear protocol options
745       url2.SetProtocolOptions("");
746       // set xbmc headers
747       for(std::map<CStdString, CStdString>::const_iterator it = options.begin(); it != options.end(); ++it)
748       {
749         const CStdString &name = it->first;
750         const CStdString &value = it->second;
751
752         if(name.Equals("auth"))
753         {
754           m_httpauth = value;
755           if(m_httpauth.IsEmpty())
756             m_httpauth = "any";
757         }
758         else if (name.Equals("Referer"))
759           SetReferer(value);
760         else if (name.Equals("User-Agent"))
761           SetUserAgent(value);
762         else if (name.Equals("Cookie"))
763           SetCookie(value);
764         else if (name.Equals("Encoding"))
765           SetContentEncoding(value);
766         else if (name.Equals("noshout") && value.Equals("true"))
767           m_skipshout = true;
768         else if (name.Equals("seekable") && value.Equals("0"))
769           m_seekable = false;
770         else
771           SetRequestHeader(name, value);
772       }
773     }
774   }
775
776   if (m_username.length() > 0 && m_password.length() > 0)
777     m_url = url2.GetWithoutUserDetails();
778   else
779     m_url = url2.Get();
780 }
781
782 bool CCurlFile::Post(const CStdString& strURL, const CStdString& strPostData, CStdString& strHTML)
783 {
784   m_postdata = strPostData;
785   m_postdataset = true;
786   return Service(strURL, strHTML);
787 }
788
789 bool CCurlFile::Get(const CStdString& strURL, CStdString& strHTML)
790 {
791   m_postdata = "";
792   m_postdataset = false;
793   return Service(strURL, strHTML);
794 }
795
796 bool CCurlFile::Service(const CStdString& strURL, CStdString& strHTML)
797 {
798   if (Open(strURL))
799   {
800     if (ReadData(strHTML))
801     {
802       Close();
803       return true;
804     }
805   }
806   Close();
807   return false;
808 }
809
810 bool CCurlFile::ReadData(CStdString& strHTML)
811 {
812   int size_read = 0;
813   int data_size = 0;
814   strHTML = "";
815   char buffer[16384];
816   while( (size_read = Read(buffer, sizeof(buffer)-1) ) > 0 )
817   {
818     buffer[size_read] = 0;
819     strHTML.append(buffer, size_read);
820     data_size += size_read;
821   }
822   if (m_state->m_cancelled)
823     return false;
824   return true;
825 }
826
827 bool CCurlFile::Download(const CStdString& strURL, const CStdString& strFileName, LPDWORD pdwSize)
828 {
829   CLog::Log(LOGINFO, "CCurlFile::Download - %s->%s", strURL.c_str(), strFileName.c_str());
830
831   CStdString strData;
832   if (!Get(strURL, strData))
833     return false;
834
835   XFILE::CFile file;
836   if (!file.OpenForWrite(strFileName, true))
837   {
838     CLog::Log(LOGERROR, "CCurlFile::Download - Unable to open file %s: %u",
839     strFileName.c_str(), GetLastError());
840     return false;
841   }
842   if (strData.size())
843     file.Write(strData.c_str(), strData.size());
844   file.Close();
845
846   if (pdwSize != NULL)
847   {
848     *pdwSize = strData.size();
849   }
850
851   return true;
852 }
853
854 // Detect whether we are "online" or not! Very simple and dirty!
855 bool CCurlFile::IsInternet(bool checkDNS /* = true */)
856 {
857   CStdString strURL = "http://www.google.com";
858   if (!checkDNS)
859     strURL = "http://74.125.19.103"; // www.google.com ip
860
861   bool found = Exists(strURL);
862   Close();
863
864   return found;
865 }
866
867 void CCurlFile::Cancel()
868 {
869   m_state->m_cancelled = true;
870   while (m_opened)
871     Sleep(1);
872 }
873
874 void CCurlFile::Reset()
875 {
876   m_state->m_cancelled = false;
877 }
878
879 bool CCurlFile::Open(const CURL& url)
880 {
881   m_opened = true;
882   m_seekable = true;
883
884   CURL url2(url);
885   ParseAndCorrectUrl(url2);
886
887   CLog::Log(LOGDEBUG, "CurlFile::Open(%p) %s", (void*)this, m_url.c_str());
888
889   ASSERT(!(!m_state->m_easyHandle ^ !m_state->m_multiHandle));
890   if( m_state->m_easyHandle == NULL )
891     g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, &m_state->m_multiHandle );
892
893   // setup common curl options
894   SetCommonOptions(m_state);
895   SetRequestHeaders(m_state);
896   m_state->m_sendRange = m_seekable;
897
898   m_httpresponse = m_state->Connect(m_bufferSize);
899   if( m_httpresponse < 0 || m_httpresponse >= 400)
900     return false;
901
902   SetCorrectHeaders(m_state);
903
904   // since we can't know the stream size up front if we're gzipped/deflated
905   // flag the stream with an unknown file size rather than the compressed
906   // file size.
907   if (m_contentencoding.size() > 0)
908     m_state->m_fileSize = 0;
909
910   // check if this stream is a shoutcast stream. sometimes checking the protocol line is not enough so examine other headers as well.
911   // shoutcast streams should be handled by FileShoutcast.
912   if ((m_state->m_httpheader.GetProtoLine().substr(0, 3) == "ICY" || !m_state->m_httpheader.GetValue("icy-notice1").empty()
913      || !m_state->m_httpheader.GetValue("icy-name").empty()
914      || !m_state->m_httpheader.GetValue("icy-br").empty()) && !m_skipshout)
915   {
916     CLog::Log(LOGDEBUG,"CCurlFile::Open - File <%s> is a shoutcast stream. Re-opening", m_url.c_str());
917     throw new CRedirectException(new CShoutcastFile);
918   }
919
920   m_multisession = false;
921   if(url2.GetProtocol().Equals("http") || url2.GetProtocol().Equals("https"))
922   {
923     m_multisession = true;
924     if(m_state->m_httpheader.GetValue("Server").find("Portable SDK for UPnP devices") != std::string::npos)
925     {
926       CLog::Log(LOGWARNING, "CCurlFile::Open - Disabling multi session due to broken libupnp server");
927       m_multisession = false;
928     }
929   }
930
931   if(StringUtils::EqualsNoCase(m_state->m_httpheader.GetValue("Transfer-Encoding"), "chunked"))
932     m_state->m_fileSize = 0;
933
934   if(m_state->m_fileSize <= 0)
935     m_seekable = false;
936   if (m_seekable)
937   {
938     if(url2.GetProtocol().Equals("http")
939     || url2.GetProtocol().Equals("https"))
940     {
941       // if server says explicitly it can't seek, respect that
942       if(StringUtils::EqualsNoCase(m_state->m_httpheader.GetValue("Accept-Ranges"),"none"))
943         m_seekable = false;
944     }
945   }
946
947   char* efurl;
948   if (CURLE_OK == g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_EFFECTIVE_URL,&efurl) && efurl)
949     m_url = efurl;
950
951   return true;
952 }
953
954 bool CCurlFile::OpenForWrite(const CURL& url, bool bOverWrite)
955 {
956   if(m_opened)
957     return false;
958
959   if (Exists(url) && !bOverWrite)
960     return false;
961
962   CURL url2(url);
963   ParseAndCorrectUrl(url2);
964
965   CLog::Log(LOGDEBUG, "CCurlFile::OpenForWrite(%p) %s", (void*)this, m_url.c_str());
966
967   ASSERT(m_state->m_easyHandle == NULL);
968   g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, &m_state->m_multiHandle);
969
970     // setup common curl options
971   SetCommonOptions(m_state);
972   SetRequestHeaders(m_state);
973
974   char* efurl;
975   if (CURLE_OK == g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_EFFECTIVE_URL,&efurl) && efurl)
976     m_url = efurl;
977
978   m_opened = true;
979   m_forWrite = true;
980   m_inError = false;
981   m_writeOffset = 0;
982
983   ASSERT(m_state->m_multiHandle);
984
985   SetCommonOptions(m_state); 
986   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_UPLOAD, 1);
987
988   g_curlInterface.multi_add_handle(m_state->m_multiHandle, m_state->m_easyHandle);
989
990   m_state->SetReadBuffer(NULL, 0);
991
992   return true;
993 }
994
995 int CCurlFile::Write(const void* lpBuf, int64_t uiBufSize)
996 {
997   if (!(m_opened && m_forWrite) || m_inError)
998     return -1;
999
1000   ASSERT(m_state->m_multiHandle);
1001
1002   m_state->SetReadBuffer(lpBuf, uiBufSize);
1003   m_state->m_isPaused = false;
1004   g_curlInterface.easy_pause(m_state->m_easyHandle, CURLPAUSE_CONT);
1005
1006   CURLMcode result = CURLM_OK;
1007
1008   m_stillRunning = 1;
1009   while (m_stillRunning && !m_state->m_isPaused)
1010   {
1011     while ((result = g_curlInterface.multi_perform(m_state->m_multiHandle, &m_stillRunning)) == CURLM_CALL_MULTI_PERFORM);
1012
1013     if (!m_stillRunning)
1014       break;
1015
1016     if (result != CURLM_OK)
1017     {
1018       long code;
1019       if(g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_RESPONSE_CODE, &code) == CURLE_OK )
1020         CLog::Log(LOGERROR, "%s - Unable to write curl resource (%s) - %ld", __FUNCTION__, m_url.c_str(), code);
1021       m_inError = true;
1022       return -1;
1023     }
1024   }
1025
1026   m_writeOffset += m_state->m_filePos;
1027   return m_state->m_filePos;
1028 }
1029
1030 bool CCurlFile::CReadState::ReadString(char *szLine, int iLineLength)
1031 {
1032   unsigned int want = (unsigned int)iLineLength;
1033
1034   if((m_fileSize == 0 || m_filePos < m_fileSize) && !FillBuffer(want))
1035     return false;
1036
1037   // ensure only available data is considered
1038   want = XMIN((unsigned int)m_buffer.getMaxReadSize(), want);
1039
1040   /* check if we finished prematurely */
1041   if (!m_stillRunning && (m_fileSize == 0 || m_filePos != m_fileSize) && !want)
1042   {
1043     if (m_fileSize != 0)
1044       CLog::Log(LOGWARNING, "%s - Transfer ended before entire file was retrieved pos %"PRId64", size %"PRId64, __FUNCTION__, m_filePos, m_fileSize);
1045
1046     return false;
1047   }
1048
1049   char* pLine = szLine;
1050   do
1051   {
1052     if (!m_buffer.ReadData(pLine, 1))
1053       break;
1054
1055     pLine++;
1056   } while (((pLine - 1)[0] != '\n') && ((unsigned int)(pLine - szLine) < want));
1057   pLine[0] = 0;
1058   m_filePos += (pLine - szLine);
1059   return (bool)((pLine - szLine) > 0);
1060 }
1061
1062 bool CCurlFile::Exists(const CURL& url)
1063 {
1064   // if file is already running, get info from it
1065   if( m_opened )
1066   {
1067     CLog::Log(LOGWARNING, "CCurlFile::Exists - Exist called on open file %s", url.Get().c_str());
1068     return true;
1069   }
1070
1071   CURL url2(url);
1072   ParseAndCorrectUrl(url2);
1073
1074   ASSERT(m_state->m_easyHandle == NULL);
1075   g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, NULL);
1076
1077   SetCommonOptions(m_state);
1078   SetRequestHeaders(m_state);
1079   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TIMEOUT, 5);
1080   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_NOBODY, 1);
1081   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_WRITEDATA, NULL); /* will cause write failure*/
1082
1083   if(url2.GetProtocol() == "ftp")
1084   {
1085     g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FILETIME, 1);
1086     // nocwd is less standard, will return empty list for non-existed remote dir on some ftp server, avoid it.
1087     if (StringUtils::EndsWith(url2.GetFileName(), "/"))
1088       g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_SINGLECWD);
1089     else
1090       g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_NOCWD);
1091   }
1092
1093   CURLcode result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1094   g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1095
1096   if (result == CURLE_WRITE_ERROR || result == CURLE_OK)
1097     return true;
1098
1099   if (result == CURLE_HTTP_RETURNED_ERROR)
1100   {
1101     long code;
1102     if(g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_RESPONSE_CODE, &code) == CURLE_OK && code != 404 )
1103       CLog::Log(LOGERROR, "CCurlFile::Exists - Failed: HTTP returned error %ld for %s", code, url.Get().c_str());
1104   }
1105   else if (result != CURLE_REMOTE_FILE_NOT_FOUND && result != CURLE_FTP_COULDNT_RETR_FILE)
1106   {
1107     CLog::Log(LOGERROR, "CCurlFile::Exists - Failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.Get().c_str());
1108   }
1109
1110   errno = ENOENT;
1111   return false;
1112 }
1113
1114 int64_t CCurlFile::Seek(int64_t iFilePosition, int iWhence)
1115 {
1116   int64_t nextPos = m_state->m_filePos;
1117   switch(iWhence)
1118   {
1119     case SEEK_SET:
1120       nextPos = iFilePosition;
1121       break;
1122     case SEEK_CUR:
1123       nextPos += iFilePosition;
1124       break;
1125     case SEEK_END:
1126       if (m_state->m_fileSize)
1127         nextPos = m_state->m_fileSize + iFilePosition;
1128       else
1129         return -1;
1130       break;
1131     default:
1132       return -1;
1133   }
1134
1135   // We can't seek beyond EOF
1136   if (m_state->m_fileSize && nextPos > m_state->m_fileSize) return -1;
1137
1138   if(m_state->Seek(nextPos))
1139     return nextPos;
1140
1141   if (m_oldState && m_oldState->Seek(nextPos))
1142   {
1143     CReadState *tmp = m_state;
1144     m_state = m_oldState;
1145     m_oldState = tmp;
1146     return nextPos;
1147   }
1148
1149   if(!m_seekable)
1150     return -1;
1151
1152   CReadState* oldstate = NULL;
1153   if(m_multisession)
1154   {
1155     CURL url(m_url);
1156     oldstate = m_oldState;
1157     m_oldState = m_state;
1158     m_state = new CReadState();
1159
1160     g_curlInterface.easy_aquire(url.GetProtocol(), url.GetHostName(), &m_state->m_easyHandle, &m_state->m_multiHandle );
1161
1162     m_state->m_fileSize = m_oldState->m_fileSize;
1163   }
1164   else
1165     m_state->Disconnect();
1166
1167   // re-setup common curl options
1168   SetCommonOptions(m_state);
1169
1170   /* caller might have changed some headers (needed for daap)*/
1171   SetRequestHeaders(m_state);
1172
1173   m_state->m_filePos = nextPos;
1174   m_state->m_sendRange = true;
1175
1176   long response = m_state->Connect(m_bufferSize);
1177   if(response < 0 && (m_state->m_fileSize == 0 || m_state->m_fileSize != m_state->m_filePos))
1178   {
1179     m_seekable = false;
1180     if(m_multisession && m_oldState)
1181     {
1182       delete m_state;
1183       m_state = m_oldState;
1184       m_oldState = oldstate;
1185     }
1186     return -1;
1187   }
1188
1189   SetCorrectHeaders(m_state);
1190   delete oldstate;
1191
1192   return m_state->m_filePos;
1193 }
1194
1195 int64_t CCurlFile::GetLength()
1196 {
1197   if (!m_opened) return 0;
1198   return m_state->m_fileSize;
1199 }
1200
1201 int64_t CCurlFile::GetPosition()
1202 {
1203   if (!m_opened) return 0;
1204   return m_state->m_filePos;
1205 }
1206
1207 int CCurlFile::Stat(const CURL& url, struct __stat64* buffer)
1208 {
1209   // if file is already running, get info from it
1210   if( m_opened )
1211   {
1212     CLog::Log(LOGWARNING, "CCurlFile::Stat - Stat called on open file %s", url.Get().c_str());
1213     if (buffer)
1214     {
1215       memset(buffer, 0, sizeof(struct __stat64));
1216       buffer->st_size = GetLength();
1217       buffer->st_mode = _S_IFREG;
1218     }
1219     return 0;
1220   }
1221
1222   CURL url2(url);
1223   ParseAndCorrectUrl(url2);
1224
1225   ASSERT(m_state->m_easyHandle == NULL);
1226   g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, NULL);
1227
1228   SetCommonOptions(m_state);
1229   SetRequestHeaders(m_state);
1230   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TIMEOUT, g_advancedSettings.m_curlconnecttimeout);
1231   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_NOBODY, 1);
1232   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_WRITEDATA, NULL); /* will cause write failure*/
1233   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FILETIME , 1); 
1234
1235   if(url2.GetProtocol() == "ftp")
1236   {
1237     // nocwd is less standard, will return empty list for non-existed remote dir on some ftp server, avoid it.
1238     if (StringUtils::EndsWith(url2.GetFileName(), "/"))
1239       g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_SINGLECWD);
1240     else
1241       g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_NOCWD);
1242   }
1243
1244   CURLcode result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1245
1246   if(result == CURLE_HTTP_RETURNED_ERROR)
1247   {
1248     long code;
1249     if(g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_RESPONSE_CODE, &code) == CURLE_OK && code == 404 )
1250       return -1;
1251   }
1252
1253   if(result == CURLE_GOT_NOTHING 
1254   || result == CURLE_HTTP_RETURNED_ERROR 
1255   || result == CURLE_RECV_ERROR /* some silly shoutcast servers */ )
1256   {
1257     /* some http servers and shoutcast servers don't give us any data on a head request */
1258     /* request normal and just fail out, it's their loss */
1259     /* somehow curl doesn't reset CURLOPT_NOBODY properly so reset everything */
1260     SetCommonOptions(m_state);
1261     SetRequestHeaders(m_state);
1262     g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TIMEOUT, g_advancedSettings.m_curlconnecttimeout);
1263     g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_RANGE, "0-0");
1264     g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_WRITEDATA, NULL); /* will cause write failure*/
1265     g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FILETIME, 1); 
1266     result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1267   }
1268
1269   if( result == CURLE_HTTP_RANGE_ERROR )
1270   {
1271     /* crap can't use the range option, disable it and try again */
1272     g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_RANGE, NULL);
1273     result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1274   }
1275
1276   if( result != CURLE_WRITE_ERROR && result != CURLE_OK )
1277   {
1278     g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1279     errno = ENOENT;
1280     CLog::Log(LOGERROR, "CCurlFile::Stat - Failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.Get().c_str());
1281     return -1;
1282   }
1283
1284   double length;
1285   result = g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &length);
1286   if (result != CURLE_OK || length < 0.0)
1287   {
1288     if (url.GetProtocol() == "ftp")
1289     {
1290       g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1291       CLog::Log(LOGNOTICE, "CCurlFile::Stat - Content length failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.Get().c_str());
1292       errno = ENOENT;
1293       return -1;
1294     }
1295     else
1296       length = 0.0;
1297   }
1298
1299   SetCorrectHeaders(m_state);
1300
1301   if(buffer)
1302   {
1303     char *content;
1304     result = g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_CONTENT_TYPE, &content);
1305     if (result != CURLE_OK)
1306     {
1307       CLog::Log(LOGNOTICE, "CCurlFile::Stat - Content type failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.Get().c_str());
1308       g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1309       errno = ENOENT;
1310       return -1;
1311     }
1312     else
1313     {
1314       memset(buffer, 0, sizeof(struct __stat64));
1315       buffer->st_size = (int64_t)length;
1316       if(content && strstr(content, "text/html")) //consider html files directories
1317         buffer->st_mode = _S_IFDIR;
1318       else
1319         buffer->st_mode = _S_IFREG;
1320     }
1321     long filetime;
1322     result = g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_FILETIME, &filetime);
1323     if (result != CURLE_OK)
1324     {
1325       CLog::Log(LOGNOTICE, "CCurlFile::Stat - Filetime failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.Get().c_str());
1326     }
1327     else
1328     {
1329       if (filetime != -1)
1330         buffer->st_mtime = filetime;
1331     }
1332   }
1333   g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1334   return 0;
1335 }
1336
1337 unsigned int CCurlFile::CReadState::Read(void* lpBuf, int64_t uiBufSize)
1338 {
1339   /* only request 1 byte, for truncated reads (only if not eof) */
1340   if((m_fileSize == 0 || m_filePos < m_fileSize) && !FillBuffer(1))
1341     return 0;
1342
1343   /* ensure only available data is considered */
1344   unsigned int want = (unsigned int)XMIN(m_buffer.getMaxReadSize(), uiBufSize);
1345
1346   /* xfer data to caller */
1347   if (m_buffer.ReadData((char *)lpBuf, want))
1348   {
1349     m_filePos += want;
1350     return want;
1351   }
1352
1353   /* check if we finished prematurely */
1354   if (!m_stillRunning && (m_fileSize == 0 || m_filePos != m_fileSize))
1355   {
1356     CLog::Log(LOGWARNING, "%s - Transfer ended before entire file was retrieved pos %"PRId64", size %"PRId64, __FUNCTION__, m_filePos, m_fileSize);
1357     return 0;
1358   }
1359
1360   return 0;
1361 }
1362
1363 /* use to attempt to fill the read buffer up to requested number of bytes */
1364 bool CCurlFile::CReadState::FillBuffer(unsigned int want)
1365 {
1366   int retry = 0;
1367   fd_set fdread;
1368   fd_set fdwrite;
1369   fd_set fdexcep;
1370
1371   // only attempt to fill buffer if transactions still running and buffer
1372   // doesnt exceed required size already
1373   while ((unsigned int)m_buffer.getMaxReadSize() < want && m_buffer.getMaxWriteSize() > 0 )
1374   {
1375     if (m_cancelled)
1376       return false;
1377
1378     /* if there is data in overflow buffer, try to use that first */
1379     if (m_overflowSize)
1380     {
1381       unsigned amount = XMIN((unsigned int)m_buffer.getMaxWriteSize(), m_overflowSize);
1382       m_buffer.WriteData(m_overflowBuffer, amount);
1383
1384       if (amount < m_overflowSize)
1385         memcpy(m_overflowBuffer, m_overflowBuffer+amount,m_overflowSize-amount);
1386
1387       m_overflowSize -= amount;
1388       m_overflowBuffer = (char*)realloc_simple(m_overflowBuffer, m_overflowSize);
1389       continue;
1390     }
1391
1392     CURLMcode result = g_curlInterface.multi_perform(m_multiHandle, &m_stillRunning);
1393     if (!m_stillRunning)
1394     {
1395       if (result == CURLM_OK)
1396       {
1397         /* if we still have stuff in buffer, we are fine */
1398         if (m_buffer.getMaxReadSize())
1399           return true;
1400
1401         /* verify that we are actually okey */
1402         int msgs;
1403         CURLcode CURLresult = CURLE_OK;
1404         CURLMsg* msg;
1405         while ((msg = g_curlInterface.multi_info_read(m_multiHandle, &msgs)))
1406         {
1407           if (msg->msg == CURLMSG_DONE)
1408           {
1409             if (msg->data.result == CURLE_OK)
1410               return true;
1411
1412             CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Failed: %s(%d)", g_curlInterface.easy_strerror(msg->data.result), msg->data.result);
1413
1414             // We need to check the result here as we don't want to retry on every error
1415             if ( (msg->data.result == CURLE_OPERATION_TIMEDOUT ||
1416                   msg->data.result == CURLE_PARTIAL_FILE       ||
1417                   msg->data.result == CURLE_COULDNT_CONNECT    ||
1418                   msg->data.result == CURLE_RECV_ERROR)        &&
1419                   !m_bFirstLoop)
1420               CURLresult = msg->data.result;
1421             else if ( (msg->data.result == CURLE_HTTP_RANGE_ERROR     ||
1422                        msg->data.result == CURLE_HTTP_RETURNED_ERROR) &&
1423                        m_bFirstLoop                                   &&
1424                        m_filePos == 0                                 &&
1425                        m_sendRange)
1426             {
1427               // If server returns a range or http error, retry with range disabled
1428               CURLresult = msg->data.result;
1429               m_sendRange = false;
1430             }
1431             else
1432               return false;
1433           }
1434         }
1435
1436         // Don't retry when we didn't "see" any error
1437         if (CURLresult == CURLE_OK)
1438           return false;
1439
1440         // Close handle
1441         if (m_multiHandle && m_easyHandle)
1442           g_curlInterface.multi_remove_handle(m_multiHandle, m_easyHandle);
1443
1444         // Reset all the stuff like we would in Disconnect()
1445         m_buffer.Clear();
1446         free(m_overflowBuffer);
1447         m_overflowBuffer = NULL;
1448         m_overflowSize = 0;
1449
1450         // If we got here something is wrong
1451         if (++retry > g_advancedSettings.m_curlretries)
1452         {
1453           CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Reconnect failed!");
1454           // Reset the rest of the variables like we would in Disconnect()
1455           m_filePos = 0;
1456           m_fileSize = 0;
1457           m_bufferSize = 0;
1458
1459           return false;
1460         }
1461
1462         CLog::Log(LOGNOTICE, "CCurlFile::FillBuffer - Reconnect, (re)try %i", retry);
1463
1464         // Connect + seek to current position (again)
1465         SetResume();
1466         g_curlInterface.multi_add_handle(m_multiHandle, m_easyHandle);
1467
1468         // Return to the beginning of the loop:
1469         continue;
1470       }
1471       return false;
1472     }
1473
1474     // We've finished out first loop
1475     if(m_bFirstLoop && m_buffer.getMaxReadSize() > 0)
1476       m_bFirstLoop = false;
1477
1478     switch (result)
1479     {
1480       case CURLM_OK:
1481       {
1482         int maxfd = -1;
1483         FD_ZERO(&fdread);
1484         FD_ZERO(&fdwrite);
1485         FD_ZERO(&fdexcep);
1486
1487         // get file descriptors from the transfers
1488         g_curlInterface.multi_fdset(m_multiHandle, &fdread, &fdwrite, &fdexcep, &maxfd);
1489
1490         long timeout = 0;
1491         if (CURLM_OK != g_curlInterface.multi_timeout(m_multiHandle, &timeout) || timeout == -1)
1492           timeout = 200;
1493
1494         struct timeval t = { timeout / 1000, (timeout % 1000) * 1000 };
1495
1496         /* Wait until data is available or a timeout occurs.
1497            We call dllselect(maxfd + 1, ...), specially in case of (maxfd == -1),
1498            we call dllselect(0, ...), which is basically equal to sleep. */
1499         if (SOCKET_ERROR == dllselect(maxfd + 1, &fdread, &fdwrite, &fdexcep, &t))
1500         {
1501           CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Failed with socket error");
1502           return false;
1503         }
1504       }
1505       break;
1506       case CURLM_CALL_MULTI_PERFORM:
1507       {
1508         // we don't keep calling here as that can easily overwrite our buffer which we want to avoid
1509         // docs says we should call it soon after, but aslong as we are reading data somewhere
1510         // this aught to be soon enough. should stay in socket otherwise
1511         continue;
1512       }
1513       break;
1514       default:
1515       {
1516         CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Multi perform failed with code %d, aborting", result);
1517         return false;
1518       }
1519       break;
1520     }
1521   }
1522   return true;
1523 }
1524
1525 void CCurlFile::CReadState::SetReadBuffer(const void* lpBuf, int64_t uiBufSize)
1526 {
1527   m_readBuffer = (char*)lpBuf;
1528   m_fileSize = uiBufSize;
1529   m_filePos = 0;
1530 }
1531
1532 void CCurlFile::ClearRequestHeaders()
1533 {
1534   m_requestheaders.clear();
1535 }
1536
1537 void CCurlFile::SetRequestHeader(CStdString header, CStdString value)
1538 {
1539   m_requestheaders[header] = value;
1540 }
1541
1542 void CCurlFile::SetRequestHeader(CStdString header, long value)
1543 {
1544   CStdString buffer;
1545   buffer.Format("%ld", value);
1546   m_requestheaders[header] = buffer;
1547 }
1548
1549 /* STATIC FUNCTIONS */
1550 bool CCurlFile::GetHttpHeader(const CURL &url, CHttpHeader &headers)
1551 {
1552   try
1553   {
1554     CCurlFile file;
1555     if(file.Stat(url, NULL) == 0)
1556     {
1557       headers = file.GetHttpHeader();
1558       return true;
1559     }
1560     return false;
1561   }
1562   catch(...)
1563   {
1564     CLog::Log(LOGERROR, "%s - Exception thrown while trying to retrieve header url: %s", __FUNCTION__, url.Get().c_str());
1565     return false;
1566   }
1567 }
1568
1569 bool CCurlFile::GetMimeType(const CURL &url, CStdString &content, CStdString useragent)
1570 {
1571   CCurlFile file;
1572   if (!useragent.IsEmpty())
1573     file.SetUserAgent(useragent);
1574
1575   struct __stat64 buffer;
1576   if( file.Stat(url, &buffer) == 0 )
1577   {
1578     if (buffer.st_mode == _S_IFDIR)
1579       content = "x-directory/normal";
1580     else
1581       content = file.GetMimeType();
1582     CLog::Log(LOGDEBUG, "CCurlFile::GetMimeType - %s -> %s", url.Get().c_str(), content.c_str());
1583     return true;
1584   }
1585   CLog::Log(LOGDEBUG, "CCurlFile::GetMimeType - %s -> failed", url.Get().c_str());
1586   content = "";
1587   return false;
1588 }
1589
1590 int CCurlFile::IoControl(EIoControl request, void* param)
1591 {
1592   if(request == IOCTRL_SEEK_POSSIBLE)
1593     return m_seekable ? 1 : 0;
1594
1595   return -1;
1596 }