Merge pull request #4489 from Orochimarufan/sslcipher
[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_cipherlist = "DEFAULT";
400   m_proxytype = PROXY_HTTP;
401   m_state = new CReadState();
402   m_oldState = NULL;
403   m_skipshout = false;
404   m_httpresponse = -1;
405   m_acceptCharset = "UTF-8,*;q=0.8"; /* prefer UTF-8 if available */
406 }
407
408 //Has to be called before Open()
409 void CCurlFile::SetBufferSize(unsigned int size)
410 {
411   m_bufferSize = size;
412 }
413
414 void CCurlFile::Close()
415 {
416   if (m_opened && m_forWrite && !m_inError)
417       Write(NULL, 0);
418
419   m_state->Disconnect();
420   delete m_oldState;
421   m_oldState = NULL;
422
423   m_url.clear();
424   m_referer.clear();
425   m_cookie.clear();
426
427   m_opened = false;
428   m_forWrite = false;
429   m_inError = false;
430 }
431
432 void CCurlFile::SetCommonOptions(CReadState* state)
433 {
434   CURL_HANDLE* h = state->m_easyHandle;
435
436   g_curlInterface.easy_reset(h);
437
438   g_curlInterface.easy_setopt(h, CURLOPT_DEBUGFUNCTION, debug_callback);
439
440   if( g_advancedSettings.m_logLevel >= LOG_LEVEL_DEBUG )
441     g_curlInterface.easy_setopt(h, CURLOPT_VERBOSE, TRUE);
442   else
443     g_curlInterface.easy_setopt(h, CURLOPT_VERBOSE, FALSE);
444
445   g_curlInterface.easy_setopt(h, CURLOPT_WRITEDATA, state);
446   g_curlInterface.easy_setopt(h, CURLOPT_WRITEFUNCTION, write_callback);
447
448   g_curlInterface.easy_setopt(h, CURLOPT_READDATA, state);
449   g_curlInterface.easy_setopt(h, CURLOPT_READFUNCTION, read_callback);
450
451   // set username and password for current handle
452   if (m_username.length() > 0 && m_password.length() > 0)
453   {
454     CStdString userpwd = m_username + ":" + m_password;
455     g_curlInterface.easy_setopt(h, CURLOPT_USERPWD, userpwd.c_str());
456   }
457
458   // make sure headers are seperated from the data stream
459   g_curlInterface.easy_setopt(h, CURLOPT_WRITEHEADER, state);
460   g_curlInterface.easy_setopt(h, CURLOPT_HEADERFUNCTION, header_callback);
461   g_curlInterface.easy_setopt(h, CURLOPT_HEADER, FALSE);
462
463   g_curlInterface.easy_setopt(h, CURLOPT_FTP_USE_EPSV, 0); // turn off epsv
464
465   // Allow us to follow two redirects
466   g_curlInterface.easy_setopt(h, CURLOPT_FOLLOWLOCATION, TRUE);
467   g_curlInterface.easy_setopt(h, CURLOPT_MAXREDIRS, 5);
468
469   // Enable cookie engine for current handle to re-use them in future requests
470   CStdString strCookieFile;
471   CStdString strTempPath = CSpecialProtocol::TranslatePath(g_advancedSettings.m_cachePath);
472   strCookieFile = URIUtils::AddFileToFolder(strTempPath, "cookies.dat");
473
474   g_curlInterface.easy_setopt(h, CURLOPT_COOKIEFILE, strCookieFile.c_str());
475   g_curlInterface.easy_setopt(h, CURLOPT_COOKIEJAR, strCookieFile.c_str());
476
477   // Set custom cookie if requested
478   if (!m_cookie.empty())
479     g_curlInterface.easy_setopt(h, CURLOPT_COOKIE, m_cookie.c_str());
480
481   g_curlInterface.easy_setopt(h, CURLOPT_COOKIELIST, "FLUSH");
482
483   // When using multiple threads you should set the CURLOPT_NOSIGNAL option to
484   // TRUE for all handles. Everything will work fine except that timeouts are not
485   // honored during the DNS lookup - which you can work around by building libcurl
486   // with c-ares support. c-ares is a library that provides asynchronous name
487   // resolves. Unfortunately, c-ares does not yet support IPv6.
488   g_curlInterface.easy_setopt(h, CURLOPT_NOSIGNAL, TRUE);
489
490   // not interested in failed requests
491   g_curlInterface.easy_setopt(h, CURLOPT_FAILONERROR, 1);
492
493   // enable support for icecast / shoutcast streams
494   if ( NULL == state->m_curlAliasList )
495     // m_curlAliasList is used only by this one place, but SetCommonOptions can
496     // be called multiple times, only append to list if it's empty.
497     state->m_curlAliasList = g_curlInterface.slist_append(state->m_curlAliasList, "ICY 200 OK");
498   g_curlInterface.easy_setopt(h, CURLOPT_HTTP200ALIASES, state->m_curlAliasList);
499
500   // never verify peer, we don't have any certificates to do this
501   g_curlInterface.easy_setopt(h, CURLOPT_SSL_VERIFYPEER, 0);
502   g_curlInterface.easy_setopt(h, CURLOPT_SSL_VERIFYHOST, 0);
503
504   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_URL, m_url.c_str());
505   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TRANSFERTEXT, FALSE);
506
507   // setup POST data if it is set (and it may be empty)
508   if (m_postdataset)
509   {
510     g_curlInterface.easy_setopt(h, CURLOPT_POST, 1 );
511     g_curlInterface.easy_setopt(h, CURLOPT_POSTFIELDSIZE, m_postdata.length());
512     g_curlInterface.easy_setopt(h, CURLOPT_POSTFIELDS, m_postdata.c_str());
513   }
514
515   // setup Referer header if needed
516   if (!m_referer.empty())
517     g_curlInterface.easy_setopt(h, CURLOPT_REFERER, m_referer.c_str());
518   else
519   {
520     g_curlInterface.easy_setopt(h, CURLOPT_REFERER, NULL);
521     g_curlInterface.easy_setopt(h, CURLOPT_AUTOREFERER, TRUE);
522   }
523
524   // setup any requested authentication
525   if( m_ftpauth.length() > 0 )
526   {
527     g_curlInterface.easy_setopt(h, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);
528     if( m_ftpauth.Equals("any") )
529       g_curlInterface.easy_setopt(h, CURLOPT_FTPSSLAUTH, CURLFTPAUTH_DEFAULT);
530     else if( m_ftpauth.Equals("ssl") )
531       g_curlInterface.easy_setopt(h, CURLOPT_FTPSSLAUTH, CURLFTPAUTH_SSL);
532     else if( m_ftpauth.Equals("tls") )
533       g_curlInterface.easy_setopt(h, CURLOPT_FTPSSLAUTH, CURLFTPAUTH_TLS);
534   }
535
536   // setup requested http authentication method
537   if(m_httpauth.length() > 0)
538   {
539     if( m_httpauth.Equals("any") )
540       g_curlInterface.easy_setopt(h, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
541     else if( m_httpauth.Equals("anysafe") )
542       g_curlInterface.easy_setopt(h, CURLOPT_HTTPAUTH, CURLAUTH_ANYSAFE);
543     else if( m_httpauth.Equals("digest") )
544       g_curlInterface.easy_setopt(h, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
545     else if( m_httpauth.Equals("ntlm") )
546       g_curlInterface.easy_setopt(h, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
547   }
548
549   // allow passive mode for ftp
550   if( m_ftpport.length() > 0 )
551     g_curlInterface.easy_setopt(h, CURLOPT_FTPPORT, m_ftpport.c_str());
552   else
553     g_curlInterface.easy_setopt(h, CURLOPT_FTPPORT, NULL);
554
555   // allow curl to not use the ip address in the returned pasv response
556   if( m_ftppasvip )
557     g_curlInterface.easy_setopt(h, CURLOPT_FTP_SKIP_PASV_IP, 0);
558   else
559     g_curlInterface.easy_setopt(h, CURLOPT_FTP_SKIP_PASV_IP, 1);
560
561   // setup Content-Encoding if requested
562   if( m_contentencoding.length() > 0 )
563     g_curlInterface.easy_setopt(h, CURLOPT_ENCODING, m_contentencoding.c_str());
564
565   if (!m_useOldHttpVersion && !m_acceptCharset.empty())
566     SetRequestHeader("Accept-Charset", m_acceptCharset);
567
568   if (m_userAgent.length() > 0)
569     g_curlInterface.easy_setopt(h, CURLOPT_USERAGENT, m_userAgent.c_str());
570   else /* set some default agent as shoutcast doesn't return proper stuff otherwise */
571     g_curlInterface.easy_setopt(h, CURLOPT_USERAGENT, g_advancedSettings.m_userAgent.c_str());
572
573   if (m_useOldHttpVersion)
574     g_curlInterface.easy_setopt(h, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
575
576   if (g_advancedSettings.m_curlDisableIPV6)
577     g_curlInterface.easy_setopt(h, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
578
579   if (m_proxy.length() > 0)
580   {
581     g_curlInterface.easy_setopt(h, CURLOPT_PROXY, m_proxy.c_str());
582     g_curlInterface.easy_setopt(h, CURLOPT_PROXYTYPE, proxyType2CUrlProxyType[m_proxytype]);
583     if (m_proxyuserpass.length() > 0)
584       g_curlInterface.easy_setopt(h, CURLOPT_PROXYUSERPWD, m_proxyuserpass.c_str());
585
586   }
587   if (m_customrequest.length() > 0)
588     g_curlInterface.easy_setopt(h, CURLOPT_CUSTOMREQUEST, m_customrequest.c_str());
589
590   if (m_connecttimeout == 0)
591     m_connecttimeout = g_advancedSettings.m_curlconnecttimeout;
592
593   // set our timeouts, we abort connection after m_timeout, and reads after no data for m_timeout seconds
594   g_curlInterface.easy_setopt(h, CURLOPT_CONNECTTIMEOUT, m_connecttimeout);
595
596   // We abort in case we transfer less than 1byte/second
597   g_curlInterface.easy_setopt(h, CURLOPT_LOW_SPEED_LIMIT, 1);
598
599   if (m_lowspeedtime == 0)
600     m_lowspeedtime = g_advancedSettings.m_curllowspeedtime;
601
602   // Set the lowspeed time very low as it seems Curl takes much longer to detect a lowspeed condition
603   g_curlInterface.easy_setopt(h, CURLOPT_LOW_SPEED_TIME, m_lowspeedtime);
604
605   if (m_skipshout)
606     // For shoutcast file, content-length should not be set, and in libcurl there is a bug, if the
607     // cast file was 302 redirected then getinfo of CURLINFO_CONTENT_LENGTH_DOWNLOAD will return
608     // the 302 response's body length, which cause the next read request failed, so we ignore
609     // content-length for shoutcast file to workaround this.
610     g_curlInterface.easy_setopt(h, CURLOPT_IGNORE_CONTENT_LENGTH, 1);
611
612   // Setup allowed TLS/SSL ciphers. New versions of cURL may deprecate things that are still in use.
613   g_curlInterface.easy_setopt(h, CURLOPT_SSL_CIPHER_LIST, m_cipherlist.c_str());
614 }
615
616 void CCurlFile::SetRequestHeaders(CReadState* state)
617 {
618   if(state->m_curlHeaderList)
619   {
620     g_curlInterface.slist_free_all(state->m_curlHeaderList);
621     state->m_curlHeaderList = NULL;
622   }
623
624   MAPHTTPHEADERS::iterator it;
625   for(it = m_requestheaders.begin(); it != m_requestheaders.end(); it++)
626   {
627     CStdString buffer = it->first + ": " + it->second;
628     state->m_curlHeaderList = g_curlInterface.slist_append(state->m_curlHeaderList, buffer.c_str());
629   }
630
631   // add user defined headers
632   if (state->m_easyHandle)
633     g_curlInterface.easy_setopt(state->m_easyHandle, CURLOPT_HTTPHEADER, state->m_curlHeaderList);
634 }
635
636 void CCurlFile::SetCorrectHeaders(CReadState* state)
637 {
638   CHttpHeader& h = state->m_httpheader;
639   /* workaround for shoutcast server wich doesn't set content type on standard mp3 */
640   if( h.GetMimeType().empty() )
641   {
642     if( !h.GetValue("icy-notice1").empty()
643     || !h.GetValue("icy-name").empty()
644     || !h.GetValue("icy-br").empty() )
645       h.AddParam("Content-Type", "audio/mpeg");
646   }
647
648   /* hack for google video */
649   if (StringUtils::EqualsNoCase(h.GetMimeType(),"text/html")
650   &&  !h.GetValue("Content-Disposition").empty() )
651   {
652     CStdString strValue = h.GetValue("Content-Disposition");
653     if (strValue.find("filename=") != std::string::npos &&
654         strValue.find(".flv") != std::string::npos)
655       h.AddParam("Content-Type", "video/flv");
656   }
657 }
658
659 void CCurlFile::ParseAndCorrectUrl(CURL &url2)
660 {
661   CStdString strProtocol = url2.GetTranslatedProtocol();
662   url2.SetProtocol(strProtocol);
663
664   if( strProtocol.Equals("ftp")
665   ||  strProtocol.Equals("ftps") )
666   {
667     // we was using url optons for urls, keep the old code work and warning
668     if (!url2.GetOptions().empty())
669     {
670       CLog::Log(LOGWARNING, "%s: ftp url option is deprecated, please switch to use protocol option (change '?' to '|'), url: [%s]", __FUNCTION__, url2.GetRedacted().c_str());
671       url2.SetProtocolOptions(url2.GetOptions().substr(1));
672       /* ftp has no options */
673       url2.SetOptions("");
674     }
675
676     /* this is uggly, depending on from where   */
677     /* we get the link it may or may not be     */
678     /* url encoded. if handed from ftpdirectory */
679     /* it won't be so let's handle that case    */
680
681     CStdString filename(url2.GetFileName());
682     std::vector<std::string> array;
683
684     // if server sent us the filename in non-utf8, we need send back with same encoding.
685     if (url2.GetProtocolOption("utf8") == "0")
686       g_charsetConverter.utf8ToStringCharset(filename);
687
688     /* TODO: create a tokenizer that doesn't skip empty's */
689     StringUtils::Tokenize(filename, array, "/");
690     filename.clear();
691     for(std::vector<std::string>::iterator it = array.begin(); it != array.end(); it++)
692     {
693       if(it != array.begin())
694         filename += "/";
695
696       filename += CURL::Encode(*it);
697     }
698
699     /* make sure we keep slashes */
700     if(StringUtils::EndsWith(url2.GetFileName(), "/"))
701       filename += "/";
702
703     url2.SetFileName(filename);
704
705     m_ftpauth = "";
706     if (url2.HasProtocolOption("auth"))
707     {
708       m_ftpauth = url2.GetProtocolOption("auth");
709       if(m_ftpauth.empty())
710         m_ftpauth = "any";
711     }
712     m_ftpport = "";
713     if (url2.HasProtocolOption("active"))
714     {
715       m_ftpport = url2.GetProtocolOption("active");
716       if(m_ftpport.empty())
717         m_ftpport = "-";
718     }
719     m_ftppasvip = url2.HasProtocolOption("pasvip") && url2.GetProtocolOption("pasvip") != "0";
720   }
721   else if( strProtocol.Equals("http")
722        ||  strProtocol.Equals("https"))
723   {
724     if (CSettings::Get().GetBool("network.usehttpproxy")
725         && !CSettings::Get().GetString("network.httpproxyserver").empty()
726         && CSettings::Get().GetInt("network.httpproxyport") > 0
727         && m_proxy.empty())
728     {
729       m_proxy = CSettings::Get().GetString("network.httpproxyserver");
730       m_proxy += StringUtils::Format(":%d", CSettings::Get().GetInt("network.httpproxyport"));
731       if (CSettings::Get().GetString("network.httpproxyusername").length() > 0 && m_proxyuserpass.empty())
732       {
733         m_proxyuserpass = CSettings::Get().GetString("network.httpproxyusername");
734         m_proxyuserpass += ":" + CSettings::Get().GetString("network.httpproxypassword");
735       }
736       m_proxytype = (ProxyType)CSettings::Get().GetInt("network.httpproxytype");
737       CLog::Log(LOGDEBUG, "Using proxy %s, type %d", m_proxy.c_str(), proxyType2CUrlProxyType[m_proxytype]);
738     }
739
740     // get username and password
741     m_username = url2.GetUserName();
742     m_password = url2.GetPassWord();
743
744     // handle any protocol options
745     std::map<CStdString, CStdString> options;
746     url2.GetProtocolOptions(options);
747     if (options.size() > 0)
748     {
749       // clear protocol options
750       url2.SetProtocolOptions("");
751       // set xbmc headers
752       for(std::map<CStdString, CStdString>::const_iterator it = options.begin(); it != options.end(); ++it)
753       {
754         const CStdString &name = it->first;
755         const CStdString &value = it->second;
756
757         if(name.Equals("auth"))
758         {
759           m_httpauth = value;
760           if(m_httpauth.empty())
761             m_httpauth = "any";
762         }
763         else if (name.Equals("Referer"))
764           SetReferer(value);
765         else if (name.Equals("User-Agent"))
766           SetUserAgent(value);
767         else if (name.Equals("Cookie"))
768           SetCookie(value);
769         else if (name.Equals("Encoding"))
770           SetContentEncoding(value);
771         else if (name.Equals("noshout") && value.Equals("true"))
772           m_skipshout = true;
773         else if (name.Equals("seekable") && value.Equals("0"))
774           m_seekable = false;
775         else if (name.Equals("Accept-Charset"))
776           SetAcceptCharset(value);
777         else if (name.Equals("HttpProxy"))
778           SetStreamProxy(value, PROXY_HTTP);
779         else if (name.Equals("SSLCipherList"))
780           m_cipherlist = value;
781         else
782           SetRequestHeader(name, value);
783       }
784     }
785   }
786
787   if (m_username.length() > 0 && m_password.length() > 0)
788     m_url = url2.GetWithoutUserDetails();
789   else
790     m_url = url2.Get();
791 }
792
793 void CCurlFile::SetStreamProxy(const CStdString &proxy, ProxyType type)
794 {
795   CURL url(proxy);
796   m_proxy = url.GetWithoutUserDetails();
797   m_proxyuserpass = url.GetUserName();
798   if (!url.GetPassWord().empty())
799     m_proxyuserpass += ":" + url.GetPassWord();
800   m_proxytype = type;
801   CLog::Log(LOGDEBUG, "Overriding proxy from URL parameter: %s, type %d", m_proxy.c_str(), proxyType2CUrlProxyType[m_proxytype]);
802 }
803
804 bool CCurlFile::Post(const CStdString& strURL, const CStdString& strPostData, CStdString& strHTML)
805 {
806   m_postdata = strPostData;
807   m_postdataset = true;
808   return Service(strURL, strHTML);
809 }
810
811 bool CCurlFile::Get(const CStdString& strURL, CStdString& strHTML)
812 {
813   m_postdata = "";
814   m_postdataset = false;
815   return Service(strURL, strHTML);
816 }
817
818 bool CCurlFile::Service(const CStdString& strURL, CStdString& strHTML)
819 {
820   if (Open(strURL))
821   {
822     if (ReadData(strHTML))
823     {
824       Close();
825       return true;
826     }
827   }
828   Close();
829   return false;
830 }
831
832 bool CCurlFile::ReadData(CStdString& strHTML)
833 {
834   int size_read = 0;
835   int data_size = 0;
836   strHTML = "";
837   char buffer[16384];
838   while( (size_read = Read(buffer, sizeof(buffer)-1) ) > 0 )
839   {
840     buffer[size_read] = 0;
841     strHTML.append(buffer, size_read);
842     data_size += size_read;
843   }
844   if (m_state->m_cancelled)
845     return false;
846   return true;
847 }
848
849 bool CCurlFile::Download(const CStdString& strURL, const CStdString& strFileName, LPDWORD pdwSize)
850 {
851   CLog::Log(LOGINFO, "CCurlFile::Download - %s->%s", strURL.c_str(), strFileName.c_str());
852
853   CStdString strData;
854   if (!Get(strURL, strData))
855     return false;
856
857   XFILE::CFile file;
858   if (!file.OpenForWrite(strFileName, true))
859   {
860     CLog::Log(LOGERROR, "CCurlFile::Download - Unable to open file %s: %u",
861     strFileName.c_str(), GetLastError());
862     return false;
863   }
864   if (strData.size())
865     file.Write(strData.c_str(), strData.size());
866   file.Close();
867
868   if (pdwSize != NULL)
869   {
870     *pdwSize = strData.size();
871   }
872
873   return true;
874 }
875
876 // Detect whether we are "online" or not! Very simple and dirty!
877 bool CCurlFile::IsInternet()
878 {
879   CStdString strURL = "http://www.google.com";
880   bool found = Exists(strURL);
881   Close();
882
883   return found;
884 }
885
886 void CCurlFile::Cancel()
887 {
888   m_state->m_cancelled = true;
889   while (m_opened)
890     Sleep(1);
891 }
892
893 void CCurlFile::Reset()
894 {
895   m_state->m_cancelled = false;
896 }
897
898 bool CCurlFile::Open(const CURL& url)
899 {
900   m_opened = true;
901   m_seekable = true;
902
903   CURL url2(url);
904   ParseAndCorrectUrl(url2);
905
906   std::string redactPath = CURL::GetRedacted(m_url);
907   CLog::Log(LOGDEBUG, "CurlFile::Open(%p) %s", (void*)this, redactPath.c_str());
908
909   ASSERT(!(!m_state->m_easyHandle ^ !m_state->m_multiHandle));
910   if( m_state->m_easyHandle == NULL )
911     g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, &m_state->m_multiHandle );
912
913   // setup common curl options
914   SetCommonOptions(m_state);
915   SetRequestHeaders(m_state);
916   m_state->m_sendRange = m_seekable;
917
918   m_httpresponse = m_state->Connect(m_bufferSize);
919   if( m_httpresponse < 0 || m_httpresponse >= 400)
920     return false;
921
922   SetCorrectHeaders(m_state);
923
924   // since we can't know the stream size up front if we're gzipped/deflated
925   // flag the stream with an unknown file size rather than the compressed
926   // file size.
927   if (m_contentencoding.size() > 0)
928     m_state->m_fileSize = 0;
929
930   // check if this stream is a shoutcast stream. sometimes checking the protocol line is not enough so examine other headers as well.
931   // shoutcast streams should be handled by FileShoutcast.
932   if ((m_state->m_httpheader.GetProtoLine().substr(0, 3) == "ICY" || !m_state->m_httpheader.GetValue("icy-notice1").empty()
933      || !m_state->m_httpheader.GetValue("icy-name").empty()
934      || !m_state->m_httpheader.GetValue("icy-br").empty()) && !m_skipshout)
935   {
936     CLog::Log(LOGDEBUG,"CCurlFile::Open - File <%s> is a shoutcast stream. Re-opening", redactPath.c_str());
937     throw new CRedirectException(new CShoutcastFile);
938   }
939
940   m_multisession = false;
941   if(url2.GetProtocol().Equals("http") || url2.GetProtocol().Equals("https"))
942   {
943     m_multisession = true;
944     if(m_state->m_httpheader.GetValue("Server").find("Portable SDK for UPnP devices") != std::string::npos)
945     {
946       CLog::Log(LOGWARNING, "CCurlFile::Open - Disabling multi session due to broken libupnp server");
947       m_multisession = false;
948     }
949   }
950
951   if(StringUtils::EqualsNoCase(m_state->m_httpheader.GetValue("Transfer-Encoding"), "chunked"))
952     m_state->m_fileSize = 0;
953
954   if(m_state->m_fileSize <= 0)
955     m_seekable = false;
956   if (m_seekable)
957   {
958     if(url2.GetProtocol().Equals("http")
959     || url2.GetProtocol().Equals("https"))
960     {
961       // if server says explicitly it can't seek, respect that
962       if(StringUtils::EqualsNoCase(m_state->m_httpheader.GetValue("Accept-Ranges"),"none"))
963         m_seekable = false;
964     }
965   }
966
967   char* efurl;
968   if (CURLE_OK == g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_EFFECTIVE_URL,&efurl) && efurl)
969     m_url = efurl;
970
971   return true;
972 }
973
974 bool CCurlFile::OpenForWrite(const CURL& url, bool bOverWrite)
975 {
976   if(m_opened)
977     return false;
978
979   if (Exists(url) && !bOverWrite)
980     return false;
981
982   CURL url2(url);
983   ParseAndCorrectUrl(url2);
984
985   CLog::Log(LOGDEBUG, "CCurlFile::OpenForWrite(%p) %s", (void*)this, CURL::GetRedacted(m_url).c_str());
986
987   ASSERT(m_state->m_easyHandle == NULL);
988   g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, &m_state->m_multiHandle);
989
990     // setup common curl options
991   SetCommonOptions(m_state);
992   SetRequestHeaders(m_state);
993
994   char* efurl;
995   if (CURLE_OK == g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_EFFECTIVE_URL,&efurl) && efurl)
996     m_url = efurl;
997
998   m_opened = true;
999   m_forWrite = true;
1000   m_inError = false;
1001   m_writeOffset = 0;
1002
1003   ASSERT(m_state->m_multiHandle);
1004
1005   SetCommonOptions(m_state); 
1006   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_UPLOAD, 1);
1007
1008   g_curlInterface.multi_add_handle(m_state->m_multiHandle, m_state->m_easyHandle);
1009
1010   m_state->SetReadBuffer(NULL, 0);
1011
1012   return true;
1013 }
1014
1015 int CCurlFile::Write(const void* lpBuf, int64_t uiBufSize)
1016 {
1017   if (!(m_opened && m_forWrite) || m_inError)
1018     return -1;
1019
1020   ASSERT(m_state->m_multiHandle);
1021
1022   m_state->SetReadBuffer(lpBuf, uiBufSize);
1023   m_state->m_isPaused = false;
1024   g_curlInterface.easy_pause(m_state->m_easyHandle, CURLPAUSE_CONT);
1025
1026   CURLMcode result = CURLM_OK;
1027
1028   m_stillRunning = 1;
1029   while (m_stillRunning && !m_state->m_isPaused)
1030   {
1031     while ((result = g_curlInterface.multi_perform(m_state->m_multiHandle, &m_stillRunning)) == CURLM_CALL_MULTI_PERFORM);
1032
1033     if (!m_stillRunning)
1034       break;
1035
1036     if (result != CURLM_OK)
1037     {
1038       long code;
1039       if(g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_RESPONSE_CODE, &code) == CURLE_OK )
1040         CLog::Log(LOGERROR, "%s - Unable to write curl resource (%s) - %ld", __FUNCTION__, CURL::GetRedacted(m_url).c_str(), code);
1041       m_inError = true;
1042       return -1;
1043     }
1044   }
1045
1046   m_writeOffset += m_state->m_filePos;
1047   return m_state->m_filePos;
1048 }
1049
1050 bool CCurlFile::CReadState::ReadString(char *szLine, int iLineLength)
1051 {
1052   unsigned int want = (unsigned int)iLineLength;
1053
1054   if((m_fileSize == 0 || m_filePos < m_fileSize) && !FillBuffer(want))
1055     return false;
1056
1057   // ensure only available data is considered
1058   want = XMIN((unsigned int)m_buffer.getMaxReadSize(), want);
1059
1060   /* check if we finished prematurely */
1061   if (!m_stillRunning && (m_fileSize == 0 || m_filePos != m_fileSize) && !want)
1062   {
1063     if (m_fileSize != 0)
1064       CLog::Log(LOGWARNING, "%s - Transfer ended before entire file was retrieved pos %"PRId64", size %"PRId64, __FUNCTION__, m_filePos, m_fileSize);
1065
1066     return false;
1067   }
1068
1069   char* pLine = szLine;
1070   do
1071   {
1072     if (!m_buffer.ReadData(pLine, 1))
1073       break;
1074
1075     pLine++;
1076   } while (((pLine - 1)[0] != '\n') && ((unsigned int)(pLine - szLine) < want));
1077   pLine[0] = 0;
1078   m_filePos += (pLine - szLine);
1079   return (bool)((pLine - szLine) > 0);
1080 }
1081
1082 bool CCurlFile::Exists(const CURL& url)
1083 {
1084   // if file is already running, get info from it
1085   if( m_opened )
1086   {
1087     CLog::Log(LOGWARNING, "CCurlFile::Exists - Exist called on open file %s", url.GetRedacted().c_str());
1088     return true;
1089   }
1090
1091   CURL url2(url);
1092   ParseAndCorrectUrl(url2);
1093
1094   ASSERT(m_state->m_easyHandle == NULL);
1095   g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, NULL);
1096
1097   SetCommonOptions(m_state);
1098   SetRequestHeaders(m_state);
1099   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TIMEOUT, 5);
1100   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_NOBODY, 1);
1101   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_WRITEDATA, NULL); /* will cause write failure*/
1102
1103   if(url2.GetProtocol() == "ftp")
1104   {
1105     g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FILETIME, 1);
1106     // nocwd is less standard, will return empty list for non-existed remote dir on some ftp server, avoid it.
1107     if (StringUtils::EndsWith(url2.GetFileName(), "/"))
1108       g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_SINGLECWD);
1109     else
1110       g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_NOCWD);
1111   }
1112
1113   CURLcode result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1114   g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1115
1116   if (result == CURLE_WRITE_ERROR || result == CURLE_OK)
1117     return true;
1118
1119   if (result == CURLE_HTTP_RETURNED_ERROR)
1120   {
1121     long code;
1122     if(g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_RESPONSE_CODE, &code) == CURLE_OK && code != 404 )
1123       CLog::Log(LOGERROR, "CCurlFile::Exists - Failed: HTTP returned error %ld for %s", code, url.GetRedacted().c_str());
1124   }
1125   else if (result != CURLE_REMOTE_FILE_NOT_FOUND && result != CURLE_FTP_COULDNT_RETR_FILE)
1126   {
1127     CLog::Log(LOGERROR, "CCurlFile::Exists - Failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.GetRedacted().c_str());
1128   }
1129
1130   errno = ENOENT;
1131   return false;
1132 }
1133
1134 int64_t CCurlFile::Seek(int64_t iFilePosition, int iWhence)
1135 {
1136   int64_t nextPos = m_state->m_filePos;
1137   switch(iWhence)
1138   {
1139     case SEEK_SET:
1140       nextPos = iFilePosition;
1141       break;
1142     case SEEK_CUR:
1143       nextPos += iFilePosition;
1144       break;
1145     case SEEK_END:
1146       if (m_state->m_fileSize)
1147         nextPos = m_state->m_fileSize + iFilePosition;
1148       else
1149         return -1;
1150       break;
1151     default:
1152       return -1;
1153   }
1154
1155   // We can't seek beyond EOF
1156   if (m_state->m_fileSize && nextPos > m_state->m_fileSize) return -1;
1157
1158   if(m_state->Seek(nextPos))
1159     return nextPos;
1160
1161   if (m_oldState && m_oldState->Seek(nextPos))
1162   {
1163     CReadState *tmp = m_state;
1164     m_state = m_oldState;
1165     m_oldState = tmp;
1166     return nextPos;
1167   }
1168
1169   if(!m_seekable)
1170     return -1;
1171
1172   CReadState* oldstate = NULL;
1173   if(m_multisession)
1174   {
1175     CURL url(m_url);
1176     oldstate = m_oldState;
1177     m_oldState = m_state;
1178     m_state = new CReadState();
1179
1180     g_curlInterface.easy_aquire(url.GetProtocol(), url.GetHostName(), &m_state->m_easyHandle, &m_state->m_multiHandle );
1181
1182     m_state->m_fileSize = m_oldState->m_fileSize;
1183   }
1184   else
1185     m_state->Disconnect();
1186
1187   // re-setup common curl options
1188   SetCommonOptions(m_state);
1189
1190   /* caller might have changed some headers (needed for daap)*/
1191   SetRequestHeaders(m_state);
1192
1193   m_state->m_filePos = nextPos;
1194   m_state->m_sendRange = true;
1195
1196   long response = m_state->Connect(m_bufferSize);
1197   if(response < 0 && (m_state->m_fileSize == 0 || m_state->m_fileSize != m_state->m_filePos))
1198   {
1199     m_seekable = false;
1200     if(m_multisession && m_oldState)
1201     {
1202       delete m_state;
1203       m_state = m_oldState;
1204       m_oldState = oldstate;
1205     }
1206     return -1;
1207   }
1208
1209   SetCorrectHeaders(m_state);
1210   delete oldstate;
1211
1212   return m_state->m_filePos;
1213 }
1214
1215 int64_t CCurlFile::GetLength()
1216 {
1217   if (!m_opened) return 0;
1218   return m_state->m_fileSize;
1219 }
1220
1221 int64_t CCurlFile::GetPosition()
1222 {
1223   if (!m_opened) return 0;
1224   return m_state->m_filePos;
1225 }
1226
1227 int CCurlFile::Stat(const CURL& url, struct __stat64* buffer)
1228 {
1229   // if file is already running, get info from it
1230   if( m_opened )
1231   {
1232     CLog::Log(LOGWARNING, "CCurlFile::Stat - Stat called on open file %s", url.GetRedacted().c_str());
1233     if (buffer)
1234     {
1235       memset(buffer, 0, sizeof(struct __stat64));
1236       buffer->st_size = GetLength();
1237       buffer->st_mode = _S_IFREG;
1238     }
1239     return 0;
1240   }
1241
1242   CURL url2(url);
1243   ParseAndCorrectUrl(url2);
1244
1245   ASSERT(m_state->m_easyHandle == NULL);
1246   g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, NULL);
1247
1248   SetCommonOptions(m_state);
1249   SetRequestHeaders(m_state);
1250   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TIMEOUT, g_advancedSettings.m_curlconnecttimeout);
1251   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_NOBODY, 1);
1252   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_WRITEDATA, NULL); /* will cause write failure*/
1253   g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FILETIME , 1); 
1254
1255   if(url2.GetProtocol() == "ftp")
1256   {
1257     // nocwd is less standard, will return empty list for non-existed remote dir on some ftp server, avoid it.
1258     if (StringUtils::EndsWith(url2.GetFileName(), "/"))
1259       g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_SINGLECWD);
1260     else
1261       g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_NOCWD);
1262   }
1263
1264   CURLcode result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1265
1266   if(result == CURLE_HTTP_RETURNED_ERROR)
1267   {
1268     long code;
1269     if(g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_RESPONSE_CODE, &code) == CURLE_OK && code == 404 )
1270       return -1;
1271   }
1272
1273   if(result == CURLE_GOT_NOTHING 
1274   || result == CURLE_HTTP_RETURNED_ERROR 
1275   || result == CURLE_RECV_ERROR /* some silly shoutcast servers */ )
1276   {
1277     /* some http servers and shoutcast servers don't give us any data on a head request */
1278     /* request normal and just fail out, it's their loss */
1279     /* somehow curl doesn't reset CURLOPT_NOBODY properly so reset everything */
1280     SetCommonOptions(m_state);
1281     SetRequestHeaders(m_state);
1282     g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TIMEOUT, g_advancedSettings.m_curlconnecttimeout);
1283     g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_RANGE, "0-0");
1284     g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_WRITEDATA, NULL); /* will cause write failure*/
1285     g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FILETIME, 1); 
1286     result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1287   }
1288
1289   if( result == CURLE_HTTP_RANGE_ERROR )
1290   {
1291     /* crap can't use the range option, disable it and try again */
1292     g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_RANGE, NULL);
1293     result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1294   }
1295
1296   if( result != CURLE_WRITE_ERROR && result != CURLE_OK )
1297   {
1298     g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1299     errno = ENOENT;
1300     CLog::Log(LOGERROR, "CCurlFile::Stat - Failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.GetRedacted().c_str());
1301     return -1;
1302   }
1303
1304   double length;
1305   result = g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &length);
1306   if (result != CURLE_OK || length < 0.0)
1307   {
1308     if (url.GetProtocol() == "ftp")
1309     {
1310       g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1311       CLog::Log(LOGNOTICE, "CCurlFile::Stat - Content length failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.GetRedacted().c_str());
1312       errno = ENOENT;
1313       return -1;
1314     }
1315     else
1316       length = 0.0;
1317   }
1318
1319   SetCorrectHeaders(m_state);
1320
1321   if(buffer)
1322   {
1323     char *content;
1324     result = g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_CONTENT_TYPE, &content);
1325     if (result != CURLE_OK)
1326     {
1327       CLog::Log(LOGNOTICE, "CCurlFile::Stat - Content type failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.GetRedacted().c_str());
1328       g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1329       errno = ENOENT;
1330       return -1;
1331     }
1332     else
1333     {
1334       memset(buffer, 0, sizeof(struct __stat64));
1335       buffer->st_size = (int64_t)length;
1336       if(content && strstr(content, "text/html")) //consider html files directories
1337         buffer->st_mode = _S_IFDIR;
1338       else
1339         buffer->st_mode = _S_IFREG;
1340     }
1341     long filetime;
1342     result = g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_FILETIME, &filetime);
1343     if (result != CURLE_OK)
1344     {
1345       CLog::Log(LOGNOTICE, "CCurlFile::Stat - Filetime failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.GetRedacted().c_str());
1346     }
1347     else
1348     {
1349       if (filetime != -1)
1350         buffer->st_mtime = filetime;
1351     }
1352   }
1353   g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1354   return 0;
1355 }
1356
1357 unsigned int CCurlFile::CReadState::Read(void* lpBuf, int64_t uiBufSize)
1358 {
1359   /* only request 1 byte, for truncated reads (only if not eof) */
1360   if((m_fileSize == 0 || m_filePos < m_fileSize) && !FillBuffer(1))
1361     return 0;
1362
1363   /* ensure only available data is considered */
1364   unsigned int want = (unsigned int)XMIN(m_buffer.getMaxReadSize(), uiBufSize);
1365
1366   /* xfer data to caller */
1367   if (m_buffer.ReadData((char *)lpBuf, want))
1368   {
1369     m_filePos += want;
1370     return want;
1371   }
1372
1373   /* check if we finished prematurely */
1374   if (!m_stillRunning && (m_fileSize == 0 || m_filePos != m_fileSize))
1375   {
1376     CLog::Log(LOGWARNING, "%s - Transfer ended before entire file was retrieved pos %"PRId64", size %"PRId64, __FUNCTION__, m_filePos, m_fileSize);
1377     return 0;
1378   }
1379
1380   return 0;
1381 }
1382
1383 /* use to attempt to fill the read buffer up to requested number of bytes */
1384 bool CCurlFile::CReadState::FillBuffer(unsigned int want)
1385 {
1386   int retry = 0;
1387   fd_set fdread;
1388   fd_set fdwrite;
1389   fd_set fdexcep;
1390
1391   // only attempt to fill buffer if transactions still running and buffer
1392   // doesnt exceed required size already
1393   while ((unsigned int)m_buffer.getMaxReadSize() < want && m_buffer.getMaxWriteSize() > 0 )
1394   {
1395     if (m_cancelled)
1396       return false;
1397
1398     /* if there is data in overflow buffer, try to use that first */
1399     if (m_overflowSize)
1400     {
1401       unsigned amount = XMIN((unsigned int)m_buffer.getMaxWriteSize(), m_overflowSize);
1402       m_buffer.WriteData(m_overflowBuffer, amount);
1403
1404       if (amount < m_overflowSize)
1405         memcpy(m_overflowBuffer, m_overflowBuffer+amount,m_overflowSize-amount);
1406
1407       m_overflowSize -= amount;
1408       m_overflowBuffer = (char*)realloc_simple(m_overflowBuffer, m_overflowSize);
1409       continue;
1410     }
1411
1412     CURLMcode result = g_curlInterface.multi_perform(m_multiHandle, &m_stillRunning);
1413     if (!m_stillRunning)
1414     {
1415       if (result == CURLM_OK)
1416       {
1417         /* if we still have stuff in buffer, we are fine */
1418         if (m_buffer.getMaxReadSize())
1419           return true;
1420
1421         /* verify that we are actually okey */
1422         int msgs;
1423         CURLcode CURLresult = CURLE_OK;
1424         CURLMsg* msg;
1425         while ((msg = g_curlInterface.multi_info_read(m_multiHandle, &msgs)))
1426         {
1427           if (msg->msg == CURLMSG_DONE)
1428           {
1429             if (msg->data.result == CURLE_OK)
1430               return true;
1431
1432             CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Failed: %s(%d)", g_curlInterface.easy_strerror(msg->data.result), msg->data.result);
1433
1434             // We need to check the result here as we don't want to retry on every error
1435             if ( (msg->data.result == CURLE_OPERATION_TIMEDOUT ||
1436                   msg->data.result == CURLE_PARTIAL_FILE       ||
1437                   msg->data.result == CURLE_COULDNT_CONNECT    ||
1438                   msg->data.result == CURLE_RECV_ERROR)        &&
1439                   !m_bFirstLoop)
1440               CURLresult = msg->data.result;
1441             else if ( (msg->data.result == CURLE_HTTP_RANGE_ERROR     ||
1442                        msg->data.result == CURLE_HTTP_RETURNED_ERROR) &&
1443                        m_bFirstLoop                                   &&
1444                        m_filePos == 0                                 &&
1445                        m_sendRange)
1446             {
1447               // If server returns a range or http error, retry with range disabled
1448               CURLresult = msg->data.result;
1449               m_sendRange = false;
1450             }
1451             else
1452               return false;
1453           }
1454         }
1455
1456         // Don't retry when we didn't "see" any error
1457         if (CURLresult == CURLE_OK)
1458           return false;
1459
1460         // Close handle
1461         if (m_multiHandle && m_easyHandle)
1462           g_curlInterface.multi_remove_handle(m_multiHandle, m_easyHandle);
1463
1464         // Reset all the stuff like we would in Disconnect()
1465         m_buffer.Clear();
1466         free(m_overflowBuffer);
1467         m_overflowBuffer = NULL;
1468         m_overflowSize = 0;
1469
1470         // If we got here something is wrong
1471         if (++retry > g_advancedSettings.m_curlretries)
1472         {
1473           CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Reconnect failed!");
1474           // Reset the rest of the variables like we would in Disconnect()
1475           m_filePos = 0;
1476           m_fileSize = 0;
1477           m_bufferSize = 0;
1478
1479           return false;
1480         }
1481
1482         CLog::Log(LOGNOTICE, "CCurlFile::FillBuffer - Reconnect, (re)try %i", retry);
1483
1484         // Connect + seek to current position (again)
1485         SetResume();
1486         g_curlInterface.multi_add_handle(m_multiHandle, m_easyHandle);
1487
1488         // Return to the beginning of the loop:
1489         continue;
1490       }
1491       return false;
1492     }
1493
1494     // We've finished out first loop
1495     if(m_bFirstLoop && m_buffer.getMaxReadSize() > 0)
1496       m_bFirstLoop = false;
1497
1498     switch (result)
1499     {
1500       case CURLM_OK:
1501       {
1502         int maxfd = -1;
1503         FD_ZERO(&fdread);
1504         FD_ZERO(&fdwrite);
1505         FD_ZERO(&fdexcep);
1506
1507         // get file descriptors from the transfers
1508         g_curlInterface.multi_fdset(m_multiHandle, &fdread, &fdwrite, &fdexcep, &maxfd);
1509
1510         long timeout = 0;
1511         if (CURLM_OK != g_curlInterface.multi_timeout(m_multiHandle, &timeout) || timeout == -1)
1512           timeout = 200;
1513
1514         struct timeval t = { timeout / 1000, (timeout % 1000) * 1000 };
1515
1516         /* Wait until data is available or a timeout occurs.
1517            We call dllselect(maxfd + 1, ...), specially in case of (maxfd == -1),
1518            we call dllselect(0, ...), which is basically equal to sleep. */
1519         if (SOCKET_ERROR == dllselect(maxfd + 1, &fdread, &fdwrite, &fdexcep, &t))
1520         {
1521           CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Failed with socket error");
1522           return false;
1523         }
1524       }
1525       break;
1526       case CURLM_CALL_MULTI_PERFORM:
1527       {
1528         // we don't keep calling here as that can easily overwrite our buffer which we want to avoid
1529         // docs says we should call it soon after, but aslong as we are reading data somewhere
1530         // this aught to be soon enough. should stay in socket otherwise
1531         continue;
1532       }
1533       break;
1534       default:
1535       {
1536         CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Multi perform failed with code %d, aborting", result);
1537         return false;
1538       }
1539       break;
1540     }
1541   }
1542   return true;
1543 }
1544
1545 void CCurlFile::CReadState::SetReadBuffer(const void* lpBuf, int64_t uiBufSize)
1546 {
1547   m_readBuffer = (char*)lpBuf;
1548   m_fileSize = uiBufSize;
1549   m_filePos = 0;
1550 }
1551
1552 void CCurlFile::ClearRequestHeaders()
1553 {
1554   m_requestheaders.clear();
1555 }
1556
1557 void CCurlFile::SetRequestHeader(CStdString header, CStdString value)
1558 {
1559   m_requestheaders[header] = value;
1560 }
1561
1562 void CCurlFile::SetRequestHeader(CStdString header, long value)
1563 {
1564   m_requestheaders[header] = StringUtils::Format("%ld", value);
1565 }
1566
1567 std::string CCurlFile::GetServerReportedCharset(void)
1568 {
1569   if (!m_state)
1570     return "";
1571
1572   return m_state->m_httpheader.GetCharset();
1573 }
1574
1575 /* STATIC FUNCTIONS */
1576 bool CCurlFile::GetHttpHeader(const CURL &url, CHttpHeader &headers)
1577 {
1578   try
1579   {
1580     CCurlFile file;
1581     if(file.Stat(url, NULL) == 0)
1582     {
1583       headers = file.GetHttpHeader();
1584       return true;
1585     }
1586     return false;
1587   }
1588   catch(...)
1589   {
1590     CLog::Log(LOGERROR, "%s - Exception thrown while trying to retrieve header url: %s", __FUNCTION__, url.GetRedacted().c_str());
1591     return false;
1592   }
1593 }
1594
1595 bool CCurlFile::GetMimeType(const CURL &url, CStdString &content, CStdString useragent)
1596 {
1597   CCurlFile file;
1598   if (!useragent.empty())
1599     file.SetUserAgent(useragent);
1600
1601   struct __stat64 buffer;
1602   std::string redactUrl = url.GetRedacted();
1603   if( file.Stat(url, &buffer) == 0 )
1604   {
1605     if (buffer.st_mode == _S_IFDIR)
1606       content = "x-directory/normal";
1607     else
1608       content = file.GetMimeType();
1609     CLog::Log(LOGDEBUG, "CCurlFile::GetMimeType - %s -> %s", redactUrl.c_str(), content.c_str());
1610     return true;
1611   }
1612   CLog::Log(LOGDEBUG, "CCurlFile::GetMimeType - %s -> failed", redactUrl.c_str());
1613   content = "";
1614   return false;
1615 }
1616
1617 bool CCurlFile::GetCookies(const CURL &url, std::string &cookies)
1618 {
1619   std::string cookiesStr;
1620   struct curl_slist*     curlCookies;
1621   XCURL::CURL_HANDLE*    easyHandle;
1622   XCURL::CURLM*          multiHandle;
1623
1624   // get the cookies list
1625   g_curlInterface.easy_aquire(url.GetProtocol(), url.GetHostName(), &easyHandle, &multiHandle);
1626   if (CURLE_OK == g_curlInterface.easy_getinfo(easyHandle, CURLINFO_COOKIELIST, &curlCookies))
1627   {
1628     // iterate over each cookie and format it into an RFC 2109 formatted Set-Cookie string
1629     struct curl_slist* curlCookieIter = curlCookies;
1630     while(curlCookieIter)
1631     {
1632       // tokenize the CURL cookie string
1633       std::vector<std::string> valuesVec;
1634       StringUtils::Tokenize(curlCookieIter->data, valuesVec, "\t");
1635
1636       // ensure the length is valid
1637       if (valuesVec.size() < 7)
1638       {
1639         CLog::Log(LOGERROR, "CCurlFile::GetCookies - invalid cookie: '%s'", curlCookieIter->data);
1640         curlCookieIter = curlCookieIter->next;
1641         continue;
1642       }
1643
1644       // create a http-header formatted cookie string
1645       std::string cookieStr = valuesVec[5] + "=" + valuesVec[6] +
1646                               "; path=" + valuesVec[2] +
1647                               "; domain=" + valuesVec[0];
1648
1649       // append this cookie to the string containing all cookies
1650       if (!cookiesStr.empty())
1651         cookiesStr += "\n";
1652       cookiesStr += cookieStr;
1653
1654       // move on to the next cookie
1655       curlCookieIter = curlCookieIter->next;
1656     }
1657
1658     // free the curl cookies
1659     g_curlInterface.slist_free_all(curlCookies);
1660
1661     // release our handles
1662     g_curlInterface.easy_release(&easyHandle, &multiHandle);
1663
1664     // if we have a non-empty cookie string, return it
1665     if (!cookiesStr.empty())
1666     {
1667       cookies = cookiesStr;
1668       return true;
1669     }
1670   }
1671
1672   // no cookies to return
1673   return false;
1674 }
1675
1676 int CCurlFile::IoControl(EIoControl request, void* param)
1677 {
1678   if(request == IOCTRL_SEEK_POSSIBLE)
1679     return m_seekable ? 1 : 0;
1680
1681   return -1;
1682 }