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