Http.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Http.h"
  5. #include "NeonIntf.h"
  6. #include "Exceptions.h"
  7. #include "ne_request.h"
  8. #include "TextsCore.h"
  9. #include <openssl/ssl.h>
  10. //---------------------------------------------------------------------------
  11. THttp::THttp()
  12. {
  13. FProxyPort = 0;
  14. FOnDownload = NULL;
  15. FResponseLimit = -1;
  16. FRequestHeaders = NULL;
  17. FResponseHeaders = new TStringList();
  18. }
  19. //---------------------------------------------------------------------------
  20. THttp::~THttp()
  21. {
  22. delete FResponseHeaders;
  23. }
  24. //---------------------------------------------------------------------------
  25. void THttp::SendRequest(const char * Method, const UnicodeString & Request)
  26. {
  27. std::unique_ptr<TStringList> AttemptedUrls(CreateSortedStringList());
  28. AttemptedUrls->Add(URL);
  29. UnicodeString RequestUrl = URL;
  30. bool WasTlsUri = false; // shut up
  31. bool Retry;
  32. do
  33. {
  34. ne_uri uri;
  35. NeonParseUrl(RequestUrl, uri);
  36. bool IsTls = IsTlsUri(uri);
  37. if (RequestUrl == URL)
  38. {
  39. WasTlsUri = IsTls;
  40. }
  41. else
  42. {
  43. if (!IsTls && WasTlsUri)
  44. {
  45. throw Exception(LoadStr(UNENCRYPTED_REDIRECT));
  46. }
  47. }
  48. FHostName = StrFromNeon(uri.host);
  49. UnicodeString Uri = StrFromNeon(uri.path);
  50. if (uri.query != NULL)
  51. {
  52. Uri += L"?" + StrFromNeon(uri.query);
  53. }
  54. FResponse.SetLength(0);
  55. FCertificateError.SetLength(0);
  56. FException.reset(NULL);
  57. ne_session_s * NeonSession = CreateNeonSession(uri);
  58. try
  59. {
  60. TProxyMethod ProxyMethod = ProxyHost.IsEmpty() ? ::pmNone : pmHTTP;
  61. InitNeonSession(NeonSession, ProxyMethod, ProxyHost, ProxyPort, UnicodeString(), UnicodeString());
  62. if (IsTls)
  63. {
  64. SetNeonTlsInit(NeonSession, InitSslSession);
  65. ne_ssl_set_verify(NeonSession, NeonServerSSLCallback, this);
  66. ne_ssl_trust_default_ca(NeonSession);
  67. }
  68. ne_request_s * NeonRequest = ne_request_create(NeonSession, Method, StrToNeon(Uri));
  69. try
  70. {
  71. if (FRequestHeaders != NULL)
  72. {
  73. for (int Index = 0; Index < FRequestHeaders->Count; Index++)
  74. {
  75. ne_add_request_header(
  76. NeonRequest, StrToNeon(FRequestHeaders->Names[Index]), StrToNeon(FRequestHeaders->ValueFromIndex[Index]));
  77. }
  78. }
  79. UTF8String RequestUtf;
  80. if (!Request.IsEmpty())
  81. {
  82. RequestUtf = UTF8String(Request);
  83. ne_set_request_body_buffer(NeonRequest, RequestUtf.c_str(), RequestUtf.Length());
  84. }
  85. ne_add_response_body_reader(NeonRequest, ne_accept_2xx, NeonBodyReader, this);
  86. int Status = ne_request_dispatch(NeonRequest);
  87. // Exception has precedence over status as status will always be NE_ERROR,
  88. // as we returned 1 from NeonBodyReader
  89. if (FException.get() != NULL)
  90. {
  91. RethrowException(FException.get());
  92. }
  93. if (Status == NE_REDIRECT)
  94. {
  95. Retry = true;
  96. RequestUrl = GetNeonRedirectUrl(NeonSession);
  97. CheckRedirectLoop(RequestUrl, AttemptedUrls.get());
  98. }
  99. else
  100. {
  101. Retry = false;
  102. CheckNeonStatus(NeonSession, Status, FHostName, FCertificateError);
  103. const ne_status * NeonStatus = ne_get_status(NeonRequest);
  104. if (NeonStatus->klass != 2)
  105. {
  106. throw Exception(FMTLOAD(HTTP_ERROR2, (NeonStatus->code, StrFromNeon(NeonStatus->reason_phrase), FHostName)));
  107. }
  108. void * Cursor = NULL;
  109. const char * HeaderName;
  110. const char * HeaderValue;
  111. while ((Cursor = ne_response_header_iterate(NeonRequest, Cursor, &HeaderName, &HeaderValue)) != NULL)
  112. {
  113. FResponseHeaders->Values[StrFromNeon(HeaderName)] = StrFromNeon(HeaderValue);
  114. }
  115. }
  116. }
  117. __finally
  118. {
  119. ne_request_destroy(NeonRequest);
  120. }
  121. }
  122. __finally
  123. {
  124. DestroyNeonSession(NeonSession);
  125. ne_uri_free(&uri);
  126. }
  127. }
  128. while (Retry);
  129. }
  130. //---------------------------------------------------------------------------
  131. void THttp::Get()
  132. {
  133. SendRequest("GET", UnicodeString());
  134. }
  135. //---------------------------------------------------------------------------
  136. void THttp::Post(const UnicodeString & Request)
  137. {
  138. SendRequest("POST", Request);
  139. }
  140. //---------------------------------------------------------------------------
  141. UnicodeString THttp::GetResponse()
  142. {
  143. UTF8String UtfResponse(FResponse);
  144. return UnicodeString(UtfResponse);
  145. }
  146. //---------------------------------------------------------------------------
  147. int THttp::NeonBodyReaderImpl(const char * Buf, size_t Len)
  148. {
  149. bool Result = true;
  150. if ((FResponseLimit < 0) ||
  151. (FResponse.Length() + Len <= FResponseLimit))
  152. {
  153. FResponse += RawByteString(Buf, Len);
  154. if (FOnDownload != NULL)
  155. {
  156. bool Cancel = false;
  157. try
  158. {
  159. FOnDownload(this, ResponseLength, Cancel);
  160. }
  161. catch (Exception & E)
  162. {
  163. FException.reset(CloneException(&E));
  164. Result = false;
  165. }
  166. if (Cancel)
  167. {
  168. FException.reset(new EAbort(UnicodeString()));
  169. Result = false;
  170. }
  171. }
  172. }
  173. // neon wants 0 for success
  174. return Result ? 0 : 1;
  175. }
  176. //---------------------------------------------------------------------------
  177. int THttp::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  178. {
  179. THttp * Http = static_cast<THttp *>(UserData);
  180. return Http->NeonBodyReaderImpl(Buf, Len);
  181. }
  182. //---------------------------------------------------------------------------
  183. __int64 THttp::GetResponseLength()
  184. {
  185. return FResponse.Length();
  186. }
  187. //------------------------------------------------------------------------------
  188. void THttp::InitSslSession(ssl_st * Ssl, ne_session * /*Session*/)
  189. {
  190. int Options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1;
  191. SSL_ctrl(Ssl, SSL_CTRL_OPTIONS, Options, NULL);
  192. }
  193. //---------------------------------------------------------------------------
  194. int THttp::NeonServerSSLCallback(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  195. {
  196. THttp * Http = static_cast<THttp *>(UserData);
  197. return Http->NeonServerSSLCallbackImpl(Failures, Certificate);
  198. }
  199. //---------------------------------------------------------------------------
  200. int THttp::NeonServerSSLCallbackImpl(int Failures, const ne_ssl_certificate * Certificate)
  201. {
  202. AnsiString AsciiCert = NeonExportCertificate(Certificate);
  203. UnicodeString WindowsCertificateError;
  204. if (Failures != 0)
  205. {
  206. NeonWindowsValidateCertificate(Failures, AsciiCert, WindowsCertificateError);
  207. }
  208. if (Failures != 0)
  209. {
  210. FCertificateError = NeonCertificateFailuresErrorStr(Failures, FHostName);
  211. AddToList(FCertificateError, WindowsCertificateError, L"\n");
  212. }
  213. return (Failures == 0) ? NE_OK : NE_ERROR;
  214. }
  215. //---------------------------------------------------------------------------
  216. bool THttp::IsCertificateError()
  217. {
  218. return !FCertificateError.IsEmpty();
  219. }
  220. //---------------------------------------------------------------------------