2 * Copyright (C) 2005-2013 Team XBMC
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)
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.
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/>.
22 #include "utils/URIUtils.h"
25 #include "settings/AdvancedSettings.h"
26 #include "settings/Settings.h"
28 #include "threads/SystemClock.h"
36 #include "../linux/XFileUtils.h"
37 #include "../linux/XTimeUtils.h"
38 #include "../linux/ConvUtils.h"
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"
48 using namespace XFILE;
49 using namespace XCURL;
51 #define XMIN(a,b) ((a)<(b)?(a):(b))
52 #define FITS_INT(a) (((a) <= INT_MAX) && ((a) >= INT_MIN))
54 curl_proxytype proxyType2CUrlProxyType[] = {
59 CURLPROXY_SOCKS5_HOSTNAME,
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)
65 if (info == CURLINFO_DATA_IN || info == CURLINFO_DATA_OUT)
68 if ((g_advancedSettings.m_extraLogLevels & LOGCURL) == 0)
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();
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;
89 while (it != vecLines.end())
91 CLog::Log(LOGDEBUG, "Curl::Debug - %s%s", infotype, (*it).c_str());
97 /* curl calls this routine to get more data */
98 extern "C" size_t write_callback(char *buffer,
103 if(userp == NULL) return 0;
105 CCurlFile::CReadState *state = (CCurlFile::CReadState *)userp;
106 return state->WriteCallback(buffer, size, nitems);
109 extern "C" size_t read_callback(char *buffer,
114 if(userp == NULL) return 0;
116 CCurlFile::CReadState *state = (CCurlFile::CReadState *)userp;
117 return state->ReadCallback(buffer, size, nitems);
120 extern "C" size_t header_callback(void *ptr, size_t size, size_t nmemb, void *stream)
122 CCurlFile::CReadState *state = (CCurlFile::CReadState *)stream;
123 return state->HeaderCallback(ptr, size, nmemb);
126 /* fix for silly behavior of realloc */
127 static inline void* realloc_simple(void *ptr, size_t size)
129 void *ptr2 = realloc(ptr, size);
130 if(ptr && !ptr2 && size > 0)
139 size_t CCurlFile::CReadState::HeaderCallback(void *ptr, size_t size, size_t nmemb)
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
148 inString.append(strBuf, iSize);
150 m_httpheader.Parse(inString);
155 size_t CCurlFile::CReadState::ReadCallback(char *buffer, size_t size, size_t nitems)
160 if (m_filePos >= m_fileSize)
163 return CURL_READFUNC_PAUSE;
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;
173 size_t CCurlFile::CReadState::WriteCallback(char *buffer, size_t size, size_t nitems)
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);
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);
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);
189 m_overflowSize -= maxWriteable;
192 // ok, now copy the data into our ring buffer
193 unsigned int maxWriteable = XMIN((unsigned int)m_buffer.getMaxWriteSize(), amount);
196 if (!m_buffer.WriteData(buffer, maxWriteable))
198 CLog::Log(LOGERROR, "CCurlFile::WriteCallback - Unable to write to buffer with %i bytes - what's up?", maxWriteable);
202 amount -= maxWriteable;
203 buffer += maxWriteable;
208 // CLog::Log(LOGDEBUG, "CCurlFile::WriteCallback(%p) not enough free space for %i bytes", (void*)this, amount);
210 m_overflowBuffer = (char*)realloc_simple(m_overflowBuffer, amount + m_overflowSize);
211 if(m_overflowBuffer == NULL)
213 CLog::Log(LOGWARNING, "CCurlFile::WriteCallback - Failed to grow overflow buffer from %i bytes to %i bytes", m_overflowSize, amount + m_overflowSize);
216 memcpy(m_overflowBuffer + m_overflowSize, buffer, amount);
217 m_overflowSize += amount;
219 return size * nitems;
222 CCurlFile::CReadState::CReadState()
225 m_multiHandle = NULL;
226 m_overflowBuffer = NULL;
236 m_curlHeaderList = NULL;
237 m_curlAliasList = NULL;
240 CCurlFile::CReadState::~CReadState()
245 g_curlInterface.easy_release(&m_easyHandle, &m_multiHandle);
248 bool CCurlFile::CReadState::Seek(int64_t pos)
253 if(FITS_INT(pos - m_filePos) && m_buffer.SkipBytes((int)(pos - m_filePos)))
259 if(pos > m_filePos && pos < m_filePos + m_bufferSize)
261 int len = m_buffer.getMaxReadSize();
263 m_buffer.SkipBytes(len);
264 if(!FillBuffer(m_bufferSize))
266 if(!m_buffer.SkipBytes(-len))
267 CLog::Log(LOGERROR, "%s - Failed to restore position after failed fill", __FUNCTION__);
273 if(!FITS_INT(pos - m_filePos) || !m_buffer.SkipBytes((int)(pos - m_filePos)))
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__);
288 void CCurlFile::CReadState::SetResume(void)
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.
295 if (m_sendRange && m_filePos == 0)
296 g_curlInterface.easy_setopt(m_easyHandle, CURLOPT_RANGE, "0-");
299 g_curlInterface.easy_setopt(m_easyHandle, CURLOPT_RANGE, NULL);
303 g_curlInterface.easy_setopt(m_easyHandle, CURLOPT_RESUME_FROM_LARGE, m_filePos);
306 long CCurlFile::CReadState::Connect(unsigned int size)
309 CLog::Log(LOGDEBUG,"CurlFile::CReadState::Connect - Resume from position %"PRId64, m_filePos);
312 g_curlInterface.multi_add_handle(m_multiHandle, m_easyHandle);
316 m_buffer.Create(size * 3);
317 m_httpheader.Clear();
319 // read some data in to try and obtain the length
320 // maybe there's a better way to get this info??
324 CLog::Log(LOGERROR, "CCurlFile::CReadState::Connect, didn't get any data from stream.");
329 if (CURLE_OK == g_curlInterface.easy_getinfo(m_easyHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &length))
333 m_fileSize = m_filePos + (int64_t)length;
337 if (CURLE_OK == g_curlInterface.easy_getinfo(m_easyHandle, CURLINFO_RESPONSE_CODE, &response))
343 void CCurlFile::CReadState::Disconnect()
345 if(m_multiHandle && m_easyHandle)
346 g_curlInterface.multi_remove_handle(m_multiHandle, m_easyHandle);
349 free(m_overflowBuffer);
350 m_overflowBuffer = NULL;
358 if( m_curlHeaderList )
359 g_curlInterface.slist_free_all(m_curlHeaderList);
360 m_curlHeaderList = NULL;
362 if( m_curlAliasList )
363 g_curlInterface.slist_free_all(m_curlAliasList);
364 m_curlAliasList = NULL;
368 CCurlFile::~CCurlFile()
373 g_curlInterface.Unload();
376 CCurlFile::CCurlFile()
378 g_curlInterface.Load(); // loads the curl dll and resolves exports etc.
382 m_multisession = true;
384 m_useOldHttpVersion = false;
385 m_connecttimeout = 0;
390 m_bufferSize = 32768;
393 m_postdataset = false;
398 m_proxytype = PROXY_HTTP;
399 m_state = new CReadState();
403 m_acceptCharset = "UTF-8,*;q=0.8"; /* prefer UTF-8 if available */
406 //Has to be called before Open()
407 void CCurlFile::SetBufferSize(unsigned int size)
412 void CCurlFile::Close()
414 if (m_opened && m_forWrite && !m_inError)
417 m_state->Disconnect();
430 void CCurlFile::SetCommonOptions(CReadState* state)
432 CURL_HANDLE* h = state->m_easyHandle;
434 g_curlInterface.easy_reset(h);
436 g_curlInterface.easy_setopt(h, CURLOPT_DEBUGFUNCTION, debug_callback);
438 if( g_advancedSettings.m_logLevel >= LOG_LEVEL_DEBUG )
439 g_curlInterface.easy_setopt(h, CURLOPT_VERBOSE, TRUE);
441 g_curlInterface.easy_setopt(h, CURLOPT_VERBOSE, FALSE);
443 g_curlInterface.easy_setopt(h, CURLOPT_WRITEDATA, state);
444 g_curlInterface.easy_setopt(h, CURLOPT_WRITEFUNCTION, write_callback);
446 g_curlInterface.easy_setopt(h, CURLOPT_READDATA, state);
447 g_curlInterface.easy_setopt(h, CURLOPT_READFUNCTION, read_callback);
449 // set username and password for current handle
450 if (m_username.length() > 0 && m_password.length() > 0)
452 CStdString userpwd = m_username + ":" + m_password;
453 g_curlInterface.easy_setopt(h, CURLOPT_USERPWD, userpwd.c_str());
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);
461 g_curlInterface.easy_setopt(h, CURLOPT_FTP_USE_EPSV, 0); // turn off epsv
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);
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");
472 g_curlInterface.easy_setopt(h, CURLOPT_COOKIEFILE, strCookieFile.c_str());
473 g_curlInterface.easy_setopt(h, CURLOPT_COOKIEJAR, strCookieFile.c_str());
475 // Set custom cookie if requested
476 if (!m_cookie.empty())
477 g_curlInterface.easy_setopt(h, CURLOPT_COOKIE, m_cookie.c_str());
479 g_curlInterface.easy_setopt(h, CURLOPT_COOKIELIST, "FLUSH");
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);
488 // not interested in failed requests
489 g_curlInterface.easy_setopt(h, CURLOPT_FAILONERROR, 1);
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);
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);
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);
505 // setup POST data if it is set (and it may be empty)
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());
513 // setup Referer header if needed
514 if (!m_referer.empty())
515 g_curlInterface.easy_setopt(h, CURLOPT_REFERER, m_referer.c_str());
518 g_curlInterface.easy_setopt(h, CURLOPT_REFERER, NULL);
519 g_curlInterface.easy_setopt(h, CURLOPT_AUTOREFERER, TRUE);
522 // setup any requested authentication
523 if( m_ftpauth.length() > 0 )
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);
534 // setup requested http authentication method
535 if(m_httpauth.length() > 0)
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);
547 // allow passive mode for ftp
548 if( m_ftpport.length() > 0 )
549 g_curlInterface.easy_setopt(h, CURLOPT_FTPPORT, m_ftpport.c_str());
551 g_curlInterface.easy_setopt(h, CURLOPT_FTPPORT, NULL);
553 // allow curl to not use the ip address in the returned pasv response
555 g_curlInterface.easy_setopt(h, CURLOPT_FTP_SKIP_PASV_IP, 0);
557 g_curlInterface.easy_setopt(h, CURLOPT_FTP_SKIP_PASV_IP, 1);
559 // setup Content-Encoding if requested
560 if( m_contentencoding.length() > 0 )
561 g_curlInterface.easy_setopt(h, CURLOPT_ENCODING, m_contentencoding.c_str());
563 if (!m_useOldHttpVersion && !m_acceptCharset.empty())
564 SetRequestHeader("Accept-Charset", m_acceptCharset);
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());
571 if (m_useOldHttpVersion)
572 g_curlInterface.easy_setopt(h, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
574 if (g_advancedSettings.m_curlDisableIPV6)
575 g_curlInterface.easy_setopt(h, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
577 if (m_proxy.length() > 0)
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());
585 if (m_customrequest.length() > 0)
586 g_curlInterface.easy_setopt(h, CURLOPT_CUSTOMREQUEST, m_customrequest.c_str());
588 if (m_connecttimeout == 0)
589 m_connecttimeout = g_advancedSettings.m_curlconnecttimeout;
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);
594 // We abort in case we transfer less than 1byte/second
595 g_curlInterface.easy_setopt(h, CURLOPT_LOW_SPEED_LIMIT, 1);
597 if (m_lowspeedtime == 0)
598 m_lowspeedtime = g_advancedSettings.m_curllowspeedtime;
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);
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);
610 // Setup allowed TLS/SSL ciphers. New versions of cURL may deprecate things that are still in use.
611 if (!m_cipherlist.empty())
612 g_curlInterface.easy_setopt(h, CURLOPT_SSL_CIPHER_LIST, m_cipherlist.c_str());
615 void CCurlFile::SetRequestHeaders(CReadState* state)
617 if(state->m_curlHeaderList)
619 g_curlInterface.slist_free_all(state->m_curlHeaderList);
620 state->m_curlHeaderList = NULL;
623 MAPHTTPHEADERS::iterator it;
624 for(it = m_requestheaders.begin(); it != m_requestheaders.end(); it++)
626 CStdString buffer = it->first + ": " + it->second;
627 state->m_curlHeaderList = g_curlInterface.slist_append(state->m_curlHeaderList, buffer.c_str());
630 // add user defined headers
631 if (state->m_easyHandle)
632 g_curlInterface.easy_setopt(state->m_easyHandle, CURLOPT_HTTPHEADER, state->m_curlHeaderList);
635 void CCurlFile::SetCorrectHeaders(CReadState* state)
637 CHttpHeader& h = state->m_httpheader;
638 /* workaround for shoutcast server wich doesn't set content type on standard mp3 */
639 if( h.GetMimeType().empty() )
641 if( !h.GetValue("icy-notice1").empty()
642 || !h.GetValue("icy-name").empty()
643 || !h.GetValue("icy-br").empty() )
644 h.AddParam("Content-Type", "audio/mpeg");
647 /* hack for google video */
648 if (StringUtils::EqualsNoCase(h.GetMimeType(),"text/html")
649 && !h.GetValue("Content-Disposition").empty() )
651 CStdString strValue = h.GetValue("Content-Disposition");
652 if (strValue.find("filename=") != std::string::npos &&
653 strValue.find(".flv") != std::string::npos)
654 h.AddParam("Content-Type", "video/flv");
658 void CCurlFile::ParseAndCorrectUrl(CURL &url2)
660 CStdString strProtocol = url2.GetTranslatedProtocol();
661 url2.SetProtocol(strProtocol);
663 if( strProtocol.Equals("ftp")
664 || strProtocol.Equals("ftps") )
666 // we was using url optons for urls, keep the old code work and warning
667 if (!url2.GetOptions().empty())
669 CLog::Log(LOGWARNING, "%s: ftp url option is deprecated, please switch to use protocol option (change '?' to '|'), url: [%s]", __FUNCTION__, url2.GetRedacted().c_str());
670 url2.SetProtocolOptions(url2.GetOptions().substr(1));
671 /* ftp has no options */
675 /* this is uggly, depending on from where */
676 /* we get the link it may or may not be */
677 /* url encoded. if handed from ftpdirectory */
678 /* it won't be so let's handle that case */
680 CStdString filename(url2.GetFileName());
681 std::vector<std::string> array;
683 // if server sent us the filename in non-utf8, we need send back with same encoding.
684 if (url2.GetProtocolOption("utf8") == "0")
685 g_charsetConverter.utf8ToStringCharset(filename);
687 /* TODO: create a tokenizer that doesn't skip empty's */
688 StringUtils::Tokenize(filename, array, "/");
690 for(std::vector<std::string>::iterator it = array.begin(); it != array.end(); it++)
692 if(it != array.begin())
695 filename += CURL::Encode(*it);
698 /* make sure we keep slashes */
699 if(StringUtils::EndsWith(url2.GetFileName(), "/"))
702 url2.SetFileName(filename);
705 if (url2.HasProtocolOption("auth"))
707 m_ftpauth = url2.GetProtocolOption("auth");
708 if(m_ftpauth.empty())
712 if (url2.HasProtocolOption("active"))
714 m_ftpport = url2.GetProtocolOption("active");
715 if(m_ftpport.empty())
718 m_ftppasvip = url2.HasProtocolOption("pasvip") && url2.GetProtocolOption("pasvip") != "0";
720 else if( strProtocol.Equals("http")
721 || strProtocol.Equals("https"))
723 if (CSettings::Get().GetBool("network.usehttpproxy")
724 && !CSettings::Get().GetString("network.httpproxyserver").empty()
725 && CSettings::Get().GetInt("network.httpproxyport") > 0
728 m_proxy = CSettings::Get().GetString("network.httpproxyserver");
729 m_proxy += StringUtils::Format(":%d", CSettings::Get().GetInt("network.httpproxyport"));
730 if (CSettings::Get().GetString("network.httpproxyusername").length() > 0 && m_proxyuserpass.empty())
732 m_proxyuserpass = CSettings::Get().GetString("network.httpproxyusername");
733 m_proxyuserpass += ":" + CSettings::Get().GetString("network.httpproxypassword");
735 m_proxytype = (ProxyType)CSettings::Get().GetInt("network.httpproxytype");
736 CLog::Log(LOGDEBUG, "Using proxy %s, type %d", m_proxy.c_str(), proxyType2CUrlProxyType[m_proxytype]);
739 // get username and password
740 m_username = url2.GetUserName();
741 m_password = url2.GetPassWord();
743 // handle any protocol options
744 std::map<CStdString, CStdString> options;
745 url2.GetProtocolOptions(options);
746 if (options.size() > 0)
748 // clear protocol options
749 url2.SetProtocolOptions("");
751 for(std::map<CStdString, CStdString>::const_iterator it = options.begin(); it != options.end(); ++it)
753 const CStdString &name = it->first;
754 const CStdString &value = it->second;
756 if(name.Equals("auth"))
759 if(m_httpauth.empty())
762 else if (name.Equals("Referer"))
764 else if (name.Equals("User-Agent"))
766 else if (name.Equals("Cookie"))
768 else if (name.Equals("Encoding"))
769 SetContentEncoding(value);
770 else if (name.Equals("noshout") && value.Equals("true"))
772 else if (name.Equals("seekable") && value.Equals("0"))
774 else if (name.Equals("Accept-Charset"))
775 SetAcceptCharset(value);
776 else if (name.Equals("HttpProxy"))
777 SetStreamProxy(value, PROXY_HTTP);
778 else if (name.Equals("SSLCipherList"))
779 m_cipherlist = value;
781 SetRequestHeader(name, value);
786 if (m_username.length() > 0 && m_password.length() > 0)
787 m_url = url2.GetWithoutUserDetails();
792 void CCurlFile::SetStreamProxy(const CStdString &proxy, ProxyType type)
795 m_proxy = url.GetWithoutUserDetails();
796 m_proxyuserpass = url.GetUserName();
797 if (!url.GetPassWord().empty())
798 m_proxyuserpass += ":" + url.GetPassWord();
800 CLog::Log(LOGDEBUG, "Overriding proxy from URL parameter: %s, type %d", m_proxy.c_str(), proxyType2CUrlProxyType[m_proxytype]);
803 bool CCurlFile::Post(const CStdString& strURL, const CStdString& strPostData, CStdString& strHTML)
805 m_postdata = strPostData;
806 m_postdataset = true;
807 return Service(strURL, strHTML);
810 bool CCurlFile::Get(const CStdString& strURL, CStdString& strHTML)
813 m_postdataset = false;
814 return Service(strURL, strHTML);
817 bool CCurlFile::Service(const CStdString& strURL, CStdString& strHTML)
821 if (ReadData(strHTML))
831 bool CCurlFile::ReadData(CStdString& strHTML)
837 while( (size_read = Read(buffer, sizeof(buffer)-1) ) > 0 )
839 buffer[size_read] = 0;
840 strHTML.append(buffer, size_read);
841 data_size += size_read;
843 if (m_state->m_cancelled)
848 bool CCurlFile::Download(const CStdString& strURL, const CStdString& strFileName, LPDWORD pdwSize)
850 CLog::Log(LOGINFO, "CCurlFile::Download - %s->%s", strURL.c_str(), strFileName.c_str());
853 if (!Get(strURL, strData))
857 if (!file.OpenForWrite(strFileName, true))
859 CLog::Log(LOGERROR, "CCurlFile::Download - Unable to open file %s: %u",
860 strFileName.c_str(), GetLastError());
864 file.Write(strData.c_str(), strData.size());
869 *pdwSize = strData.size();
875 // Detect whether we are "online" or not! Very simple and dirty!
876 bool CCurlFile::IsInternet()
878 CStdString strURL = "http://www.google.com";
879 bool found = Exists(strURL);
885 void CCurlFile::Cancel()
887 m_state->m_cancelled = true;
892 void CCurlFile::Reset()
894 m_state->m_cancelled = false;
897 bool CCurlFile::Open(const CURL& url)
903 ParseAndCorrectUrl(url2);
905 std::string redactPath = CURL::GetRedacted(m_url);
906 CLog::Log(LOGDEBUG, "CurlFile::Open(%p) %s", (void*)this, redactPath.c_str());
908 ASSERT(!(!m_state->m_easyHandle ^ !m_state->m_multiHandle));
909 if( m_state->m_easyHandle == NULL )
910 g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, &m_state->m_multiHandle );
912 // setup common curl options
913 SetCommonOptions(m_state);
914 SetRequestHeaders(m_state);
915 m_state->m_sendRange = m_seekable;
917 m_httpresponse = m_state->Connect(m_bufferSize);
918 if( m_httpresponse < 0 || m_httpresponse >= 400)
921 SetCorrectHeaders(m_state);
923 // since we can't know the stream size up front if we're gzipped/deflated
924 // flag the stream with an unknown file size rather than the compressed
926 if (m_contentencoding.size() > 0)
927 m_state->m_fileSize = 0;
929 // check if this stream is a shoutcast stream. sometimes checking the protocol line is not enough so examine other headers as well.
930 // shoutcast streams should be handled by FileShoutcast.
931 if ((m_state->m_httpheader.GetProtoLine().substr(0, 3) == "ICY" || !m_state->m_httpheader.GetValue("icy-notice1").empty()
932 || !m_state->m_httpheader.GetValue("icy-name").empty()
933 || !m_state->m_httpheader.GetValue("icy-br").empty()) && !m_skipshout)
935 CLog::Log(LOGDEBUG,"CCurlFile::Open - File <%s> is a shoutcast stream. Re-opening", redactPath.c_str());
936 throw new CRedirectException(new CShoutcastFile);
939 m_multisession = false;
940 if(url2.GetProtocol().Equals("http") || url2.GetProtocol().Equals("https"))
942 m_multisession = true;
943 if(m_state->m_httpheader.GetValue("Server").find("Portable SDK for UPnP devices") != std::string::npos)
945 CLog::Log(LOGWARNING, "CCurlFile::Open - Disabling multi session due to broken libupnp server");
946 m_multisession = false;
950 if(StringUtils::EqualsNoCase(m_state->m_httpheader.GetValue("Transfer-Encoding"), "chunked"))
951 m_state->m_fileSize = 0;
953 if(m_state->m_fileSize <= 0)
957 if(url2.GetProtocol().Equals("http")
958 || url2.GetProtocol().Equals("https"))
960 // if server says explicitly it can't seek, respect that
961 if(StringUtils::EqualsNoCase(m_state->m_httpheader.GetValue("Accept-Ranges"),"none"))
967 if (CURLE_OK == g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_EFFECTIVE_URL,&efurl) && efurl)
973 bool CCurlFile::OpenForWrite(const CURL& url, bool bOverWrite)
978 if (Exists(url) && !bOverWrite)
982 ParseAndCorrectUrl(url2);
984 CLog::Log(LOGDEBUG, "CCurlFile::OpenForWrite(%p) %s", (void*)this, CURL::GetRedacted(m_url).c_str());
986 ASSERT(m_state->m_easyHandle == NULL);
987 g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, &m_state->m_multiHandle);
989 // setup common curl options
990 SetCommonOptions(m_state);
991 SetRequestHeaders(m_state);
994 if (CURLE_OK == g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_EFFECTIVE_URL,&efurl) && efurl)
1002 ASSERT(m_state->m_multiHandle);
1004 SetCommonOptions(m_state);
1005 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_UPLOAD, 1);
1007 g_curlInterface.multi_add_handle(m_state->m_multiHandle, m_state->m_easyHandle);
1009 m_state->SetReadBuffer(NULL, 0);
1014 int CCurlFile::Write(const void* lpBuf, int64_t uiBufSize)
1016 if (!(m_opened && m_forWrite) || m_inError)
1019 ASSERT(m_state->m_multiHandle);
1021 m_state->SetReadBuffer(lpBuf, uiBufSize);
1022 m_state->m_isPaused = false;
1023 g_curlInterface.easy_pause(m_state->m_easyHandle, CURLPAUSE_CONT);
1025 CURLMcode result = CURLM_OK;
1028 while (m_stillRunning && !m_state->m_isPaused)
1030 while ((result = g_curlInterface.multi_perform(m_state->m_multiHandle, &m_stillRunning)) == CURLM_CALL_MULTI_PERFORM);
1032 if (!m_stillRunning)
1035 if (result != CURLM_OK)
1038 if(g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_RESPONSE_CODE, &code) == CURLE_OK )
1039 CLog::Log(LOGERROR, "%s - Unable to write curl resource (%s) - %ld", __FUNCTION__, CURL::GetRedacted(m_url).c_str(), code);
1045 m_writeOffset += m_state->m_filePos;
1046 return m_state->m_filePos;
1049 bool CCurlFile::CReadState::ReadString(char *szLine, int iLineLength)
1051 unsigned int want = (unsigned int)iLineLength;
1053 if((m_fileSize == 0 || m_filePos < m_fileSize) && !FillBuffer(want))
1056 // ensure only available data is considered
1057 want = XMIN((unsigned int)m_buffer.getMaxReadSize(), want);
1059 /* check if we finished prematurely */
1060 if (!m_stillRunning && (m_fileSize == 0 || m_filePos != m_fileSize) && !want)
1062 if (m_fileSize != 0)
1063 CLog::Log(LOGWARNING, "%s - Transfer ended before entire file was retrieved pos %"PRId64", size %"PRId64, __FUNCTION__, m_filePos, m_fileSize);
1068 char* pLine = szLine;
1071 if (!m_buffer.ReadData(pLine, 1))
1075 } while (((pLine - 1)[0] != '\n') && ((unsigned int)(pLine - szLine) < want));
1077 m_filePos += (pLine - szLine);
1078 return (bool)((pLine - szLine) > 0);
1081 bool CCurlFile::Exists(const CURL& url)
1083 // if file is already running, get info from it
1086 CLog::Log(LOGWARNING, "CCurlFile::Exists - Exist called on open file %s", url.GetRedacted().c_str());
1091 ParseAndCorrectUrl(url2);
1093 ASSERT(m_state->m_easyHandle == NULL);
1094 g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, NULL);
1096 SetCommonOptions(m_state);
1097 SetRequestHeaders(m_state);
1098 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TIMEOUT, 5);
1099 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_NOBODY, 1);
1100 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_WRITEDATA, NULL); /* will cause write failure*/
1102 if(url2.GetProtocol() == "ftp")
1104 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FILETIME, 1);
1105 // nocwd is less standard, will return empty list for non-existed remote dir on some ftp server, avoid it.
1106 if (StringUtils::EndsWith(url2.GetFileName(), "/"))
1107 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_SINGLECWD);
1109 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_NOCWD);
1112 CURLcode result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1113 g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1115 if (result == CURLE_WRITE_ERROR || result == CURLE_OK)
1118 if (result == CURLE_HTTP_RETURNED_ERROR)
1121 if(g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_RESPONSE_CODE, &code) == CURLE_OK && code != 404 )
1122 CLog::Log(LOGERROR, "CCurlFile::Exists - Failed: HTTP returned error %ld for %s", code, url.GetRedacted().c_str());
1124 else if (result != CURLE_REMOTE_FILE_NOT_FOUND && result != CURLE_FTP_COULDNT_RETR_FILE)
1126 CLog::Log(LOGERROR, "CCurlFile::Exists - Failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.GetRedacted().c_str());
1133 int64_t CCurlFile::Seek(int64_t iFilePosition, int iWhence)
1135 int64_t nextPos = m_state->m_filePos;
1143 nextPos = iFilePosition;
1146 nextPos += iFilePosition;
1149 if (m_state->m_fileSize)
1150 nextPos = m_state->m_fileSize + iFilePosition;
1158 // We can't seek beyond EOF
1159 if (m_state->m_fileSize && nextPos > m_state->m_fileSize) return -1;
1161 if(m_state->Seek(nextPos))
1169 m_oldState = m_state;
1170 m_state = new CReadState();
1171 m_state->m_fileSize = m_oldState->m_fileSize;
1172 g_curlInterface.easy_aquire(url.GetProtocol(),
1174 &m_state->m_easyHandle,
1175 &m_state->m_multiHandle );
1181 m_state = m_oldState;
1184 if (m_state->Seek(nextPos))
1187 m_state->Disconnect();
1191 m_state->Disconnect();
1193 // re-setup common curl options
1194 SetCommonOptions(m_state);
1196 /* caller might have changed some headers (needed for daap)*/
1197 SetRequestHeaders(m_state);
1199 m_state->m_filePos = nextPos;
1200 m_state->m_sendRange = true;
1202 long response = m_state->Connect(m_bufferSize);
1203 if(response < 0 && (m_state->m_fileSize == 0 || m_state->m_fileSize != m_state->m_filePos))
1210 m_state = m_oldState;
1213 // Retry without mutlisession
1214 m_multisession = false;
1215 return Seek(iFilePosition, iWhence);
1224 SetCorrectHeaders(m_state);
1226 return m_state->m_filePos;
1229 int64_t CCurlFile::GetLength()
1231 if (!m_opened) return 0;
1232 return m_state->m_fileSize;
1235 int64_t CCurlFile::GetPosition()
1237 if (!m_opened) return 0;
1238 return m_state->m_filePos;
1241 int CCurlFile::Stat(const CURL& url, struct __stat64* buffer)
1243 // if file is already running, get info from it
1246 CLog::Log(LOGWARNING, "CCurlFile::Stat - Stat called on open file %s", url.GetRedacted().c_str());
1249 memset(buffer, 0, sizeof(struct __stat64));
1250 buffer->st_size = GetLength();
1251 buffer->st_mode = _S_IFREG;
1257 ParseAndCorrectUrl(url2);
1259 ASSERT(m_state->m_easyHandle == NULL);
1260 g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, NULL);
1262 SetCommonOptions(m_state);
1263 SetRequestHeaders(m_state);
1264 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TIMEOUT, g_advancedSettings.m_curlconnecttimeout);
1265 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_NOBODY, 1);
1266 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_WRITEDATA, NULL); /* will cause write failure*/
1267 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FILETIME , 1);
1269 if(url2.GetProtocol() == "ftp")
1271 // nocwd is less standard, will return empty list for non-existed remote dir on some ftp server, avoid it.
1272 if (StringUtils::EndsWith(url2.GetFileName(), "/"))
1273 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_SINGLECWD);
1275 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_NOCWD);
1278 CURLcode result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1280 if(result == CURLE_HTTP_RETURNED_ERROR)
1283 if(g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_RESPONSE_CODE, &code) == CURLE_OK && code == 404 )
1287 if(result == CURLE_GOT_NOTHING
1288 || result == CURLE_HTTP_RETURNED_ERROR
1289 || result == CURLE_RECV_ERROR /* some silly shoutcast servers */ )
1291 /* some http servers and shoutcast servers don't give us any data on a head request */
1292 /* request normal and just fail out, it's their loss */
1293 /* somehow curl doesn't reset CURLOPT_NOBODY properly so reset everything */
1294 SetCommonOptions(m_state);
1295 SetRequestHeaders(m_state);
1296 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TIMEOUT, g_advancedSettings.m_curlconnecttimeout);
1297 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_RANGE, "0-0");
1298 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_WRITEDATA, NULL); /* will cause write failure*/
1299 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FILETIME, 1);
1300 result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1303 if( result == CURLE_HTTP_RANGE_ERROR )
1305 /* crap can't use the range option, disable it and try again */
1306 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_RANGE, NULL);
1307 result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1310 if( result != CURLE_WRITE_ERROR && result != CURLE_OK )
1312 g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1314 CLog::Log(LOGERROR, "CCurlFile::Stat - Failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.GetRedacted().c_str());
1319 result = g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &length);
1320 if (result != CURLE_OK || length < 0.0)
1322 if (url.GetProtocol() == "ftp")
1324 g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1325 CLog::Log(LOGNOTICE, "CCurlFile::Stat - Content length failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.GetRedacted().c_str());
1333 SetCorrectHeaders(m_state);
1338 result = g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_CONTENT_TYPE, &content);
1339 if (result != CURLE_OK)
1341 CLog::Log(LOGNOTICE, "CCurlFile::Stat - Content type failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.GetRedacted().c_str());
1342 g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1348 memset(buffer, 0, sizeof(struct __stat64));
1349 buffer->st_size = (int64_t)length;
1350 if(content && strstr(content, "text/html")) //consider html files directories
1351 buffer->st_mode = _S_IFDIR;
1353 buffer->st_mode = _S_IFREG;
1356 result = g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_FILETIME, &filetime);
1357 if (result != CURLE_OK)
1359 CLog::Log(LOGNOTICE, "CCurlFile::Stat - Filetime failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.GetRedacted().c_str());
1364 buffer->st_mtime = filetime;
1367 g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1371 unsigned int CCurlFile::CReadState::Read(void* lpBuf, int64_t uiBufSize)
1373 /* only request 1 byte, for truncated reads (only if not eof) */
1374 if((m_fileSize == 0 || m_filePos < m_fileSize) && !FillBuffer(1))
1377 /* ensure only available data is considered */
1378 unsigned int want = (unsigned int)XMIN(m_buffer.getMaxReadSize(), uiBufSize);
1380 /* xfer data to caller */
1381 if (m_buffer.ReadData((char *)lpBuf, want))
1387 /* check if we finished prematurely */
1388 if (!m_stillRunning && (m_fileSize == 0 || m_filePos != m_fileSize))
1390 CLog::Log(LOGWARNING, "%s - Transfer ended before entire file was retrieved pos %"PRId64", size %"PRId64, __FUNCTION__, m_filePos, m_fileSize);
1397 /* use to attempt to fill the read buffer up to requested number of bytes */
1398 bool CCurlFile::CReadState::FillBuffer(unsigned int want)
1405 // only attempt to fill buffer if transactions still running and buffer
1406 // doesnt exceed required size already
1407 while ((unsigned int)m_buffer.getMaxReadSize() < want && m_buffer.getMaxWriteSize() > 0 )
1412 /* if there is data in overflow buffer, try to use that first */
1415 unsigned amount = XMIN((unsigned int)m_buffer.getMaxWriteSize(), m_overflowSize);
1416 m_buffer.WriteData(m_overflowBuffer, amount);
1418 if (amount < m_overflowSize)
1419 memcpy(m_overflowBuffer, m_overflowBuffer+amount,m_overflowSize-amount);
1421 m_overflowSize -= amount;
1422 m_overflowBuffer = (char*)realloc_simple(m_overflowBuffer, m_overflowSize);
1426 CURLMcode result = g_curlInterface.multi_perform(m_multiHandle, &m_stillRunning);
1427 if (!m_stillRunning)
1429 if (result == CURLM_OK)
1431 /* if we still have stuff in buffer, we are fine */
1432 if (m_buffer.getMaxReadSize())
1435 /* verify that we are actually okey */
1437 CURLcode CURLresult = CURLE_OK;
1439 while ((msg = g_curlInterface.multi_info_read(m_multiHandle, &msgs)))
1441 if (msg->msg == CURLMSG_DONE)
1443 if (msg->data.result == CURLE_OK)
1446 CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Failed: %s(%d)", g_curlInterface.easy_strerror(msg->data.result), msg->data.result);
1448 // We need to check the result here as we don't want to retry on every error
1449 if ( (msg->data.result == CURLE_OPERATION_TIMEDOUT ||
1450 msg->data.result == CURLE_PARTIAL_FILE ||
1451 msg->data.result == CURLE_COULDNT_CONNECT ||
1452 msg->data.result == CURLE_RECV_ERROR) &&
1454 CURLresult = msg->data.result;
1455 else if ( (msg->data.result == CURLE_HTTP_RANGE_ERROR ||
1456 msg->data.result == CURLE_HTTP_RETURNED_ERROR) &&
1461 // If server returns a range or http error, retry with range disabled
1462 CURLresult = msg->data.result;
1463 m_sendRange = false;
1470 // Don't retry when we didn't "see" any error
1471 if (CURLresult == CURLE_OK)
1475 if (m_multiHandle && m_easyHandle)
1476 g_curlInterface.multi_remove_handle(m_multiHandle, m_easyHandle);
1478 // Reset all the stuff like we would in Disconnect()
1480 free(m_overflowBuffer);
1481 m_overflowBuffer = NULL;
1484 // If we got here something is wrong
1485 if (++retry > g_advancedSettings.m_curlretries)
1487 CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Reconnect failed!");
1488 // Reset the rest of the variables like we would in Disconnect()
1496 CLog::Log(LOGNOTICE, "CCurlFile::FillBuffer - Reconnect, (re)try %i", retry);
1498 // Connect + seek to current position (again)
1500 g_curlInterface.multi_add_handle(m_multiHandle, m_easyHandle);
1502 // Return to the beginning of the loop:
1508 // We've finished out first loop
1509 if(m_bFirstLoop && m_buffer.getMaxReadSize() > 0)
1510 m_bFirstLoop = false;
1521 // get file descriptors from the transfers
1522 g_curlInterface.multi_fdset(m_multiHandle, &fdread, &fdwrite, &fdexcep, &maxfd);
1525 if (CURLM_OK != g_curlInterface.multi_timeout(m_multiHandle, &timeout) || timeout == -1)
1528 XbmcThreads::EndTime endTime(timeout);
1533 unsigned int time_left = endTime.MillisLeft();
1534 struct timeval t = { time_left / 1000, (time_left % 1000) * 1000 };
1536 // Wait until data is available or a timeout occurs.
1537 rc = select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &t);
1538 #ifdef TARGET_WINDOWS
1539 } while(rc == SOCKET_ERROR && WSAGetLastError() == WSAEINTR);
1541 } while(rc == SOCKET_ERROR && errno == EINTR);
1544 if(rc == SOCKET_ERROR)
1546 #ifdef TARGET_WINDOWS
1548 strerror_s(buf, 256, WSAGetLastError());
1549 CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Failed with socket error:%s", buf);
1551 char const * str = strerror(errno);
1552 CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Failed with socket error:%s", str);
1559 case CURLM_CALL_MULTI_PERFORM:
1561 // we don't keep calling here as that can easily overwrite our buffer which we want to avoid
1562 // docs says we should call it soon after, but aslong as we are reading data somewhere
1563 // this aught to be soon enough. should stay in socket otherwise
1569 CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Multi perform failed with code %d, aborting", result);
1578 void CCurlFile::CReadState::SetReadBuffer(const void* lpBuf, int64_t uiBufSize)
1580 m_readBuffer = (char*)lpBuf;
1581 m_fileSize = uiBufSize;
1585 void CCurlFile::ClearRequestHeaders()
1587 m_requestheaders.clear();
1590 void CCurlFile::SetRequestHeader(CStdString header, CStdString value)
1592 m_requestheaders[header] = value;
1595 void CCurlFile::SetRequestHeader(CStdString header, long value)
1597 m_requestheaders[header] = StringUtils::Format("%ld", value);
1600 std::string CCurlFile::GetServerReportedCharset(void)
1605 return m_state->m_httpheader.GetCharset();
1608 /* STATIC FUNCTIONS */
1609 bool CCurlFile::GetHttpHeader(const CURL &url, CHttpHeader &headers)
1614 if(file.Stat(url, NULL) == 0)
1616 headers = file.GetHttpHeader();
1623 CLog::Log(LOGERROR, "%s - Exception thrown while trying to retrieve header url: %s", __FUNCTION__, url.GetRedacted().c_str());
1628 bool CCurlFile::GetMimeType(const CURL &url, CStdString &content, CStdString useragent)
1631 if (!useragent.empty())
1632 file.SetUserAgent(useragent);
1634 struct __stat64 buffer;
1635 std::string redactUrl = url.GetRedacted();
1636 if( file.Stat(url, &buffer) == 0 )
1638 if (buffer.st_mode == _S_IFDIR)
1639 content = "x-directory/normal";
1641 content = file.GetMimeType();
1642 CLog::Log(LOGDEBUG, "CCurlFile::GetMimeType - %s -> %s", redactUrl.c_str(), content.c_str());
1645 CLog::Log(LOGDEBUG, "CCurlFile::GetMimeType - %s -> failed", redactUrl.c_str());
1650 bool CCurlFile::GetCookies(const CURL &url, std::string &cookies)
1652 std::string cookiesStr;
1653 struct curl_slist* curlCookies;
1654 XCURL::CURL_HANDLE* easyHandle;
1655 XCURL::CURLM* multiHandle;
1657 // get the cookies list
1658 g_curlInterface.easy_aquire(url.GetProtocol(), url.GetHostName(), &easyHandle, &multiHandle);
1659 if (CURLE_OK == g_curlInterface.easy_getinfo(easyHandle, CURLINFO_COOKIELIST, &curlCookies))
1661 // iterate over each cookie and format it into an RFC 2109 formatted Set-Cookie string
1662 struct curl_slist* curlCookieIter = curlCookies;
1663 while(curlCookieIter)
1665 // tokenize the CURL cookie string
1666 std::vector<std::string> valuesVec;
1667 StringUtils::Tokenize(curlCookieIter->data, valuesVec, "\t");
1669 // ensure the length is valid
1670 if (valuesVec.size() < 7)
1672 CLog::Log(LOGERROR, "CCurlFile::GetCookies - invalid cookie: '%s'", curlCookieIter->data);
1673 curlCookieIter = curlCookieIter->next;
1677 // create a http-header formatted cookie string
1678 std::string cookieStr = valuesVec[5] + "=" + valuesVec[6] +
1679 "; path=" + valuesVec[2] +
1680 "; domain=" + valuesVec[0];
1682 // append this cookie to the string containing all cookies
1683 if (!cookiesStr.empty())
1685 cookiesStr += cookieStr;
1687 // move on to the next cookie
1688 curlCookieIter = curlCookieIter->next;
1691 // free the curl cookies
1692 g_curlInterface.slist_free_all(curlCookies);
1694 // release our handles
1695 g_curlInterface.easy_release(&easyHandle, &multiHandle);
1697 // if we have a non-empty cookie string, return it
1698 if (!cookiesStr.empty())
1700 cookies = cookiesStr;
1705 // no cookies to return
1709 int CCurlFile::IoControl(EIoControl request, void* param)
1711 if(request == IOCTRL_SEEK_POSSIBLE)
1712 return m_seekable ? 1 : 0;