Http.cpp 7.4 KB

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