Http.cpp 7.4 KB

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