/// <summary> /// Obtain status information for a Multi transfer. /// </summary> /// <returns> /// An array of <see cref="MultiInfo"/> objects, one for each /// <see cref="Easy"/> object child. /// </returns> /// <exception cref="System.NullReferenceException"> /// This is thrown if the native <c>Multi</c> handle wasn't /// created successfully. /// </exception> public MultiInfo[] InfoRead() { if (m_bGotMultiInfo) { return(m_multiInfo); } m_bGotMultiInfo = true; int nMsgs = 0; IntPtr pInfo = External.curl_shim_multi_info_read(m_pMulti, ref nMsgs); if (pInfo != IntPtr.Zero) { m_multiInfo = new MultiInfo[nMsgs]; for (int i = 0; i < nMsgs; i++) { CURLMSG msg = (CURLMSG)Marshal.ReadInt32( pInfo, i * 12); IntPtr pEasy = Marshal.ReadIntPtr( pInfo, i * 12 + 4); CURLcode code = (CURLcode)Marshal.ReadInt32( pInfo, i * 12 + 8); m_multiInfo[i] = new MultiInfo(msg, (Easy)m_htEasy[pEasy], code); } External.curl_shim_multi_info_free(pInfo); } return(m_multiInfo); }
/// <summary> /// Process-wide initialization -- call only once per process. /// </summary> /// <param name="flags">An or'd combination of /// <see cref="CURLinitFlag"/> members.</param> /// <returns>A <see cref="CURLcode"/>, hopefully /// <c>CURLcode.CURLE_OK</c>.</returns> public static CURLcode GlobalInit(int flags) { sm_curlCode = External.curl_global_init(flags); if (sm_curlCode == CURLcode.CURLE_OK) External.curl_shim_initialize(); return sm_curlCode; }
/// <summary> /// Extract <c>DateTime</c> information from an <c>Easy</c> object. /// </summary> /// <param name="info">One of the values in the /// <see cref="CURLINFO"/> enumeration. In this case, it must /// specifically be <see cref="CURLINFO.CURLINFO_FILETIME"/>. /// </param> /// <param name="dt">Reference to a <c>DateTime</c> value.</param> /// <returns>The <see cref="CURLcode"/> obtained from the internal /// call to <c>curl_easy_getinfo()</c>. /// </returns> /// <exception cref="System.NullReferenceException">This is thrown if /// the native <c>CURL*</c> handle wasn't created successfully.</exception> public CURLcode GetInfo(CURLINFO info, ref DateTime dt) { EnsureHandle(); CURLcode retCode = CURLcode.CURLE_OK; IntPtr ptr = IntPtr.Zero; if (info != CURLINFO.CURLINFO_FILETIME) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } retCode = External.curl_easy_getinfo(m_pCURL, info, ref ptr); if (retCode == CURLcode.CURLE_OK) { if ((int)ptr < 0) { dt = new DateTime(0); } else { int yy = 0, mm = 0, dd = 0, hh = 0, mn = 0, ss = 0; External.curl_shim_get_file_time((int)ptr, ref yy, ref mm, ref dd, ref hh, ref mn, ref ss); dt = new DateTime(yy, mm, dd, hh, mn, ss); } } return(retCode); }
public string Perform() { CURLcode data = easy.Perform(); easy.Dispose(); return(buffer); }
//static object lock_variable = new object(); /// <summary> /// Downloads web page synchronously /// </summary> /// <param name="url">url of page</param> /// <param name="send_cookies">defines if cookies should be sent</param> /// <returns>reqest status</returns> public bool GetPage(string url, bool send_cookies) { if (AutoRotateProxy) { proxy = Proxies.Next(); } int attempt_count = 1; CURLcode rc = load_page(url, send_cookies); while (proxy != null && (rc == CURLcode.CURLE_GOT_NOTHING || rc == CURLcode.CURLE_COULDNT_RESOLVE_PROXY || rc == CURLcode.CURLE_OPERATION_TIMEOUTED || rc == CURLcode.CURLE_COULDNT_CONNECT || rc == CURLcode.CURLE_SEND_ERROR) ) { Proxies.Delete(proxy); if (attempt_count >= Config.Proxy.MaxAttemptCountWithNewProxy) { WR.log.Error("Attempt quota exeeded: " + attempt_count.ToString()); break; } proxy = Proxies.Next(); attempt_count++; WR.log.Write("Attempt #: " + attempt_count.ToString()); rc = load_page(url, send_cookies); } return(rc == CURLcode.CURLE_OK); }
/// <summary> /// Process-wide cleanup -- call just before exiting process. /// </summary> /// <remarks> /// While it's not necessary that your program call this method /// before exiting, doing so will prevent leaks of native cURL resources. /// </remarks> public static void GlobalCleanup() { if (sm_curlCode == CURLcode.CURLE_OK) { External.curl_shim_cleanup(); External.curl_global_cleanup(); sm_curlCode = CURLcode.CURLE_FAILED_INIT; } }
/// <summary> /// Process-wide initialization -- call only once per process. /// </summary> /// <param name="flags">An or'd combination of /// <see cref="CURLinitFlag"/> members.</param> /// <returns>A <see cref="CURLcode"/>, hopefully /// <c>CURLcode.CURLE_OK</c>.</returns> public static CURLcode GlobalInit(int flags) { sm_curlCode = External.curl_global_init(flags); if (sm_curlCode == CURLcode.CURLE_OK) { External.curl_shim_initialize(); } return(sm_curlCode); }
static void Main(string[] args) { Console.WriteLine("libcurlFtpsExample..."); const string url = "ftp://*****:*****@ftp.somesite.com/dir/"; try { Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL); Easy easy = new Easy(); if (easy != null) { easy.SetOpt(CURLoption.CURLOPT_URL, url); easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, false); easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYHOST, false); easy.SetOpt(CURLoption.CURLOPT_FTP_SSL, CURLftpSSL.CURLFTPSSL_TRY); // For debugging will print headers to console. Easy.HeaderFunction hf = new Easy.HeaderFunction(OnHeaderData); easy.SetOpt(CURLoption.CURLOPT_HEADERFUNCTION, hf); // For debugging will print received data to console. Easy.DebugFunction df = new Easy.DebugFunction(OnDebug); easy.SetOpt(CURLoption.CURLOPT_DEBUGFUNCTION, df); easy.SetOpt(CURLoption.CURLOPT_VERBOSE, true); // List directory only easy.SetOpt(CURLoption.CURLOPT_FTPLISTONLY, true); CURLcode code = easy.Perform(); if (code != CURLcode.CURLE_OK) { Console.WriteLine("Request failed!"); } easy.Cleanup(); } else { Console.WriteLine("Failed to get Easy libcurl handle!"); } } catch (Exception exp) { Console.WriteLine(exp); } finally { Curl.GlobalCleanup(); } }
public static Int64 GetUrlFileSizeEx(string url, string hostname, int timeout) { long size = -1; Easy easy = new Easy(); Easy.SetCurrentEasy(easy); Slist headers = new Slist(); headers.Append(HobaText.Format("Host: {0}", hostname)); easy.SetOpt(CURLoption.CURLOPT_URL, url); easy.SetOpt(CURLoption.CURLOPT_HEADER, 1L); easy.SetOpt(CURLoption.CURLOPT_NOBODY, 1L); easy.SetOpt(CURLoption.CURLOPT_HTTPHEADER, headers); //easy.SetOpt(CURLoption.CURLOPT_IPRESOLVE, (long)CURLipResolve.CURL_IPRESOLVE_V4); easy.SetOpt(CURLoption.CURLOPT_CONNECTTIMEOUT, timeout / 1000); easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, 0L); easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYHOST, 0L); int error = 0; double downloadFileLength = 0.0f; if (easy.Perform() == CURLcode.CURLE_OK) { CURLcode code = easy.GetInfo(CURLINFO.CURLINFO_RESPONSE_CODE, ref error); if (code == CURLcode.CURLE_OK && error == 200) { easy.GetInfo(CURLINFO.CURLINFO_CONTENT_LENGTH_DOWNLOAD, ref downloadFileLength); } if (downloadFileLength >= 0.0f) { size = (int)downloadFileLength; } } else { size = -1; } headers.FreeAll(); Easy.SetCurrentEasy(null); easy.Cleanup(); return(size); }
/// <summary> /// Extract <c>string</c> information from an <c>Easy</c> object. /// </summary> /// <param name="info">One of the values in the /// <see cref="CURLINFO"/> enumeration. In this case, it must /// specifically be one of the members that obtains a <c>string</c>. /// </param> /// <param name="strVal">Reference to an <c>string</c> value.</param> /// <returns>The <see cref="CURLcode"/> obtained from the internal /// call to <c>curl_easy_getinfo()</c>. /// </returns> /// <exception cref="System.NullReferenceException">This is thrown if /// the native <c>CURL*</c> handle wasn't created successfully.</exception> public CURLcode GetInfo(CURLINFO info, ref string strVal) { EnsureHandle(); CURLcode retCode = CURLcode.CURLE_OK; IntPtr ptr = IntPtr.Zero; if ((int)info < CURLINFO_STRING || (int)info >= CURLINFO_LONG) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } retCode = External.curl_easy_getinfo_ptr(m_pCURL, info, ref ptr); if (retCode == CURLcode.CURLE_OK) { strVal = Marshal.PtrToStringAnsi(ptr); } return(retCode); }
/// <summary> /// Returns whether the given CURLcode is an SSL error code. /// </summary> /// <param name="curlCode"></param> /// <returns></returns> public static bool IsSslError(CURLcode curlCode) { switch (curlCode) { case CURLcode.PEER_FAILED_VERIFICATION: case CURLcode.SSL_CIPHER: case CURLcode.SSL_ENGINE_INITFAILED: case CURLcode.SSL_CONNECT_ERROR: case CURLcode.SSL_INVALIDCERTSTATUS: case CURLcode.SSL_ISSUER_ERROR: case CURLcode.SSL_SHUTDOWN_FAILED: return(true); default: return(false); } }
/// <summary> /// Extract <c>DateTime</c> information from an <c>Easy</c> object. /// </summary> /// <param name="info">One of the values in the /// <see cref="CURLINFO"/> enumeration. In this case, it must /// specifically be <see cref="CURLINFO.CURLINFO_FILETIME"/>. /// </param> /// <param name="dt">Reference to a <c>DateTime</c> value.</param> /// <returns>The <see cref="CURLcode"/> obtained from the internal /// call to <c>curl_easy_getinfo()</c>. /// </returns> /// <exception cref="System.NullReferenceException">This is thrown if /// the native <c>CURL*</c> handle wasn't created successfully.</exception> public CURLcode GetInfo(CURLINFO info, ref DateTime dt) { EnsureHandle(); CURLcode retCode = CURLcode.CURLE_OK; if (info != CURLINFO.CURLINFO_FILETIME) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } int yy = 0, mm = 0, dd = 0, hh = 0, mn = 0, ss = 0; retCode = External.curl_easy_getinfo_time(m_pCURL, info, ref yy, ref mm, ref dd, ref hh, ref mn, ref ss); if (retCode == CURLcode.CURLE_OK) { dt = new DateTime(yy, mm, dd, hh, mn, ss); } return(retCode); }
/// <summary> /// Extract <c>int</c> information from an <c>Easy</c> object. /// </summary> /// <param name="info">One of the values in the /// <see cref="CURLINFO"/> enumeration. In this case, it must /// specifically be one of the members that obtains an <c>int</c>. /// </param> /// <param name="intVal">Reference to an <c>int</c> value.</param> /// <returns>The <see cref="CURLcode"/> obtained from the internal /// call to <c>curl_easy_getinfo()</c>. /// </returns> /// <exception cref="System.NullReferenceException">This is thrown if /// the native <c>CURL*</c> handle wasn't created successfully.</exception> public CURLcode GetInfo(CURLINFO info, ref int intVal) { EnsureHandle(); CURLcode retCode = CURLcode.CURLE_OK; IntPtr ptr = IntPtr.Zero; // ensure it's an integral type if ((int)info < CURLINFO_LONG || (int)info >= CURLINFO_DOUBLE) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } retCode = External.curl_easy_getinfo(m_pCURL, info, ref ptr); if (retCode == CURLcode.CURLE_OK) { intVal = (int)ptr; } return(retCode); }
/// <summary> /// Extract information from a cURL handle. /// </summary> /// <param name="info">One of the values in the /// <see cref="CURLINFO"/> enumeration.</param> /// <param name="objInfo">Reference to an object into which the /// value specified by <c>info</c> is written.</param> /// <returns>The <see cref="CURLcode"/> obtained from the internal /// call to <c>curl_easy_getinfo()</c>. /// </returns> /// <exception cref="System.NullReferenceException">This is thrown if /// the native <c>CURL*</c> handle wasn't created successfully.</exception> public CURLcode GetInfo(CURLINFO info, ref Object objInfo) { EnsureHandle(); CURLcode retCode = CURLcode.CURLE_OK; IntPtr ptr = IntPtr.Zero; if ((int)info < CURLINFO_STRING) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } // trickery for filetime if (info == CURLINFO.CURLINFO_FILETIME) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } // private data if (info == CURLINFO.CURLINFO_PRIVATE) { objInfo = m_privateData; return(retCode); } // string case if ((int)info < CURLINFO_LONG) { retCode = External.curl_easy_getinfo_ptr(m_pCURL, info, ref ptr); if (retCode == CURLcode.CURLE_OK) { objInfo = (Object)Marshal.PtrToStringAnsi(ptr); } return(retCode); } // int or double: return problem return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); }
public static string GetUrlContentType(string url, string hostname, int timeout) { Easy easy = new Easy(); Easy.SetCurrentEasy(easy); Slist headers = new Slist(); headers.Append(HobaText.Format("Host: {0}", hostname)); easy.SetOpt(CURLoption.CURLOPT_URL, url); easy.SetOpt(CURLoption.CURLOPT_HEADER, 1L); easy.SetOpt(CURLoption.CURLOPT_NOBODY, 1L); easy.SetOpt(CURLoption.CURLOPT_HTTPHEADER, headers); //easy.SetOpt(CURLoption.CURLOPT_IPRESOLVE, (long)CURLipResolve.CURL_IPRESOLVE_V4); easy.SetOpt(CURLoption.CURLOPT_CONNECTTIMEOUT, timeout / 1000); easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, 0L); easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYHOST, 0L); int error = 0; string contentType = ""; if (easy.Perform() == CURLcode.CURLE_OK) { CURLcode code = easy.GetInfo(CURLINFO.CURLINFO_RESPONSE_CODE, ref error); if (code == CURLcode.CURLE_OK && error == 200) { easy.GetInfo(CURLINFO.CURLINFO_CONTENT_TYPE, ref contentType); } } headers.FreeAll(); Easy.SetCurrentEasy(null); easy.Cleanup(); return(contentType); }
public static void PerformPostMultipartRequest(string query, string postData) { Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL); Easy easy = new Easy(); Easy.WriteFunction wf = new Easy.WriteFunction(OnWriteData); easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf); // simple post - with a string easy.SetOpt(CURLoption.CURLOPT_POSTFIELDS, postData); easy.SetOpt(CURLoption.CURLOPT_USERAGENT, "C# EchoNest Lib"); easy.SetOpt(CURLoption.CURLOPT_FOLLOWLOCATION, true); easy.SetOpt(CURLoption.CURLOPT_URL, query); easy.SetOpt(CURLoption.CURLOPT_POST, true); CURLcode res = easy.Perform(); if (res != CURLcode.CURLE_OK) { throw new WebException("Post operation failed"); } easy.Cleanup(); Curl.GlobalCleanup(); }
/// <summary> /// Extract <c>Slist</c> information from an <c>Easy</c> object. /// </summary> /// <param name="info">One of the values in the /// <see cref="CURLINFO"/> enumeration. In this case, it must /// specifically be one of the members that obtains an <c>Slist</c>. /// </param> /// <param name="slist">Reference to an <c>Slist</c> value.</param> /// <returns>The <see cref="CURLcode"/> obtained from the internal /// call to <c>curl_easy_getinfo()</c>. /// </returns> /// <exception cref="System.NullReferenceException">This is thrown if /// the native <c>CURL*</c> handle wasn't created successfully.</exception> public CURLcode GetInfo(CURLINFO info, ref Slist slist) { EnsureHandle(); CURLcode retCode = CURLcode.CURLE_OK; IntPtr ptr = IntPtr.Zero, ptrs = IntPtr.Zero; if ((int)info < CURLINFO_SLIST) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } retCode = External.curl_easy_getinfo_ptr(m_pCURL, info, ref ptr); if (retCode != CURLcode.CURLE_OK) { return(retCode); } slist = new Slist(); while (ptr != IntPtr.Zero) { ptr = External.curl_shim_get_string_from_slist( ptr, ref ptrs); slist.Append(Marshal.PtrToStringAnsi(ptrs)); } return(retCode); }
internal static extern IntPtr curl_easy_strerror(CURLcode err);
/// <summary> /// Get a string description of an error code. /// </summary> /// <param name="code">Error code.</param> /// <returns>String description of the error code.</returns> public String StrError(CURLcode code) { return Marshal.PtrToStringAnsi( External.curl_easy_strerror(code)); }
public static extern bool MultiInfoRead( SafeCurlMultiHandle multiHandle, out CURLMSG message, out IntPtr easyHandle, out CURLcode result);
/// <summary> /// Set options for this object. See the <c>EasyGet</c> sample for /// basic usage. /// </summary> /// <param name="option">This should be a valid <see cref="CURLoption"/>.</param> /// <param name="parameter">This should be a parameter of a varying /// type based on the value of the <c>option</c> parameter.</param> /// <exception cref="System.NullReferenceException">This is thrown if /// the native <c>CURL*</c> handle wasn't created successfully.</exception> /// <returns>A <see cref="CURLcode"/>, typically obtained from /// <c>cURL</c> internally, but sometimes a /// <see cref="CURLcode.CURLE_BAD_FUNCTION_ARGUMENT"/> /// will be returned if the type of value of <c>parameter</c> is invalid. /// </returns> public CURLcode SetOpt(CURLoption option, Object parameter) { EnsureHandle(); CURLcode retCode = CURLcode.CURLE_OK; // numeric cases if ((int)option < CURLOPTTYPE_OBJECTPOINT) { int i = 0; if (option == CURLoption.CURLOPT_DNS_USE_GLOBAL_CACHE || option == CURLoption.CURLOPT_SOURCE_PORT) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } else if (option == CURLoption.CURLOPT_TIMEVALUE) { // unboxing may throw class cast exception //DateTime d = (DateTime)parameter; DateTime startTime = Main.DateTimeBegin; TimeSpan currTime = new TimeSpan(DateTime.Now.Ticks - startTime.Ticks); i = Convert.ToInt32(currTime.TotalSeconds); } else { i = Convert.ToInt32(parameter); } retCode = External.curl_easy_setopt_int(m_pCURL, option, i); } // object cases: the majority else if ((int)option < CURLOPTTYPE_FUNCTIONPOINT) { switch (option) { // various data items case CURLoption.CURLOPT_PRIVATE: m_privateData = parameter; break; case CURLoption.CURLOPT_WRITEDATA: m_writeData = parameter; break; case CURLoption.CURLOPT_READDATA: m_readData = parameter; break; case CURLoption.CURLOPT_PROGRESSDATA: m_progressData = parameter; break; case CURLoption.CURLOPT_DEBUGDATA: m_debugData = parameter; break; case CURLoption.CURLOPT_HEADERDATA: m_headerData = parameter; break; case CURLoption.CURLOPT_SSL_CTX_DATA: m_sslContextData = parameter; break; case CURLoption.CURLOPT_IOCTLDATA: m_ioctlData = parameter; break; // items that can't be set externally or // obsolete items case CURLoption.CURLOPT_ERRORBUFFER: case CURLoption.CURLOPT_STDERR: case CURLoption.CURLOPT_SOURCE_HOST: case CURLoption.CURLOPT_SOURCE_PATH: case CURLoption.CURLOPT_PASV_HOST: return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); // singular case for share case CURLoption.CURLOPT_SHARE: { Share share = parameter as Share; if (share == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } retCode = External.curl_easy_setopt_ptr(m_pCURL, option, share.GetHandle()); break; } // multipart HTTP post case CURLoption.CURLOPT_HTTPPOST: { MultiPartForm mf = parameter as MultiPartForm; if (mf == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } retCode = External.curl_easy_setopt_ptr(m_pCURL, option, mf.GetHandle()); break; } // items curl wants as a curl_slist case CURLoption.CURLOPT_HTTPHEADER: case CURLoption.CURLOPT_PREQUOTE: case CURLoption.CURLOPT_QUOTE: case CURLoption.CURLOPT_POSTQUOTE: case CURLoption.CURLOPT_SOURCE_QUOTE: case CURLoption.CURLOPT_TELNETOPTIONS: case CURLoption.CURLOPT_HTTP200ALIASES: { Slist slist = parameter as Slist; if (slist == null) { retCode = External.curl_easy_setopt_ptr(m_pCURL, option, IntPtr.Zero); } else { retCode = External.curl_easy_setopt_ptr(m_pCURL, option, slist.GetHandle()); } break; } // string items default: { string s = parameter as string; if (s == null) { retCode = External.curl_easy_setopt_ptr(m_pCURL, option, IntPtr.Zero); } else { IntPtr pCurlStr = External.curl_shim_add_string( m_pMyStrings, s); if (pCurlStr != IntPtr.Zero) { retCode = External.curl_easy_setopt_ptr(m_pCURL, option, pCurlStr); } } break; } } } // FUNCTIONPOINT args, for delegates else if ((int)option < CURLOPTTYPE_OFF_T) { switch (option) { case CURLoption.CURLOPT_WRITEFUNCTION: { WriteFunction wf = parameter as WriteFunction; if (wf == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfWrite = wf; break; } case CURLoption.CURLOPT_READFUNCTION: { ReadFunction rf = parameter as ReadFunction; if (rf == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfRead = rf; break; } case CURLoption.CURLOPT_PROGRESSFUNCTION: { ProgressFunction pf = parameter as ProgressFunction; if (pf == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfProgress = pf; break; } case CURLoption.CURLOPT_DEBUGFUNCTION: { DebugFunction pd = parameter as DebugFunction; if (pd == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfDebug = pd; break; } case CURLoption.CURLOPT_HEADERFUNCTION: { HeaderFunction hf = parameter as HeaderFunction; if (hf == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfHeader = hf; break; } case CURLoption.CURLOPT_SSL_CTX_FUNCTION: { SSLContextFunction sf = parameter as SSLContextFunction; if (sf == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfSSLContext = sf; break; } case CURLoption.CURLOPT_IOCTLFUNCTION: { IoctlFunction iof = parameter as IoctlFunction; if (iof == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfIoctl = iof; break; } default: return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } } // otherwise, it's one of those 64-bit off_t guys! else { Int64 i = Convert.ToInt64(parameter); retCode = External.curl_easy_setopt_int64(m_pCURL, option, i); } return(retCode); }
/// <summary> /// Universal method to load page /// </summary> /// <param name="url">url to load. It is ignored if form is not null.</param> /// <param name="form">form to submit. Should be null if url is not null.</param> /// <param name="send_cookies"></param> /// <returns></returns> CURLcode load_page(string url, bool send_cookies) { try { if (Cache.GetCachedFile(ref url, out WR.HtmlResult, out WR.ResponseUrl)) { WR.web_routine_status = WebRoutineStatus.CACHED; WR.log.Write("From cache: " + url); return(CURLcode.CURLE_OK); } if (UseCommonCookieFile) { copy_common_cookie_file2thread_cookie_file(); } result_ms.Position = 0; result_sb.Length = 0; encode_type = EncodeType.NONE; easy = new Easy(); content_length = -1; WR.ErrorMessage = null; WR.HtmlResult = null; //WR.saved_file = null; WR.log.Write("Downloading:" + url); if (WR.BTC != null) { WR.BTC.BTS.ProgressMax = 0; WR.BTC.BTS.ProgressValue = 100; WR.BTC.BTS.Status = "Sleeping Crawl Interval: " + Config.Web.CrawlTimeIntervalInMss.ToString(); WR.BTC.DisplayStatus(); Thread.Sleep(Config.Web.CrawlTimeIntervalInMss); WR.BTC.BTS.Status = "URL:" + url; WR.BTC.DisplayStatus(); } WR.web_routine_status = WebRoutineStatus.UNDEFINED; //if (flagReceiveDebugMessages) //{ // Easy.DebugFunction df = new Easy.DebugFunction(OnDebug); // easy.SetOpt(CURLoption.CURLOPT_DEBUGFUNCTION, df); // easy.SetOpt(CURLoption.CURLOPT_VERBOSE, true); //} Easy.WriteFunction wf = new Easy.WriteFunction(OnWriteStringBuilder); easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf); easy.SetOpt(CURLoption.CURLOPT_URL, url); if (url.StartsWith("https")) { easy.SetOpt(CURLoption.CURLOPT_CAINFO, "ca-bundle.crt"); } Easy.HeaderFunction hf = new Easy.HeaderFunction(OnHeaderData); easy.SetOpt(CURLoption.CURLOPT_HEADERFUNCTION, hf); Slist sl = new Slist(); sl.Append("Accept: " + WR.HttpRequestAcceptHeader); sl.Append("Referer: " + WR.HttpRequestRefererHeader); sl.Append("Accept-Encoding: gzip, deflate"); easy.SetOpt(CURLoption.CURLOPT_HTTPHEADER, sl); easy.SetOpt(CURLoption.CURLOPT_USERAGENT, Config.Web.HttpUserAgent); easy.SetOpt(CURLoption.CURLOPT_COOKIEJAR, CookieFile); if (send_cookies) { easy.SetOpt(CURLoption.CURLOPT_COOKIEFILE, CookieFile); } if (WR.MaxAutoRedirectionCount >= 0) { easy.SetOpt(CURLoption.CURLOPT_MAXREDIRS, WR.MaxAutoRedirectionCount); } //Easy.ProgressFunction pf = new Easy.ProgressFunction(OnProgress); //easy.SetOpt(CURLoption.CURLOPT_PROGRESSDATA, ); easy.SetOpt(CURLoption.CURLOPT_FOLLOWLOCATION, true); if (proxy != null) { easy.SetOpt(CURLoption.CURLOPT_PROXY, proxy.Ip); easy.SetOpt(CURLoption.CURLOPT_PROXYPORT, proxy.Port); easy.SetOpt(CURLoption.CURLOPT_PROXYAUTH, CURLhttpAuth.CURLAUTH_ANY); if (proxy.Login != "" || proxy.Password != "") { easy.SetOpt(CURLoption.CURLOPT_PROXYUSERPWD, proxy.Login + ":" + proxy.Password); } if (proxy.Type == ProxyType.SOCKS5) { easy.SetOpt(CURLoption.CURLOPT_PROXYTYPE, CURLproxyType.CURLPROXY_SOCKS5); } else if (proxy.Type == ProxyType.SOCKS4) { easy.SetOpt(CURLoption.CURLOPT_PROXYTYPE, CURLproxyType.CURLPROXY_SOCKS4); } else { easy.SetOpt(CURLoption.CURLOPT_PROXYTYPE, CURLproxyType.CURLPROXY_HTTP); } easy.SetOpt(CURLoption.CURLOPT_PROXYAUTH, CURLhttpAuth.CURLAUTH_ANY); } if (WR.BTC != null) { if (proxy != null) { WR.BTC.BTS.Proxy = proxy.Ip + ":" + proxy.Port; } else { WR.BTC.BTS.Proxy = "NOT USED"; } WR.BTC.DisplayStatus(); } easy.SetOpt(CURLoption.CURLOPT_TIMEOUT, Config.Web.HttpRequestTimeoutInSeconds); CURLcode rc = easy.Perform(); easy.GetInfo(CURLINFO.CURLINFO_EFFECTIVE_URL, ref WR.ResponseUrl); easy.Cleanup(); WR.HtmlResult = result_sb.ToString(); if (rc != CURLcode.CURLE_OK) { WR.ErrorMessage = easy.StrError(rc); WR.web_routine_status = WebRoutineStatus.DOWNLOAD_ERROR; WR.log.Error("Download error: " + WR.ErrorMessage + "\nURL:" + url + "\nPROXY: " + proxy.Ip + ":" + proxy.Port); return(rc); } if (UseCommonCookieFile) { copy_thread_cookie_file2common_cookie_file(); } if (WR.web_routine_status == WebRoutineStatus.UNDEFINED) { WR.web_routine_status = WebRoutineStatus.OK; } WR.log.CacheDownloadedString(ref url, ref WR.ResponseUrl, ref WR.HtmlResult, WR.page_number++, WR.CycleIdentifier); return(rc); } catch (ThreadAbortException) { } catch (Exception error) { WR.web_routine_status = WebRoutineStatus.EXCEPTION; WR.log.Error(error.Message + "\nURL: " + url + "\nPROXY: " + proxy.Ip + ":" + proxy.Port); if (easy != null) { easy.Cleanup(); } } return(CURLcode.CURLE_FAILED_INIT); }
/// <summary> /// Execute is modified Curl_http() which in Curl gets called from the generic Curl_do() function when a HTTP /// request is to be performed. This creates and sends a properly constructed /// HTTP request. /// </summary> /// <param name="curl"></param> /// <param name="result"></param> /// <returns></returns> internal override object Execute(PhpCurlResource curl, ref CURLcode result) { UserDefined data = curl.Data; HttpBitsUploader uploader; bool terminatedCorrectly = false; int redirectAttempts = 0; bool keepVerb = false; result = CURLcode.CURLE_OK; if (data.Str[(int)DupString.SET_URL] == null) { result = CURLcode.CURLE_COULDNT_CONNECT; return(false); } Uri uri = Utils.CompleteUri(PhpVariable.AsString(data.Str[(int)DupString.SET_URL]), Scheme, data.UsePort); for (; ;) { request = (HttpWebRequest)HttpWebRequest.Create(uri); Curl_HttpReq httpreq = (redirectAttempts == 0) || keepVerb?setRequestMethod(data) : Curl_HttpReq.GET; setTimeOut(data); setHttpVersion(data); request.AllowAutoRedirect = data.FollowLocation; request.MaximumAutomaticRedirections = data.MaxRedirects; if (data.Str[(int)DupString.USERAGENT] != null) { request.UserAgent = PhpVariable.AsString(data.Str[(int)DupString.USERAGENT]); } if (data.Str[(int)DupString.SET_REFERER] != null) { request.Referer = PhpVariable.AsString(data.Str[(int)DupString.SET_REFERER]); } if (data.Headers != null) { request.SetHttpHeaders(data.Headers); } setProxy(data); setCredentials(data); setCookies(data); //ssl.VerifyPeer && ssl.VerifyHost == 2 is supported by default .NET // other values are currently unsupported if (data.Str[(int)DupString.CERT] != null) { X509Certificate cert; string certPath; try { certPath = Path.Combine(ScriptContext.CurrentContext.WorkingDirectory, PhpVariable.AsString(data.Str[(int)DupString.SSL_CAFILE])); if (data.Str[(int)DupString.KEY_PASSWD] == null) { cert = new X509Certificate(certPath); } else { cert = new X509Certificate(certPath, PhpVariable.AsString(data.Str[(int)DupString.KEY_PASSWD])); } request.ClientCertificates.Add(cert); } catch (CryptographicException) { //TODO: here are more caises to differentiate result = CURLcode.CURLE_SSL_CACERT_BADFILE; return(false); } } switch (httpreq) { case Curl_HttpReq.POST_FORM: //same as POST but we can send multiple items asform-data if (data.HttpPostForm != null) { try { HttpFormDataUploader formUploader = new HttpFormDataUploader(request); formUploader.UploadForm(data.HttpPostForm); } catch (WebException ex) { switch (ex.Status) { case WebExceptionStatus.Timeout: result = CURLcode.CURLE_OPERATION_TIMEOUTED; break; default: result = CURLcode.CURLE_COULDNT_CONNECT; // for now just this break; } return(false); } } break; case Curl_HttpReq.PUT: /* Let's PUT the data to the server! */ //INFILE & INFILESIZE has to be set NativeStream nativeStream = data.Infile as NativeStream; if (nativeStream == null) { return(false); } FileStream fs = nativeStream.RawStream as FileStream; if (fs == null) { return(false); } try { uploader = new HttpBitsUploader(request); uploader.UploadFile(fs); } catch (WebException ex) { switch (ex.Status) { case WebExceptionStatus.Timeout: result = CURLcode.CURLE_OPERATION_TIMEOUTED; break; default: result = CURLcode.CURLE_COULDNT_CONNECT; // for now just this break; } return(false); } break; case Curl_HttpReq.POST: /* this is the simple POST, using x-www-form-urlencoded style */ if (String.IsNullOrEmpty(request.ContentType)) // if Content-type isn't set set the default { request.ContentType = "application/x-www-form-urlencoded"; } if (data.Postfields != null) { try { uploader = new HttpBitsUploader(request); uploader.UploadData(data.Postfields); } catch (WebException ex) { switch (ex.Status) { case WebExceptionStatus.Timeout: result = CURLcode.CURLE_OPERATION_TIMEOUTED; break; default: result = CURLcode.CURLE_COULDNT_CONNECT; // for now just this break; } return(false); } } break; } try { // if we got this far, we will turn off AutoRedirect (assuming it was on), since // we are ready to handle manually following certain responses. this is needed // to harvest cookies that are set on any intermediate response (i.e. anything // other than the last one followed), since the .NET HTTP class will use, but // NOT return, cookies set on anything but the last request. request.AllowAutoRedirect = false; response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { switch (ex.Status) { case WebExceptionStatus.Timeout: result = CURLcode.CURLE_OPERATION_TIMEOUTED; break; case WebExceptionStatus.ConnectFailure: result = CURLcode.CURLE_COULDNT_CONNECT; break; case WebExceptionStatus.TrustFailure: result = CURLcode.CURLE_SSL_CACERT; break; case WebExceptionStatus.ProtocolError: //Response from server was complete, but indicated protocol error as 404, 401 etc. break; default: result = CURLcode.CURLE_COULDNT_CONNECT; // for now just this break; } //TODO: other errorCodes response = (HttpWebResponse)ex.Response; //return false; //error = true; } if (response == null)// just to make sure I have the response object { return(false); } if (data.FollowLocation) { // see if we need to follow a redirect. switch (response.StatusCode) { case HttpStatusCode.MovedPermanently: case HttpStatusCode.Found: case HttpStatusCode.SeeOther: case HttpStatusCode.RedirectKeepVerb: if (redirectAttempts++ >= data.MaxRedirects) { result = CURLcode.CURLE_TOO_MANY_REDIRECTS; return(false); } string location = response.Headers["Location"]; if (!string.IsNullOrWhiteSpace(location)) { try { keepVerb = response.StatusCode == HttpStatusCode.RedirectKeepVerb; data.Cookies.Add(response.Cookies); response.Close(); uri = new Uri(uri, location); continue; } catch (Exception) { // closest error code though could be confusing as it's not the user- // submitted URL that's the problem result = CURLcode.CURLE_URL_MALFORMAT; return(false); } } break; } } //Save cookies data.Cookies.Add(response.Cookies); // break out of the for loop as we aren't following a redirect break; } byte[] headers = null; byte[] content = null; int headersLength = 0; if (data.IncludeHeader) { //It's necessary to put HTTP header into the result //first we need to create it since there isn't anywhere headers = Encoding.ASCII.GetBytes(response.GetHttpHeaderAsString()); headersLength = headers.Length; } if (data.FunctionWriteHeader != null)// TODO: probably invoke before { response.InvokeHeaderFunction(curl, data.FunctionWriteHeader); } Stream writeStream = null; if (data.WriteFunction != null) { writeStream = new WriteFunctionStream(curl, data.WriteFunction); } else if (data.OutFile != null) { var outStream = data.OutFile as PhpStream; if (outStream == null) { return(false); } Stream fs = outStream.RawStream as Stream; if (fs == null) { return(false); } writeStream = fs; } else if (data.ReturnTransfer == false) // Output to standart output { writeStream = ScriptContext.CurrentContext.OutputStream; } if (writeStream != null) { if (headers != null) //there is http header to copy to the result { writeStream.Write(headers, 0, headersLength); } HttpBitsDownloader reader = new HttpBitsDownloader(response); try { reader.ReadToStream(writeStream, out terminatedCorrectly); } catch (WebException ex) { switch (ex.Status) { case WebExceptionStatus.Timeout: result = CURLcode.CURLE_OPERATION_TIMEOUTED; break; default: result = CURLcode.CURLE_COULDNT_CONNECT; // for now just this break; } } if (!terminatedCorrectly) { result = CURLcode.CURLE_PARTIAL_FILE; } return(true); } else { // Read the response HttpBitsDownloader reader = new HttpBitsDownloader(response); try { content = reader.ReadToEnd(headersLength, out terminatedCorrectly); } catch (WebException ex) { switch (ex.Status) { case WebExceptionStatus.Timeout: result = CURLcode.CURLE_OPERATION_TIMEOUTED; break; default: result = CURLcode.CURLE_COULDNT_CONNECT; // for now just this break; } } if (!terminatedCorrectly) { result = CURLcode.CURLE_PARTIAL_FILE; } if (headers != null) //there is http header to copy to the result { if (content != null) { Buffer.BlockCopy(headers, 0, content, 0, headersLength); } else { content = headers; } } if (content == null) { return(PhpBytes.Empty); } else { return(new PhpBytes(content)); } } }
public static bool gopost(string url, string user, string password, string data, TradeLink.API.DebugDelegate deb, out string result) { debs = deb; Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL); Easy easy = new Easy(); rresult = new StringBuilder(); hasresult = false; Easy.WriteFunction wf = new Easy.WriteFunction(OnWritePostData); easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf); Easy.DebugFunction df = new Easy.DebugFunction(OnDebug); easy.SetOpt(CURLoption.CURLOPT_DEBUGFUNCTION, df); // simple post - with a string easy.SetOpt(CURLoption.CURLOPT_POSTFIELDS, data); Slist sl = new Slist(); sl.Append("Content-Type:application/xml"); sl.Append("Accept: application/xml"); easy.SetOpt(CURLoption.CURLOPT_HTTPHEADER, sl); easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, false); easy.SetOpt(CURLoption.CURLOPT_USERAGENT, "Mozilla 4.0 (compatible; MSIE 6.0; Win32"); easy.SetOpt(CURLoption.CURLOPT_FOLLOWLOCATION, true); easy.SetOpt(CURLoption.CURLOPT_USERPWD, user + ":" + password); CURLhttpAuth authflag = CURLhttpAuth.CURLAUTH_BASIC; easy.SetOpt(CURLoption.CURLOPT_HTTPAUTH, authflag); easy.SetOpt(CURLoption.CURLOPT_URL, url); easy.SetOpt(CURLoption.CURLOPT_POST, true); if (debs != null) { easy.SetOpt(CURLoption.CURLOPT_VERBOSE, true); } CURLcode err = easy.Perform(); int waits = 0; int maxwaits = 200; while (!hasresult && (waits++ < maxwaits)) { System.Threading.Thread.Sleep(10); } int rcodei = 0; CURLcode rcode = easy.GetInfo(CURLINFO.CURLINFO_RESPONSE_CODE, ref rcodei); if (!hasresult && (deb != null)) { deb(easy.StrError(err)); } easy.Cleanup(); Curl.GlobalCleanup(); result = rresult.ToString(); return(hasresult); }
/// <summary> /// Class constructor - initialize global status. /// </summary> static Curl() { sm_curlCode = CURLcode.CURLE_FAILED_INIT; }
private void btn_Post_Click(object sender, EventArgs e) { IntPtr m_pCURL = External.curl_easy_init(); CURLcode retCode = CURLcode.CURLE_OK; retCode = External.curl_easy_setopt(m_pCURL, CURLoption.CURLOPT_URL, Marshal.StringToCoTaskMemAnsi("https://account.storepos.cn/UnifiedPay/Mch_Reg")); retCode = External.curl_easy_setopt(m_pCURL, CURLoption.CURLOPT_POSTFIELDS, Marshal.StringToCoTaskMemAnsi($"a={Uri.EscapeDataString("我是中文")}&b={Uri.EscapeDataString("i am English")}")); retCode = External.curl_easy_setopt(m_pCURL, CURLoption.CURLOPT_USERAGENT, Marshal.StringToCoTaskMemAnsi("我是尹自强的工具")); retCode = External.curl_easy_setopt(m_pCURL, CURLoption.CURLOPT_SSL_VERIFYHOST, (IntPtr)0); retCode = External.curl_easy_setopt(m_pCURL, CURLoption.CURLOPT_SSL_VERIFYPEER, (IntPtr)0); CURLcode res = External.curl_easy_perform(m_pCURL); if (res != CURLcode.CURLE_OK) { // Error } this.txt_Result.AppendText(res.ToString()); this.txt_Result.AppendText(Environment.NewLine); External.curl_easy_cleanup(m_pCURL); return; //try //{ // using (var pro = new Process()) // { // var str_form = $"a={Uri.EscapeDataString("我是中文")}&b={Uri.EscapeDataString("i am English")}"; // var str_cmd = $"-H \"Content-Type:application/x-www-form-urlencoded;charset=UTF-8\" --user-agent \"YZQ.curl\" --data \"{str_form}\" https://account.storepos.cn/UnifiedPay/Mch_Reg"; // pro.StartInfo.FileName = Path.Combine(Environment.CurrentDirectory, "Lib\\curl.exe"); // pro.StartInfo.UseShellExecute = false; // pro.StartInfo.RedirectStandardInput = true; // pro.StartInfo.RedirectStandardOutput = true; // pro.StartInfo.RedirectStandardError = true; // pro.StartInfo.CreateNoWindow = true; // pro.StartInfo.Arguments = str_cmd; // //pro.StartInfo.StandardInputEncoding = Encoding.UTF8; // pro.StartInfo.StandardOutputEncoding = Encoding.UTF8; // pro.Start(); // pro.StandardInput.AutoFlush = true; // //获取cmd窗口的输出信息 // var output = pro.StandardOutput.ReadToEnd(); // pro.WaitForExit(); // pro.Close(); // this.AppendResult(string.Format("【FormData】:{0}", str_form)); // this.AppendResult(string.Format("【Arguments】:{0}", str_cmd)); // this.AppendResult(string.Format("【Response】:{0}", output)); // } //} //catch (Exception ex) //{ // Console.WriteLine(ex.Message); //} }
public MainForm() { InitializeComponent(); sm_curlCode = Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL); }
//public static CURLcode GlobalInit(int flags) static Curl() { sm_curlCode = curl_global_init((int)CURLinitFlag.CURL_GLOBAL_ALL); }
public HandleCompletedAction OnComplete(SafeEasyHandle easy, MyRequestContext context, CURLcode errorCode) { Console.WriteLine($"Request label: {context.Label}."); if (errorCode != CURLcode.OK) { Console.BackgroundColor = ConsoleColor.DarkRed; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"cURL error code: {errorCode}"); var pErrorMsg = CurlNative.Easy.StrError(errorCode); var errorMsg = Marshal.PtrToStringAnsi(pErrorMsg); Console.WriteLine($"cURL error message: {errorMsg}"); Console.ResetColor(); Console.WriteLine("--------"); Console.WriteLine(); context.Dispose(); return(HandleCompletedAction.ResetHandleAndNext); } // Get HTTP response code. CurlNative.Easy.GetInfo(easy, CURLINFO.RESPONSE_CODE, out int httpCode); if (httpCode != 200) { Console.BackgroundColor = ConsoleColor.DarkRed; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"Invalid HTTP response code: {httpCode}"); Console.ResetColor(); Console.WriteLine("--------"); Console.WriteLine(); context.Dispose(); return(HandleCompletedAction.ResetHandleAndNext); } Console.WriteLine($"Response code: {httpCode}"); // Get effective URL. IntPtr pDoneUrl; CurlNative.Easy.GetInfo(easy, CURLINFO.EFFECTIVE_URL, out pDoneUrl); var doneUrl = Marshal.PtrToStringAnsi(pDoneUrl); Console.WriteLine($"Effective URL: {doneUrl}"); // Get response body as string. string html; context.ContentStream.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(context.ContentStream)) { html = reader.ReadToEnd(); } // Scrape question from HTML source. var match = Regex.Match(html, "<title>(.+?)<\\/"); Console.WriteLine($"Question: {match.Groups[1].Value.Trim()}"); Console.WriteLine("--------"); Console.WriteLine(); context.Dispose(); return(HandleCompletedAction.ResetHandleAndNext); }
/// <summary> /// Execute is modified Curl_http() which in Curl gets called from the generic Curl_do() function when a HTTP /// request is to be performed. This creates and sends a properly constructed /// HTTP request. /// </summary> /// <param name="curl"></param> /// <param name="result"></param> /// <returns></returns> internal override object Execute(PhpCurlResource curl, ref CURLcode result) { UserDefined data = curl.Data; HttpBitsUploader uploader; bool terminatedCorrectly = false; int redirectAttempts = 0; bool keepVerb = false; result = CURLcode.CURLE_OK; if (data.Str[(int)DupString.SET_URL] == null) { result = CURLcode.CURLE_COULDNT_CONNECT; return false; } Uri uri = Utils.CompleteUri(PhpVariable.AsString(data.Str[(int)DupString.SET_URL]), Scheme, data.UsePort); for (; ; ) { request = (HttpWebRequest)HttpWebRequest.Create(uri); Curl_HttpReq httpreq = (redirectAttempts == 0) || keepVerb ? setRequestMethod(data) : Curl_HttpReq.GET; setTimeOut(data); setHttpVersion(data); request.AllowAutoRedirect = data.FollowLocation; request.MaximumAutomaticRedirections = data.MaxRedirects; if (data.Str[(int)DupString.USERAGENT] != null) request.UserAgent = PhpVariable.AsString(data.Str[(int)DupString.USERAGENT]); if (data.Str[(int)DupString.SET_REFERER] != null) request.Referer = PhpVariable.AsString(data.Str[(int)DupString.SET_REFERER]); if (data.Headers != null) request.SetHttpHeaders(data.Headers); setProxy(data); setCredentials(data); setCookies(data); //ssl.VerifyPeer && ssl.VerifyHost == 2 is supported by default .NET // other values are currently unsupported if (data.Str[(int)DupString.CERT] != null) { X509Certificate cert; string certPath; try { certPath = Path.Combine(ScriptContext.CurrentContext.WorkingDirectory, PhpVariable.AsString(data.Str[(int)DupString.SSL_CAFILE])); if (data.Str[(int)DupString.KEY_PASSWD] == null) cert = new X509Certificate(certPath); else cert = new X509Certificate(certPath, PhpVariable.AsString(data.Str[(int)DupString.KEY_PASSWD])); request.ClientCertificates.Add(cert); } catch (CryptographicException) { //TODO: here are more caises to differentiate result = CURLcode.CURLE_SSL_CACERT_BADFILE; return false; } } switch (httpreq) { case Curl_HttpReq.POST_FORM: //same as POST but we can send multiple items asform-data if (data.HttpPostForm != null) { try { HttpFormDataUploader formUploader = new HttpFormDataUploader(request); formUploader.UploadForm(data.HttpPostForm); } catch (WebException ex) { switch (ex.Status) { case WebExceptionStatus.Timeout: result = CURLcode.CURLE_OPERATION_TIMEOUTED; break; default: result = CURLcode.CURLE_COULDNT_CONNECT;// for now just this break; } return false; } } break; case Curl_HttpReq.PUT: /* Let's PUT the data to the server! */ //INFILE & INFILESIZE has to be set NativeStream nativeStream = data.Infile as NativeStream; if (nativeStream == null) return false; FileStream fs = nativeStream.RawStream as FileStream; if (fs == null) return false; try { uploader = new HttpBitsUploader(request); uploader.UploadFile(fs); } catch (WebException ex) { switch (ex.Status) { case WebExceptionStatus.Timeout: result = CURLcode.CURLE_OPERATION_TIMEOUTED; break; default: result = CURLcode.CURLE_COULDNT_CONNECT;// for now just this break; } return false; } break; case Curl_HttpReq.POST: /* this is the simple POST, using x-www-form-urlencoded style */ if (String.IsNullOrEmpty(request.ContentType))// if Content-type isn't set set the default request.ContentType = "application/x-www-form-urlencoded"; if (data.Postfields != null) { try { uploader = new HttpBitsUploader(request); uploader.UploadData(data.Postfields); } catch (WebException ex) { switch (ex.Status) { case WebExceptionStatus.Timeout: result = CURLcode.CURLE_OPERATION_TIMEOUTED; break; default: result = CURLcode.CURLE_COULDNT_CONNECT;// for now just this break; } return false; } } break; } try { // if we got this far, we will turn off AutoRedirect (assuming it was on), since // we are ready to handle manually following certain responses. this is needed // to harvest cookies that are set on any intermediate response (i.e. anything // other than the last one followed), since the .NET HTTP class will use, but // NOT return, cookies set on anything but the last request. request.AllowAutoRedirect = false; response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { switch (ex.Status) { case WebExceptionStatus.Timeout: result = CURLcode.CURLE_OPERATION_TIMEOUTED; break; case WebExceptionStatus.ConnectFailure: result = CURLcode.CURLE_COULDNT_CONNECT; break; case WebExceptionStatus.TrustFailure: result = CURLcode.CURLE_SSL_CACERT; break; case WebExceptionStatus.ProtocolError: //Response from server was complete, but indicated protocol error as 404, 401 etc. break; default: result = CURLcode.CURLE_COULDNT_CONNECT;// for now just this break; } //TODO: other errorCodes response = (HttpWebResponse)ex.Response; //return false; //error = true; } if (response == null)// just to make sure I have the response object return false; if (data.FollowLocation) { // see if we need to follow a redirect. switch (response.StatusCode) { case HttpStatusCode.MovedPermanently: case HttpStatusCode.Found: case HttpStatusCode.SeeOther: case HttpStatusCode.RedirectKeepVerb: if (redirectAttempts++ >= data.MaxRedirects) { result = CURLcode.CURLE_TOO_MANY_REDIRECTS; return false; } string location = response.Headers["Location"]; if (!string.IsNullOrWhiteSpace(location)) { try { keepVerb = response.StatusCode == HttpStatusCode.RedirectKeepVerb; data.Cookies.Add(response.Cookies); response.Close(); uri = new Uri(uri, location); continue; } catch (Exception) { // closest error code though could be confusing as it's not the user- // submitted URL that's the problem result = CURLcode.CURLE_URL_MALFORMAT; return false; } } break; } } //Save cookies data.Cookies.Add(response.Cookies); // break out of the for loop as we aren't following a redirect break; } byte[] headers = null; byte[] content = null; int headersLength = 0; if (data.IncludeHeader) { //It's necessary to put HTTP header into the result //first we need to create it since there isn't anywhere headers = Encoding.ASCII.GetBytes(response.GetHttpHeaderAsString()); headersLength = headers.Length; } if (data.FunctionWriteHeader != null)// TODO: probably invoke before { response.InvokeHeaderFunction(curl, data.FunctionWriteHeader); } Stream writeStream = null; if (data.WriteFunction != null) { writeStream = new WriteFunctionStream(curl, data.WriteFunction); } else if (data.OutFile != null) { var outStream = data.OutFile as PhpStream; if (outStream == null) return false; Stream fs = outStream.RawStream as Stream; if (fs == null) return false; writeStream = fs; } else if (data.ReturnTransfer == false) // Output to standart output { writeStream = ScriptContext.CurrentContext.OutputStream; } if (writeStream != null) { if (headers != null) //there is http header to copy to the result { writeStream.Write(headers, 0, headersLength); } HttpBitsDownloader reader = new HttpBitsDownloader(response); try { reader.ReadToStream(writeStream, out terminatedCorrectly); } catch (WebException ex) { switch (ex.Status) { case WebExceptionStatus.Timeout: result = CURLcode.CURLE_OPERATION_TIMEOUTED; break; default: result = CURLcode.CURLE_COULDNT_CONNECT;// for now just this break; } } if (!terminatedCorrectly) result = CURLcode.CURLE_PARTIAL_FILE; return true; } else { // Read the response HttpBitsDownloader reader = new HttpBitsDownloader(response); try { content = reader.ReadToEnd(headersLength, out terminatedCorrectly); } catch(WebException ex) { switch (ex.Status) { case WebExceptionStatus.Timeout: result = CURLcode.CURLE_OPERATION_TIMEOUTED; break; default: result = CURLcode.CURLE_COULDNT_CONNECT;// for now just this break; } } if (!terminatedCorrectly) result = CURLcode.CURLE_PARTIAL_FILE; if (headers != null) //there is http header to copy to the result { if (content != null) Buffer.BlockCopy(headers, 0, content, 0, headersLength); else content = headers; } if (content == null) return PhpBytes.Empty; else return new PhpBytes(content); } }
/// <summary> /// Get the curl error /// </summary> /// <param name="code"></param> /// <returns></returns> public string GetError(CURLcode code) { IntPtr ptr = curl_easy_strerror(code); return Marshal.PtrToStringAnsi(ptr); }
public long GetFileSize(string url, string hostName, int timeout, ref string modifiedTimeGMT) { long size = -1; modifiedTimeGMT = ""; Easy easy = new Easy(); Easy.SetCurrentEasy(easy); Slist headers = new Slist(); CURLcode curlCode = CURLcode.CURLE_OK; try { headers.Append(HobaText.Format("Host: {0}", hostName)); easy.SetOpt(CURLoption.CURLOPT_URL, url); easy.SetOpt(CURLoption.CURLOPT_FILETIME, 1L); easy.SetOpt(CURLoption.CURLOPT_HEADER, 1L); easy.SetOpt(CURLoption.CURLOPT_NOBODY, 1L); easy.SetOpt(CURLoption.CURLOPT_HTTPHEADER, headers); easy.SetOpt(CURLoption.CURLOPT_CONNECTTIMEOUT, timeout / 1000); easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, 0L); easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYHOST, 0L); int error = 0; double downloadFileLength = -1.0f; curlCode = easy.Perform(); if (curlCode == CURLcode.CURLE_OK) { CURLcode code = easy.GetInfo(CURLINFO.CURLINFO_RESPONSE_CODE, ref error); if (code == CURLcode.CURLE_OK && error == 200) { easy.GetInfo(CURLINFO.CURLINFO_CONTENT_LENGTH_DOWNLOAD, ref downloadFileLength); DateTime time = new DateTime(); code = easy.GetInfo(CURLINFO.CURLINFO_FILETIME, ref time); if (code == CURLcode.CURLE_OK) { modifiedTimeGMT = time.ToUniversalTime().ToString("R"); } } if (downloadFileLength >= 0.0f) { size = (int)downloadFileLength; } } else { size = -1; } } finally { headers.FreeAll(); Easy.SetCurrentEasy(null); easy.Cleanup(); } if (curlCode != CURLcode.CURLE_OK) { throw new ArgumentException(String.Format( "Error downloading \"{0}\": {1}", url, curlCode)); } return(size); }
public static extern IntPtr StrError(CURLcode errornum);
public bool DoDownload(string url, string hostname, string destFileName, int timeout, long bufferSize, WRITE_DATA_DELEGATE onWriteData, Object extraData) { bool ret = false; Easy easy = new Easy(); Easy.SetCurrentEasy(easy); Slist headers = new Slist(); Easy.WriteFunction wf = new Easy.WriteFunction(onWriteData); CURLcode curlCode = CURLcode.CURLE_OK; try { headers.Append(HobaText.Format("Host: {0}", hostname)); easy.SetOpt(CURLoption.CURLOPT_URL, url); easy.SetOpt(CURLoption.CURLOPT_WRITEDATA, extraData); easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf); easy.SetOpt(CURLoption.CURLOPT_HEADER, 0L); easy.SetOpt(CURLoption.CURLOPT_VERBOSE, 0L); easy.SetOpt(CURLoption.CURLOPT_BUFFERSIZE, (long)bufferSize); easy.SetOpt(CURLoption.CURLOPT_HTTPHEADER, headers); //easy.SetOpt(CURLoption.CURLOPT_IPRESOLVE, (long)CURLipResolve.CURL_IPRESOLVE_V4); easy.SetOpt(CURLoption.CURLOPT_CONNECTTIMEOUT, timeout / 1000); // easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, 0L); easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYHOST, 0L); if (StartPoint > 0) { easy.SetOpt(CURLoption.CURLOPT_RESUME_FROM, StartPoint); } int error = 0; curlCode = easy.Perform(); if (curlCode == CURLcode.CURLE_OK) { CURLcode code = easy.GetInfo(CURLINFO.CURLINFO_RESPONSE_CODE, ref error); if (code == CURLcode.CURLE_OK && error == 200) { ret = true; } } } finally { headers.FreeAll(); Easy.SetCurrentEasy(null); easy.Cleanup(); } if (curlCode != CURLcode.CURLE_OK) { throw new WebException(String.Format( "Error downloading \"{0}\": {1}", url, curlCode)); } return(ret); }
/// <summary> /// Get a string description of an error code. /// </summary> /// <param name="code">Error code.</param> /// <returns>String description of the error code.</returns> public String StrError(CURLcode code) { return(Marshal.PtrToStringAnsi( External.curl_easy_strerror(code))); }
public CurlException(CURLcode code) : base(code.ToString()) { }
public static bool gomultipartpost(string url, string user, string password, string fname, string fpath, int ticketid, int maxwaitsec, bool showprogress, TradeLink.API.DebugDelegate deb, out string result) { debs = deb; Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL); Easy easy = new Easy(); rresult = new StringBuilder(); hasresult = false; MultiPartForm mf = new MultiPartForm(); // <input name="frmFileOrigPath"> mf.AddSection(CURLformoption.CURLFORM_COPYNAME, "document[name]", CURLformoption.CURLFORM_COPYCONTENTS, fname, CURLformoption.CURLFORM_END); // <input type="File" name="f1"> mf.AddSection(CURLformoption.CURLFORM_COPYNAME, "document[file]", CURLformoption.CURLFORM_FILE, fpath, CURLformoption.CURLFORM_CONTENTTYPE, "application/octet-stream", CURLformoption.CURLFORM_END); // <input name="frmFileDate"> if (ticketid != 0) { mf.AddSection(CURLformoption.CURLFORM_COPYNAME, "document[ticket_id]", CURLformoption.CURLFORM_COPYCONTENTS, ticketid.ToString(), CURLformoption.CURLFORM_END); } if (showprogress) { Easy.ProgressFunction pf = new Easy.ProgressFunction(OnProgress); easy.SetOpt(CURLoption.CURLOPT_PROGRESSFUNCTION, pf); } Easy.WriteFunction wf = new Easy.WriteFunction(OnWritePostData); easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf); easy.SetOpt(CURLoption.CURLOPT_HTTPPOST, mf); Easy.DebugFunction df = new Easy.DebugFunction(OnDebug); easy.SetOpt(CURLoption.CURLOPT_DEBUGFUNCTION, df); // simple post - with a string //easy.SetOpt(CURLoption.CURLOPT_POSTFIELDS,data); Slist sl = new Slist(); //sl.Append("Content-Type:multipart/form-data"); sl.Append("Accept: application/xml"); easy.SetOpt(CURLoption.CURLOPT_HTTPHEADER, sl); easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, false); easy.SetOpt(CURLoption.CURLOPT_USERAGENT, "Mozilla 4.0 (compatible; MSIE 6.0; Win32"); easy.SetOpt(CURLoption.CURLOPT_FOLLOWLOCATION, true); easy.SetOpt(CURLoption.CURLOPT_USERPWD, user + ":" + password); CURLhttpAuth authflag = CURLhttpAuth.CURLAUTH_BASIC; easy.SetOpt(CURLoption.CURLOPT_HTTPAUTH, authflag); easy.SetOpt(CURLoption.CURLOPT_URL, url); //easy.SetOpt(CURLoption.CURLOPT_POST, true); if (debs != null) { easy.SetOpt(CURLoption.CURLOPT_VERBOSE, true); } CURLcode err = easy.Perform(); int waits = 0; int maxwaits = 100 * maxwaitsec; while (!hasresult && (waits++ < maxwaits)) { System.Threading.Thread.Sleep(10); } int rcodei = 0; CURLcode rcode = easy.GetInfo(CURLINFO.CURLINFO_RESPONSE_CODE, ref rcodei); if (!hasresult && (deb != null)) { deb(easy.StrError(err)); } easy.Cleanup(); mf.Free(); Curl.GlobalCleanup(); result = rresult.ToString(); return(hasresult && (rcodei == 201)); }
internal MultiInfo(CURLMSG msg, Easy easy, CURLcode result) { m_msg = msg; m_easy = easy; m_result = result; }
internal abstract object Execute(PhpCurlResource curl, ref CURLcode result);