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"
35 #include "../linux/XFileUtils.h"
36 #include "../linux/XTimeUtils.h"
37 #include "../linux/ConvUtils.h"
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"
47 using namespace XFILE;
48 using namespace XCURL;
50 #define XMIN(a,b) ((a)<(b)?(a):(b))
51 #define FITS_INT(a) (((a) <= INT_MAX) && ((a) >= INT_MIN))
53 #define dllselect select
56 curl_proxytype proxyType2CUrlProxyType[] = {
61 CURLPROXY_SOCKS5_HOSTNAME,
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)
67 if (info == CURLINFO_DATA_IN || info == CURLINFO_DATA_OUT)
70 if ((g_advancedSettings.m_extraLogLevels & LOGCURL) == 0)
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();
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;
91 while (it != vecLines.end())
93 CLog::Log(LOGDEBUG, "Curl::Debug - %s%s", infotype, (*it).c_str());
99 /* curl calls this routine to get more data */
100 extern "C" size_t write_callback(char *buffer,
105 if(userp == NULL) return 0;
107 CCurlFile::CReadState *state = (CCurlFile::CReadState *)userp;
108 return state->WriteCallback(buffer, size, nitems);
111 extern "C" size_t read_callback(char *buffer,
116 if(userp == NULL) return 0;
118 CCurlFile::CReadState *state = (CCurlFile::CReadState *)userp;
119 return state->ReadCallback(buffer, size, nitems);
122 extern "C" size_t header_callback(void *ptr, size_t size, size_t nmemb, void *stream)
124 CCurlFile::CReadState *state = (CCurlFile::CReadState *)stream;
125 return state->HeaderCallback(ptr, size, nmemb);
128 /* fix for silly behavior of realloc */
129 static inline void* realloc_simple(void *ptr, size_t size)
131 void *ptr2 = realloc(ptr, size);
132 if(ptr && !ptr2 && size > 0)
141 size_t CCurlFile::CReadState::HeaderCallback(void *ptr, size_t size, size_t nmemb)
143 // clear any previous header
146 m_httpheader.Clear();
147 m_headerdone = false;
150 // libcurl doc says that this info is not always \0 terminated
151 char* strData = (char*)ptr;
152 int iSize = size * nmemb;
154 if (strData[iSize] != 0)
156 strData = (char*)malloc(iSize + 1);
157 strncpy(strData, (char*)ptr, iSize);
160 else strData = strdup((char*)ptr);
162 if(strcmp(strData, "\r\n") == 0)
165 m_httpheader.Parse(strData);
172 size_t CCurlFile::CReadState::ReadCallback(char *buffer, size_t size, size_t nitems)
177 if (m_filePos >= m_fileSize)
180 return CURL_READFUNC_PAUSE;
183 int64_t retSize = XMIN(m_fileSize - m_filePos, int64_t(nitems * size));
184 memcpy(buffer, m_readBuffer + m_filePos, retSize);
185 m_filePos += retSize;
190 size_t CCurlFile::CReadState::WriteCallback(char *buffer, size_t size, size_t nitems)
192 unsigned int amount = size * nitems;
193 // CLog::Log(LOGDEBUG, "CCurlFile::WriteCallback (%p) with %i bytes, readsize = %i, writesize = %i", this, amount, m_buffer.getMaxReadSize(), m_buffer.getMaxWriteSize() - m_overflowSize);
196 // we have our overflow buffer - first get rid of as much as we can
197 unsigned int maxWriteable = XMIN((unsigned int)m_buffer.getMaxWriteSize(), m_overflowSize);
200 if (!m_buffer.WriteData(m_overflowBuffer, maxWriteable))
201 CLog::Log(LOGERROR, "CCurlFile::WriteCallback - Unable to write to buffer - what's up?");
202 if (m_overflowSize > maxWriteable)
203 { // still have some more - copy it down
204 memmove(m_overflowBuffer, m_overflowBuffer + maxWriteable, m_overflowSize - maxWriteable);
206 m_overflowSize -= maxWriteable;
209 // ok, now copy the data into our ring buffer
210 unsigned int maxWriteable = XMIN((unsigned int)m_buffer.getMaxWriteSize(), amount);
213 if (!m_buffer.WriteData(buffer, maxWriteable))
215 CLog::Log(LOGERROR, "CCurlFile::WriteCallback - Unable to write to buffer with %i bytes - what's up?", maxWriteable);
219 amount -= maxWriteable;
220 buffer += maxWriteable;
225 // CLog::Log(LOGDEBUG, "CCurlFile::WriteCallback(%p) not enough free space for %i bytes", (void*)this, amount);
227 m_overflowBuffer = (char*)realloc_simple(m_overflowBuffer, amount + m_overflowSize);
228 if(m_overflowBuffer == NULL)
230 CLog::Log(LOGWARNING, "CCurlFile::WriteCallback - Failed to grow overflow buffer from %i bytes to %i bytes", m_overflowSize, amount + m_overflowSize);
233 memcpy(m_overflowBuffer + m_overflowSize, buffer, amount);
234 m_overflowSize += amount;
236 return size * nitems;
239 CCurlFile::CReadState::CReadState()
242 m_multiHandle = NULL;
243 m_overflowBuffer = NULL;
251 m_headerdone = false;
254 m_curlHeaderList = NULL;
255 m_curlAliasList = NULL;
258 CCurlFile::CReadState::~CReadState()
263 g_curlInterface.easy_release(&m_easyHandle, &m_multiHandle);
266 bool CCurlFile::CReadState::Seek(int64_t pos)
271 if(FITS_INT(pos - m_filePos) && m_buffer.SkipBytes((int)(pos - m_filePos)))
277 if(pos > m_filePos && pos < m_filePos + m_bufferSize)
279 int len = m_buffer.getMaxReadSize();
281 m_buffer.SkipBytes(len);
282 if(!FillBuffer(m_bufferSize))
284 if(!m_buffer.SkipBytes(-len))
285 CLog::Log(LOGERROR, "%s - Failed to restore position after failed fill", __FUNCTION__);
291 if(!FITS_INT(pos - m_filePos) || !m_buffer.SkipBytes((int)(pos - m_filePos)))
293 CLog::Log(LOGERROR, "%s - Failed to skip to position after having filled buffer", __FUNCTION__);
294 if(!m_buffer.SkipBytes(-len))
295 CLog::Log(LOGERROR, "%s - Failed to restore position after failed seek", __FUNCTION__);
306 void CCurlFile::CReadState::SetResume(void)
309 * Explicitly set RANGE header when filepos=0 as some http servers require us to always send the range
310 * request header. If we don't the server may provide different content causing seeking to fail.
311 * This only affects HTTP-like items, for FTP it's a null operation.
313 if (m_sendRange && m_filePos == 0)
314 g_curlInterface.easy_setopt(m_easyHandle, CURLOPT_RANGE, "0-");
317 g_curlInterface.easy_setopt(m_easyHandle, CURLOPT_RANGE, NULL);
321 g_curlInterface.easy_setopt(m_easyHandle, CURLOPT_RESUME_FROM_LARGE, m_filePos);
324 long CCurlFile::CReadState::Connect(unsigned int size)
327 CLog::Log(LOGDEBUG,"CurlFile::CReadState::Connect - Resume from position %"PRId64, m_filePos);
330 g_curlInterface.multi_add_handle(m_multiHandle, m_easyHandle);
334 m_buffer.Create(size * 3);
335 m_headerdone = false;
337 // read some data in to try and obtain the length
338 // maybe there's a better way to get this info??
342 CLog::Log(LOGERROR, "CCurlFile::CReadState::Connect, didn't get any data from stream.");
347 if (CURLE_OK == g_curlInterface.easy_getinfo(m_easyHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &length))
351 m_fileSize = m_filePos + (int64_t)length;
355 if (CURLE_OK == g_curlInterface.easy_getinfo(m_easyHandle, CURLINFO_RESPONSE_CODE, &response))
361 void CCurlFile::CReadState::Disconnect()
363 if(m_multiHandle && m_easyHandle)
364 g_curlInterface.multi_remove_handle(m_multiHandle, m_easyHandle);
367 free(m_overflowBuffer);
368 m_overflowBuffer = NULL;
376 if( m_curlHeaderList )
377 g_curlInterface.slist_free_all(m_curlHeaderList);
378 m_curlHeaderList = NULL;
380 if( m_curlAliasList )
381 g_curlInterface.slist_free_all(m_curlAliasList);
382 m_curlAliasList = NULL;
386 CCurlFile::~CCurlFile()
391 g_curlInterface.Unload();
394 CCurlFile::CCurlFile()
396 g_curlInterface.Load(); // loads the curl dll and resolves exports etc.
400 m_multisession = true;
402 m_useOldHttpVersion = false;
403 m_connecttimeout = 0;
408 m_bufferSize = 32768;
411 m_postdataset = false;
415 m_proxytype = PROXY_HTTP;
416 m_state = new CReadState();
422 //Has to be called before Open()
423 void CCurlFile::SetBufferSize(unsigned int size)
428 void CCurlFile::Close()
430 if (m_opened && m_forWrite && !m_inError)
433 m_state->Disconnect();
446 void CCurlFile::SetCommonOptions(CReadState* state)
448 CURL_HANDLE* h = state->m_easyHandle;
450 g_curlInterface.easy_reset(h);
452 g_curlInterface.easy_setopt(h, CURLOPT_DEBUGFUNCTION, debug_callback);
454 if( g_advancedSettings.m_logLevel >= LOG_LEVEL_DEBUG )
455 g_curlInterface.easy_setopt(h, CURLOPT_VERBOSE, TRUE);
457 g_curlInterface.easy_setopt(h, CURLOPT_VERBOSE, FALSE);
459 g_curlInterface.easy_setopt(h, CURLOPT_WRITEDATA, state);
460 g_curlInterface.easy_setopt(h, CURLOPT_WRITEFUNCTION, write_callback);
462 g_curlInterface.easy_setopt(h, CURLOPT_READDATA, state);
463 g_curlInterface.easy_setopt(h, CURLOPT_READFUNCTION, read_callback);
465 // set username and password for current handle
466 if (m_username.length() > 0 && m_password.length() > 0)
468 CStdString userpwd = m_username + ":" + m_password;
469 g_curlInterface.easy_setopt(h, CURLOPT_USERPWD, userpwd.c_str());
472 // make sure headers are seperated from the data stream
473 g_curlInterface.easy_setopt(h, CURLOPT_WRITEHEADER, state);
474 g_curlInterface.easy_setopt(h, CURLOPT_HEADERFUNCTION, header_callback);
475 g_curlInterface.easy_setopt(h, CURLOPT_HEADER, FALSE);
477 g_curlInterface.easy_setopt(h, CURLOPT_FTP_USE_EPSV, 0); // turn off epsv
479 // Allow us to follow two redirects
480 g_curlInterface.easy_setopt(h, CURLOPT_FOLLOWLOCATION, TRUE);
481 g_curlInterface.easy_setopt(h, CURLOPT_MAXREDIRS, 5);
483 // Enable cookie engine for current handle to re-use them in future requests
484 CStdString strCookieFile;
485 CStdString strTempPath = CSpecialProtocol::TranslatePath(g_advancedSettings.m_cachePath);
486 strCookieFile = URIUtils::AddFileToFolder(strTempPath, "cookies.dat");
488 g_curlInterface.easy_setopt(h, CURLOPT_COOKIEFILE, strCookieFile.c_str());
489 g_curlInterface.easy_setopt(h, CURLOPT_COOKIEJAR, strCookieFile.c_str());
491 // Set custom cookie if requested
492 if (!m_cookie.IsEmpty())
493 g_curlInterface.easy_setopt(h, CURLOPT_COOKIE, m_cookie.c_str());
495 g_curlInterface.easy_setopt(h, CURLOPT_COOKIELIST, "FLUSH");
497 // When using multiple threads you should set the CURLOPT_NOSIGNAL option to
498 // TRUE for all handles. Everything will work fine except that timeouts are not
499 // honored during the DNS lookup - which you can work around by building libcurl
500 // with c-ares support. c-ares is a library that provides asynchronous name
501 // resolves. Unfortunately, c-ares does not yet support IPv6.
502 g_curlInterface.easy_setopt(h, CURLOPT_NOSIGNAL, TRUE);
504 // not interested in failed requests
505 g_curlInterface.easy_setopt(h, CURLOPT_FAILONERROR, 1);
507 // enable support for icecast / shoutcast streams
508 if ( NULL == state->m_curlAliasList )
509 // m_curlAliasList is used only by this one place, but SetCommonOptions can
510 // be called multiple times, only append to list if it's empty.
511 state->m_curlAliasList = g_curlInterface.slist_append(state->m_curlAliasList, "ICY 200 OK");
512 g_curlInterface.easy_setopt(h, CURLOPT_HTTP200ALIASES, state->m_curlAliasList);
514 // never verify peer, we don't have any certificates to do this
515 g_curlInterface.easy_setopt(h, CURLOPT_SSL_VERIFYPEER, 0);
516 g_curlInterface.easy_setopt(h, CURLOPT_SSL_VERIFYHOST, 0);
518 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_URL, m_url.c_str());
519 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TRANSFERTEXT, FALSE);
521 // setup POST data if it is set (and it may be empty)
524 g_curlInterface.easy_setopt(h, CURLOPT_POST, 1 );
525 g_curlInterface.easy_setopt(h, CURLOPT_POSTFIELDSIZE, m_postdata.length());
526 g_curlInterface.easy_setopt(h, CURLOPT_POSTFIELDS, m_postdata.c_str());
529 // setup Referer header if needed
530 if (!m_referer.IsEmpty())
531 g_curlInterface.easy_setopt(h, CURLOPT_REFERER, m_referer.c_str());
534 g_curlInterface.easy_setopt(h, CURLOPT_REFERER, NULL);
535 g_curlInterface.easy_setopt(h, CURLOPT_AUTOREFERER, TRUE);
538 // setup any requested authentication
539 if( m_ftpauth.length() > 0 )
541 g_curlInterface.easy_setopt(h, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);
542 if( m_ftpauth.Equals("any") )
543 g_curlInterface.easy_setopt(h, CURLOPT_FTPSSLAUTH, CURLFTPAUTH_DEFAULT);
544 else if( m_ftpauth.Equals("ssl") )
545 g_curlInterface.easy_setopt(h, CURLOPT_FTPSSLAUTH, CURLFTPAUTH_SSL);
546 else if( m_ftpauth.Equals("tls") )
547 g_curlInterface.easy_setopt(h, CURLOPT_FTPSSLAUTH, CURLFTPAUTH_TLS);
550 // setup requested http authentication method
551 if(m_httpauth.length() > 0)
553 if( m_httpauth.Equals("any") )
554 g_curlInterface.easy_setopt(h, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
555 else if( m_httpauth.Equals("anysafe") )
556 g_curlInterface.easy_setopt(h, CURLOPT_HTTPAUTH, CURLAUTH_ANYSAFE);
557 else if( m_httpauth.Equals("digest") )
558 g_curlInterface.easy_setopt(h, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
559 else if( m_httpauth.Equals("ntlm") )
560 g_curlInterface.easy_setopt(h, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
563 // allow passive mode for ftp
564 if( m_ftpport.length() > 0 )
565 g_curlInterface.easy_setopt(h, CURLOPT_FTPPORT, m_ftpport.c_str());
567 g_curlInterface.easy_setopt(h, CURLOPT_FTPPORT, NULL);
569 // allow curl to not use the ip address in the returned pasv response
571 g_curlInterface.easy_setopt(h, CURLOPT_FTP_SKIP_PASV_IP, 0);
573 g_curlInterface.easy_setopt(h, CURLOPT_FTP_SKIP_PASV_IP, 1);
575 // setup Content-Encoding if requested
576 if( m_contentencoding.length() > 0 )
577 g_curlInterface.easy_setopt(h, CURLOPT_ENCODING, m_contentencoding.c_str());
579 if (m_userAgent.length() > 0)
580 g_curlInterface.easy_setopt(h, CURLOPT_USERAGENT, m_userAgent.c_str());
581 else /* set some default agent as shoutcast doesn't return proper stuff otherwise */
582 g_curlInterface.easy_setopt(h, CURLOPT_USERAGENT, g_advancedSettings.m_userAgent.c_str());
584 if (m_useOldHttpVersion)
585 g_curlInterface.easy_setopt(h, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
587 SetRequestHeader("Connection", "keep-alive");
589 if (g_advancedSettings.m_curlDisableIPV6)
590 g_curlInterface.easy_setopt(h, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
592 if (m_proxy.length() > 0)
594 g_curlInterface.easy_setopt(h, CURLOPT_PROXY, m_proxy.c_str());
595 g_curlInterface.easy_setopt(h, CURLOPT_PROXYTYPE, proxyType2CUrlProxyType[m_proxytype]);
596 if (m_proxyuserpass.length() > 0)
597 g_curlInterface.easy_setopt(h, CURLOPT_PROXYUSERPWD, m_proxyuserpass.c_str());
600 if (m_customrequest.length() > 0)
601 g_curlInterface.easy_setopt(h, CURLOPT_CUSTOMREQUEST, m_customrequest.c_str());
603 if (m_connecttimeout == 0)
604 m_connecttimeout = g_advancedSettings.m_curlconnecttimeout;
606 // set our timeouts, we abort connection after m_timeout, and reads after no data for m_timeout seconds
607 g_curlInterface.easy_setopt(h, CURLOPT_CONNECTTIMEOUT, m_connecttimeout);
609 // We abort in case we transfer less than 1byte/second
610 g_curlInterface.easy_setopt(h, CURLOPT_LOW_SPEED_LIMIT, 1);
612 if (m_lowspeedtime == 0)
613 m_lowspeedtime = g_advancedSettings.m_curllowspeedtime;
615 // Set the lowspeed time very low as it seems Curl takes much longer to detect a lowspeed condition
616 g_curlInterface.easy_setopt(h, CURLOPT_LOW_SPEED_TIME, m_lowspeedtime);
619 // For shoutcast file, content-length should not be set, and in libcurl there is a bug, if the
620 // cast file was 302 redirected then getinfo of CURLINFO_CONTENT_LENGTH_DOWNLOAD will return
621 // the 302 response's body length, which cause the next read request failed, so we ignore
622 // content-length for shoutcast file to workaround this.
623 g_curlInterface.easy_setopt(h, CURLOPT_IGNORE_CONTENT_LENGTH, 1);
626 void CCurlFile::SetRequestHeaders(CReadState* state)
628 if(state->m_curlHeaderList)
630 g_curlInterface.slist_free_all(state->m_curlHeaderList);
631 state->m_curlHeaderList = NULL;
634 MAPHTTPHEADERS::iterator it;
635 for(it = m_requestheaders.begin(); it != m_requestheaders.end(); it++)
637 CStdString buffer = it->first + ": " + it->second;
638 state->m_curlHeaderList = g_curlInterface.slist_append(state->m_curlHeaderList, buffer.c_str());
641 // add user defined headers
642 if (state->m_easyHandle)
643 g_curlInterface.easy_setopt(state->m_easyHandle, CURLOPT_HTTPHEADER, state->m_curlHeaderList);
646 void CCurlFile::SetCorrectHeaders(CReadState* state)
648 CHttpHeader& h = state->m_httpheader;
649 /* workaround for shoutcast server wich doesn't set content type on standard mp3 */
650 if( h.GetMimeType().empty() )
652 if( !h.GetValue("icy-notice1").empty()
653 || !h.GetValue("icy-name").empty()
654 || !h.GetValue("icy-br").empty() )
655 h.Parse("Content-Type: audio/mpeg\r\n");
658 /* hack for google video */
659 if (StringUtils::EqualsNoCase(h.GetMimeType(),"text/html")
660 && !h.GetValue("Content-Disposition").empty() )
662 CStdString strValue = h.GetValue("Content-Disposition");
663 if (strValue.Find("filename=") > -1 && strValue.Find(".flv") > -1)
664 h.Parse("Content-Type: video/flv\r\n");
668 void CCurlFile::ParseAndCorrectUrl(CURL &url2)
670 CStdString strProtocol = url2.GetTranslatedProtocol();
671 url2.SetProtocol(strProtocol);
673 if( strProtocol.Equals("ftp")
674 || strProtocol.Equals("ftps") )
676 // we was using url optons for urls, keep the old code work and warning
677 if (!url2.GetOptions().IsEmpty())
679 CLog::Log(LOGWARNING, "%s: ftp url option is deprecated, please switch to use protocol option (change '?' to '|'), url: [%s]", __FUNCTION__, url2.Get().c_str());
680 url2.SetProtocolOptions(url2.GetOptions().Mid(1));
681 /* ftp has no options */
685 /* this is uggly, depending on from where */
686 /* we get the link it may or may not be */
687 /* url encoded. if handed from ftpdirectory */
688 /* it won't be so let's handle that case */
690 CStdString partial, filename(url2.GetFileName());
691 std::vector<std::string> array;
693 // if server sent us the filename in non-utf8, we need send back with same encoding.
694 if (url2.GetProtocolOption("utf8") == "0")
695 g_charsetConverter.utf8ToStringCharset(filename);
697 /* TODO: create a tokenizer that doesn't skip empty's */
698 StringUtils::Tokenize(filename, array, "/");
700 for(std::vector<std::string>::iterator it = array.begin(); it != array.end(); it++)
702 if(it != array.begin())
706 CURL::Encode(partial);
710 /* make sure we keep slashes */
711 if(url2.GetFileName().Right(1) == "/")
714 url2.SetFileName(filename);
717 if (url2.HasProtocolOption("auth"))
719 m_ftpauth = url2.GetProtocolOption("auth");
720 if(m_ftpauth.IsEmpty())
724 if (url2.HasProtocolOption("active"))
726 m_ftpport = url2.GetProtocolOption("active");
727 if(m_ftpport.IsEmpty())
730 m_ftppasvip = url2.HasProtocolOption("pasvip") && url2.GetProtocolOption("pasvip") != "0";
732 else if( strProtocol.Equals("http")
733 || strProtocol.Equals("https"))
735 if (CSettings::Get().GetBool("network.usehttpproxy")
736 && !CSettings::Get().GetString("network.httpproxyserver").empty()
737 && CSettings::Get().GetInt("network.httpproxyport") > 0
738 && m_proxy.IsEmpty())
740 m_proxy = CSettings::Get().GetString("network.httpproxyserver");
741 m_proxy.AppendFormat(":%d", CSettings::Get().GetInt("network.httpproxyport"));
742 if (CSettings::Get().GetString("network.httpproxyusername").length() > 0 && m_proxyuserpass.IsEmpty())
744 m_proxyuserpass = CSettings::Get().GetString("network.httpproxyusername");
745 m_proxyuserpass += ":" + CSettings::Get().GetString("network.httpproxypassword");
747 m_proxytype = (ProxyType)CSettings::Get().GetInt("network.httpproxytype");
748 CLog::Log(LOGDEBUG, "Using proxy %s, type %d", m_proxy.c_str(), proxyType2CUrlProxyType[m_proxytype]);
751 // get username and password
752 m_username = url2.GetUserName();
753 m_password = url2.GetPassWord();
755 // handle any protocol options
756 std::map<CStdString, CStdString> options;
757 url2.GetProtocolOptions(options);
758 if (options.size() > 0)
760 // clear protocol options
761 url2.SetProtocolOptions("");
763 for(std::map<CStdString, CStdString>::const_iterator it = options.begin(); it != options.end(); ++it)
765 const CStdString &name = it->first;
766 const CStdString &value = it->second;
768 if(name.Equals("auth"))
771 if(m_httpauth.IsEmpty())
774 else if (name.Equals("Referer"))
776 else if (name.Equals("User-Agent"))
778 else if (name.Equals("Cookie"))
780 else if (name.Equals("Encoding"))
781 SetContentEncoding(value);
782 else if (name.Equals("noshout") && value.Equals("true"))
784 else if (name.Equals("seekable") && value.Equals("0"))
787 SetRequestHeader(name, value);
792 if (m_username.length() > 0 && m_password.length() > 0)
793 m_url = url2.GetWithoutUserDetails();
798 bool CCurlFile::Post(const CStdString& strURL, const CStdString& strPostData, CStdString& strHTML)
800 m_postdata = strPostData;
801 m_postdataset = true;
802 return Service(strURL, strHTML);
805 bool CCurlFile::Get(const CStdString& strURL, CStdString& strHTML)
808 m_postdataset = false;
809 return Service(strURL, strHTML);
812 bool CCurlFile::Service(const CStdString& strURL, CStdString& strHTML)
816 if (ReadData(strHTML))
826 bool CCurlFile::ReadData(CStdString& strHTML)
832 while( (size_read = Read(buffer, sizeof(buffer)-1) ) > 0 )
834 buffer[size_read] = 0;
835 strHTML.append(buffer, size_read);
836 data_size += size_read;
838 if (m_state->m_cancelled)
843 bool CCurlFile::Download(const CStdString& strURL, const CStdString& strFileName, LPDWORD pdwSize)
845 CLog::Log(LOGINFO, "CCurlFile::Download - %s->%s", strURL.c_str(), strFileName.c_str());
848 if (!Get(strURL, strData))
852 if (!file.OpenForWrite(strFileName, true))
854 CLog::Log(LOGERROR, "CCurlFile::Download - Unable to open file %s: %u",
855 strFileName.c_str(), GetLastError());
859 file.Write(strData.c_str(), strData.size());
864 *pdwSize = strData.size();
870 // Detect whether we are "online" or not! Very simple and dirty!
871 bool CCurlFile::IsInternet(bool checkDNS /* = true */)
873 CStdString strURL = "http://www.google.com";
875 strURL = "http://74.125.19.103"; // www.google.com ip
877 bool found = Exists(strURL);
883 void CCurlFile::Cancel()
885 m_state->m_cancelled = true;
890 void CCurlFile::Reset()
892 m_state->m_cancelled = false;
895 bool CCurlFile::Open(const CURL& url)
901 ParseAndCorrectUrl(url2);
903 CLog::Log(LOGDEBUG, "CurlFile::Open(%p) %s", (void*)this, m_url.c_str());
905 ASSERT(!(!m_state->m_easyHandle ^ !m_state->m_multiHandle));
906 if( m_state->m_easyHandle == NULL )
907 g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, &m_state->m_multiHandle );
909 // setup common curl options
910 SetCommonOptions(m_state);
911 SetRequestHeaders(m_state);
912 m_state->m_sendRange = m_seekable;
914 m_httpresponse = m_state->Connect(m_bufferSize);
915 if( m_httpresponse < 0 || m_httpresponse >= 400)
918 SetCorrectHeaders(m_state);
920 // since we can't know the stream size up front if we're gzipped/deflated
921 // flag the stream with an unknown file size rather than the compressed
923 if (m_contentencoding.size() > 0)
924 m_state->m_fileSize = 0;
926 // check if this stream is a shoutcast stream. sometimes checking the protocol line is not enough so examine other headers as well.
927 // shoutcast streams should be handled by FileShoutcast.
928 if ((m_state->m_httpheader.GetProtoLine().substr(0, 3) == "ICY" || !m_state->m_httpheader.GetValue("icy-notice1").empty()
929 || !m_state->m_httpheader.GetValue("icy-name").empty()
930 || !m_state->m_httpheader.GetValue("icy-br").empty()) && !m_skipshout)
932 CLog::Log(LOGDEBUG,"CCurlFile::Open - File <%s> is a shoutcast stream. Re-opening", m_url.c_str());
933 throw new CRedirectException(new CShoutcastFile);
936 m_multisession = false;
937 if(url2.GetProtocol().Equals("http") || url2.GetProtocol().Equals("https"))
939 m_multisession = true;
940 if(m_state->m_httpheader.GetValue("Server").find("Portable SDK for UPnP devices") != std::string::npos)
942 CLog::Log(LOGWARNING, "CCurlFile::Open - Disabling multi session due to broken libupnp server");
943 m_multisession = false;
947 if(StringUtils::EqualsNoCase(m_state->m_httpheader.GetValue("Transfer-Encoding"), "chunked"))
948 m_state->m_fileSize = 0;
950 if(m_state->m_fileSize <= 0)
954 if(url2.GetProtocol().Equals("http")
955 || url2.GetProtocol().Equals("https"))
957 // if server says explicitly it can't seek, respect that
958 if(StringUtils::EqualsNoCase(m_state->m_httpheader.GetValue("Accept-Ranges"),"none"))
964 if (CURLE_OK == g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_EFFECTIVE_URL,&efurl) && efurl)
970 bool CCurlFile::OpenForWrite(const CURL& url, bool bOverWrite)
975 if (Exists(url) && !bOverWrite)
979 ParseAndCorrectUrl(url2);
981 CLog::Log(LOGDEBUG, "CCurlFile::OpenForWrite(%p) %s", (void*)this, m_url.c_str());
983 ASSERT(m_state->m_easyHandle == NULL);
984 g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, &m_state->m_multiHandle);
986 // setup common curl options
987 SetCommonOptions(m_state);
988 SetRequestHeaders(m_state);
991 if (CURLE_OK == g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_EFFECTIVE_URL,&efurl) && efurl)
999 ASSERT(m_state->m_multiHandle);
1001 SetCommonOptions(m_state);
1002 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_UPLOAD, 1);
1004 g_curlInterface.multi_add_handle(m_state->m_multiHandle, m_state->m_easyHandle);
1006 m_state->SetReadBuffer(NULL, 0);
1011 int CCurlFile::Write(const void* lpBuf, int64_t uiBufSize)
1013 if (!(m_opened && m_forWrite) || m_inError)
1016 ASSERT(m_state->m_multiHandle);
1018 m_state->SetReadBuffer(lpBuf, uiBufSize);
1019 m_state->m_isPaused = false;
1020 g_curlInterface.easy_pause(m_state->m_easyHandle, CURLPAUSE_CONT);
1022 CURLMcode result = CURLM_OK;
1025 while (m_stillRunning && !m_state->m_isPaused)
1027 while ((result = g_curlInterface.multi_perform(m_state->m_multiHandle, &m_stillRunning)) == CURLM_CALL_MULTI_PERFORM);
1029 if (!m_stillRunning)
1032 if (result != CURLM_OK)
1035 if(g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_RESPONSE_CODE, &code) == CURLE_OK )
1036 CLog::Log(LOGERROR, "%s - Unable to write curl resource (%s) - %ld", __FUNCTION__, m_url.c_str(), code);
1042 m_writeOffset += m_state->m_filePos;
1043 return m_state->m_filePos;
1046 bool CCurlFile::CReadState::ReadString(char *szLine, int iLineLength)
1048 unsigned int want = (unsigned int)iLineLength;
1050 if((m_fileSize == 0 || m_filePos < m_fileSize) && !FillBuffer(want))
1053 // ensure only available data is considered
1054 want = XMIN((unsigned int)m_buffer.getMaxReadSize(), want);
1056 /* check if we finished prematurely */
1057 if (!m_stillRunning && (m_fileSize == 0 || m_filePos != m_fileSize) && !want)
1059 if (m_fileSize != 0)
1060 CLog::Log(LOGWARNING, "%s - Transfer ended before entire file was retrieved pos %"PRId64", size %"PRId64, __FUNCTION__, m_filePos, m_fileSize);
1065 char* pLine = szLine;
1068 if (!m_buffer.ReadData(pLine, 1))
1072 } while (((pLine - 1)[0] != '\n') && ((unsigned int)(pLine - szLine) < want));
1074 m_filePos += (pLine - szLine);
1075 return (bool)((pLine - szLine) > 0);
1078 bool CCurlFile::Exists(const CURL& url)
1080 // if file is already running, get info from it
1083 CLog::Log(LOGWARNING, "CCurlFile::Exists - Exist called on open file %s", url.Get().c_str());
1088 ParseAndCorrectUrl(url2);
1090 ASSERT(m_state->m_easyHandle == NULL);
1091 g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, NULL);
1093 SetCommonOptions(m_state);
1094 SetRequestHeaders(m_state);
1095 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TIMEOUT, 5);
1096 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_NOBODY, 1);
1097 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_WRITEDATA, NULL); /* will cause write failure*/
1099 if(url2.GetProtocol() == "ftp")
1101 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FILETIME, 1);
1102 // nocwd is less standard, will return empty list for non-existed remote dir on some ftp server, avoid it.
1103 if (StringUtils::EndsWith(url2.GetFileName(), "/"))
1104 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_SINGLECWD);
1106 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_NOCWD);
1109 CURLcode result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1110 g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1112 if (result == CURLE_WRITE_ERROR || result == CURLE_OK)
1115 if (result == CURLE_HTTP_RETURNED_ERROR)
1118 if(g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_RESPONSE_CODE, &code) == CURLE_OK && code != 404 )
1119 CLog::Log(LOGERROR, "CCurlFile::Exists - Failed: HTTP returned error %ld for %s", code, url.Get().c_str());
1121 else if (result != CURLE_REMOTE_FILE_NOT_FOUND && result != CURLE_FTP_COULDNT_RETR_FILE)
1123 CLog::Log(LOGERROR, "CCurlFile::Exists - Failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.Get().c_str());
1130 int64_t CCurlFile::Seek(int64_t iFilePosition, int iWhence)
1132 int64_t nextPos = m_state->m_filePos;
1136 nextPos = iFilePosition;
1139 nextPos += iFilePosition;
1142 if (m_state->m_fileSize)
1143 nextPos = m_state->m_fileSize + iFilePosition;
1151 // We can't seek beyond EOF
1152 if (m_state->m_fileSize && nextPos > m_state->m_fileSize) return -1;
1154 if(m_state->Seek(nextPos))
1157 if (m_oldState && m_oldState->Seek(nextPos))
1159 CReadState *tmp = m_state;
1160 m_state = m_oldState;
1168 CReadState* oldstate = NULL;
1172 oldstate = m_oldState;
1173 m_oldState = m_state;
1174 m_state = new CReadState();
1176 g_curlInterface.easy_aquire(url.GetProtocol(), url.GetHostName(), &m_state->m_easyHandle, &m_state->m_multiHandle );
1178 m_state->m_fileSize = m_oldState->m_fileSize;
1181 m_state->Disconnect();
1183 // re-setup common curl options
1184 SetCommonOptions(m_state);
1186 /* caller might have changed some headers (needed for daap)*/
1187 SetRequestHeaders(m_state);
1189 m_state->m_filePos = nextPos;
1190 m_state->m_sendRange = true;
1192 long response = m_state->Connect(m_bufferSize);
1193 if(response < 0 && (m_state->m_fileSize == 0 || m_state->m_fileSize != m_state->m_filePos))
1196 if(m_multisession && m_oldState)
1199 m_state = m_oldState;
1200 m_oldState = oldstate;
1205 SetCorrectHeaders(m_state);
1208 return m_state->m_filePos;
1211 int64_t CCurlFile::GetLength()
1213 if (!m_opened) return 0;
1214 return m_state->m_fileSize;
1217 int64_t CCurlFile::GetPosition()
1219 if (!m_opened) return 0;
1220 return m_state->m_filePos;
1223 int CCurlFile::Stat(const CURL& url, struct __stat64* buffer)
1225 // if file is already running, get info from it
1228 CLog::Log(LOGWARNING, "CCurlFile::Stat - Stat called on open file %s", url.Get().c_str());
1231 memset(buffer, 0, sizeof(struct __stat64));
1232 buffer->st_size = GetLength();
1233 buffer->st_mode = _S_IFREG;
1239 ParseAndCorrectUrl(url2);
1241 ASSERT(m_state->m_easyHandle == NULL);
1242 g_curlInterface.easy_aquire(url2.GetProtocol(), url2.GetHostName(), &m_state->m_easyHandle, NULL);
1244 SetCommonOptions(m_state);
1245 SetRequestHeaders(m_state);
1246 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TIMEOUT, g_advancedSettings.m_curlconnecttimeout);
1247 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_NOBODY, 1);
1248 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_WRITEDATA, NULL); /* will cause write failure*/
1249 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FILETIME , 1);
1251 if(url2.GetProtocol() == "ftp")
1253 // nocwd is less standard, will return empty list for non-existed remote dir on some ftp server, avoid it.
1254 if (StringUtils::EndsWith(url2.GetFileName(), "/"))
1255 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_SINGLECWD);
1257 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FTP_FILEMETHOD, CURLFTPMETHOD_NOCWD);
1260 CURLcode result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1262 if(result == CURLE_HTTP_RETURNED_ERROR)
1265 if(g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_RESPONSE_CODE, &code) == CURLE_OK && code == 404 )
1269 if(result == CURLE_GOT_NOTHING
1270 || result == CURLE_HTTP_RETURNED_ERROR
1271 || result == CURLE_RECV_ERROR /* some silly shoutcast servers */ )
1273 /* some http servers and shoutcast servers don't give us any data on a head request */
1274 /* request normal and just fail out, it's their loss */
1275 /* somehow curl doesn't reset CURLOPT_NOBODY properly so reset everything */
1276 SetCommonOptions(m_state);
1277 SetRequestHeaders(m_state);
1278 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_TIMEOUT, g_advancedSettings.m_curlconnecttimeout);
1279 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_RANGE, "0-0");
1280 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_WRITEDATA, NULL); /* will cause write failure*/
1281 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_FILETIME, 1);
1282 result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1285 if( result == CURLE_HTTP_RANGE_ERROR )
1287 /* crap can't use the range option, disable it and try again */
1288 g_curlInterface.easy_setopt(m_state->m_easyHandle, CURLOPT_RANGE, NULL);
1289 result = g_curlInterface.easy_perform(m_state->m_easyHandle);
1292 if( result != CURLE_WRITE_ERROR && result != CURLE_OK )
1294 g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1296 CLog::Log(LOGERROR, "CCurlFile::Stat - Failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.Get().c_str());
1301 result = g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &length);
1302 if (result != CURLE_OK || length < 0.0)
1304 if (url.GetProtocol() == "ftp")
1306 g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1307 CLog::Log(LOGNOTICE, "CCurlFile::Stat - Content length failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.Get().c_str());
1315 SetCorrectHeaders(m_state);
1320 result = g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_CONTENT_TYPE, &content);
1321 if (result != CURLE_OK)
1323 CLog::Log(LOGNOTICE, "CCurlFile::Stat - Content type failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.Get().c_str());
1324 g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1330 memset(buffer, 0, sizeof(struct __stat64));
1331 buffer->st_size = (int64_t)length;
1332 if(content && strstr(content, "text/html")) //consider html files directories
1333 buffer->st_mode = _S_IFDIR;
1335 buffer->st_mode = _S_IFREG;
1338 result = g_curlInterface.easy_getinfo(m_state->m_easyHandle, CURLINFO_FILETIME, &filetime);
1339 if (result != CURLE_OK)
1341 CLog::Log(LOGNOTICE, "CCurlFile::Stat - Filetime failed: %s(%d) for %s", g_curlInterface.easy_strerror(result), result, url.Get().c_str());
1346 buffer->st_mtime = filetime;
1349 g_curlInterface.easy_release(&m_state->m_easyHandle, NULL);
1353 unsigned int CCurlFile::CReadState::Read(void* lpBuf, int64_t uiBufSize)
1355 /* only request 1 byte, for truncated reads (only if not eof) */
1356 if((m_fileSize == 0 || m_filePos < m_fileSize) && !FillBuffer(1))
1359 /* ensure only available data is considered */
1360 unsigned int want = (unsigned int)XMIN(m_buffer.getMaxReadSize(), uiBufSize);
1362 /* xfer data to caller */
1363 if (m_buffer.ReadData((char *)lpBuf, want))
1369 /* check if we finished prematurely */
1370 if (!m_stillRunning && (m_fileSize == 0 || m_filePos != m_fileSize))
1372 CLog::Log(LOGWARNING, "%s - Transfer ended before entire file was retrieved pos %"PRId64", size %"PRId64, __FUNCTION__, m_filePos, m_fileSize);
1379 /* use to attempt to fill the read buffer up to requested number of bytes */
1380 bool CCurlFile::CReadState::FillBuffer(unsigned int want)
1387 // only attempt to fill buffer if transactions still running and buffer
1388 // doesnt exceed required size already
1389 while ((unsigned int)m_buffer.getMaxReadSize() < want && m_buffer.getMaxWriteSize() > 0 )
1394 /* if there is data in overflow buffer, try to use that first */
1397 unsigned amount = XMIN((unsigned int)m_buffer.getMaxWriteSize(), m_overflowSize);
1398 m_buffer.WriteData(m_overflowBuffer, amount);
1400 if (amount < m_overflowSize)
1401 memcpy(m_overflowBuffer, m_overflowBuffer+amount,m_overflowSize-amount);
1403 m_overflowSize -= amount;
1404 m_overflowBuffer = (char*)realloc_simple(m_overflowBuffer, m_overflowSize);
1408 CURLMcode result = g_curlInterface.multi_perform(m_multiHandle, &m_stillRunning);
1409 if (!m_stillRunning)
1411 if (result == CURLM_OK)
1413 /* if we still have stuff in buffer, we are fine */
1414 if (m_buffer.getMaxReadSize())
1417 /* verify that we are actually okey */
1419 CURLcode CURLresult = CURLE_OK;
1421 while ((msg = g_curlInterface.multi_info_read(m_multiHandle, &msgs)))
1423 if (msg->msg == CURLMSG_DONE)
1425 if (msg->data.result == CURLE_OK)
1428 CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Failed: %s(%d)", g_curlInterface.easy_strerror(msg->data.result), msg->data.result);
1430 // We need to check the result here as we don't want to retry on every error
1431 if ( (msg->data.result == CURLE_OPERATION_TIMEDOUT ||
1432 msg->data.result == CURLE_PARTIAL_FILE ||
1433 msg->data.result == CURLE_COULDNT_CONNECT ||
1434 msg->data.result == CURLE_RECV_ERROR) &&
1436 CURLresult = msg->data.result;
1437 else if ( (msg->data.result == CURLE_HTTP_RANGE_ERROR ||
1438 msg->data.result == CURLE_HTTP_RETURNED_ERROR) &&
1443 // If server returns a range or http error, retry with range disabled
1444 CURLresult = msg->data.result;
1445 m_sendRange = false;
1452 // Don't retry when we didn't "see" any error
1453 if (CURLresult == CURLE_OK)
1457 if (m_multiHandle && m_easyHandle)
1458 g_curlInterface.multi_remove_handle(m_multiHandle, m_easyHandle);
1460 // Reset all the stuff like we would in Disconnect()
1462 free(m_overflowBuffer);
1463 m_overflowBuffer = NULL;
1466 // If we got here something is wrong
1467 if (++retry > g_advancedSettings.m_curlretries)
1469 CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Reconnect failed!");
1470 // Reset the rest of the variables like we would in Disconnect()
1478 CLog::Log(LOGNOTICE, "CCurlFile::FillBuffer - Reconnect, (re)try %i", retry);
1480 // Connect + seek to current position (again)
1482 g_curlInterface.multi_add_handle(m_multiHandle, m_easyHandle);
1484 // Return to the beginning of the loop:
1490 // We've finished out first loop
1491 if(m_bFirstLoop && m_buffer.getMaxReadSize() > 0)
1492 m_bFirstLoop = false;
1503 // get file descriptors from the transfers
1504 g_curlInterface.multi_fdset(m_multiHandle, &fdread, &fdwrite, &fdexcep, &maxfd);
1507 if (CURLM_OK != g_curlInterface.multi_timeout(m_multiHandle, &timeout) || timeout == -1)
1510 struct timeval t = { timeout / 1000, (timeout % 1000) * 1000 };
1512 /* Wait until data is available or a timeout occurs.
1513 We call dllselect(maxfd + 1, ...), specially in case of (maxfd == -1),
1514 we call dllselect(0, ...), which is basically equal to sleep. */
1515 if (SOCKET_ERROR == dllselect(maxfd + 1, &fdread, &fdwrite, &fdexcep, &t))
1517 CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Failed with socket error");
1522 case CURLM_CALL_MULTI_PERFORM:
1524 // we don't keep calling here as that can easily overwrite our buffer which we want to avoid
1525 // docs says we should call it soon after, but aslong as we are reading data somewhere
1526 // this aught to be soon enough. should stay in socket otherwise
1532 CLog::Log(LOGERROR, "CCurlFile::FillBuffer - Multi perform failed with code %d, aborting", result);
1541 void CCurlFile::CReadState::SetReadBuffer(const void* lpBuf, int64_t uiBufSize)
1543 m_readBuffer = (char*)lpBuf;
1544 m_fileSize = uiBufSize;
1548 void CCurlFile::ClearRequestHeaders()
1550 m_requestheaders.clear();
1553 void CCurlFile::SetRequestHeader(CStdString header, CStdString value)
1555 m_requestheaders[header] = value;
1558 void CCurlFile::SetRequestHeader(CStdString header, long value)
1561 buffer.Format("%ld", value);
1562 m_requestheaders[header] = buffer;
1565 /* STATIC FUNCTIONS */
1566 bool CCurlFile::GetHttpHeader(const CURL &url, CHttpHeader &headers)
1571 if(file.Stat(url, NULL) == 0)
1573 headers = file.GetHttpHeader();
1580 CLog::Log(LOGERROR, "%s - Exception thrown while trying to retrieve header url: %s", __FUNCTION__, url.Get().c_str());
1585 bool CCurlFile::GetMimeType(const CURL &url, CStdString &content, CStdString useragent)
1588 if (!useragent.IsEmpty())
1589 file.SetUserAgent(useragent);
1591 struct __stat64 buffer;
1592 if( file.Stat(url, &buffer) == 0 )
1594 if (buffer.st_mode == _S_IFDIR)
1595 content = "x-directory/normal";
1597 content = file.GetMimeType();
1598 CLog::Log(LOGDEBUG, "CCurlFile::GetMimeType - %s -> %s", url.Get().c_str(), content.c_str());
1601 CLog::Log(LOGDEBUG, "CCurlFile::GetMimeType - %s -> failed", url.Get().c_str());
1606 int CCurlFile::IoControl(EIoControl request, void* param)
1608 if(request == IOCTRL_SEEK_POSSIBLE)
1609 return m_seekable ? 1 : 0;