Http.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Http.h"
  5. #include "NeonIntf.h"
  6. #include "Exceptions.h"
  7. #include "CoreMain.h"
  8. #include "ne_request.h"
  9. #include "TextsCore.h"
  10. #include <openssl/ssl.h>
  11. //---------------------------------------------------------------------------
  12. THttp::THttp()
  13. {
  14. FProxyPort = 0;
  15. FOnDownload = NULL;
  16. FOnError = NULL;
  17. FResponseLimit = -1;
  18. FRequestHeaders = NULL;
  19. FResponseHeaders = new TStringList();
  20. }
  21. //---------------------------------------------------------------------------
  22. THttp::~THttp()
  23. {
  24. delete FResponseHeaders;
  25. }
  26. //---------------------------------------------------------------------------
  27. void THttp::SendRequest(const char * Method, const UnicodeString & Request)
  28. {
  29. std::unique_ptr<TStringList> AttemptedUrls(CreateSortedStringList());
  30. AttemptedUrls->Add(URL);
  31. UnicodeString RequestUrl = URL;
  32. bool WasTlsUri = false; // shut up
  33. bool Retry;
  34. do
  35. {
  36. ne_uri uri;
  37. NeonParseUrl(RequestUrl, uri);
  38. bool IsTls = IsTlsUri(uri);
  39. if (RequestUrl == URL)
  40. {
  41. WasTlsUri = IsTls;
  42. }
  43. else
  44. {
  45. if (!IsTls && WasTlsUri)
  46. {
  47. throw Exception(LoadStr(UNENCRYPTED_REDIRECT));
  48. }
  49. }
  50. FHostName = StrFromNeon(uri.host);
  51. UnicodeString Uri = StrFromNeon(uri.path);
  52. if (uri.query != NULL)
  53. {
  54. Uri += L"?" + StrFromNeon(uri.query);
  55. }
  56. FResponse.SetLength(0);
  57. FCertificateError.SetLength(0);
  58. FException.reset(NULL);
  59. ne_session_s * NeonSession = CreateNeonSession(uri);
  60. try
  61. {
  62. TProxyMethod ProxyMethod = ProxyHost.IsEmpty() ? ::pmNone : pmHTTP;
  63. InitNeonSession(NeonSession, ProxyMethod, ProxyHost, ProxyPort, UnicodeString(), UnicodeString(), NULL);
  64. if (IsTls)
  65. {
  66. InitNeonTls(NeonSession, InitSslSession, NeonServerSSLCallback, this, NULL);
  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. int Status = NeonStatus->code;
  107. UnicodeString Message = StrFromNeon(NeonStatus->reason_phrase);
  108. if (OnError != NULL)
  109. {
  110. OnError(this, Status, Message);
  111. }
  112. throw Exception(FMTLOAD(HTTP_ERROR2, (Status, Message, FHostName)));
  113. }
  114. void * Cursor = NULL;
  115. const char * HeaderName;
  116. const char * HeaderValue;
  117. while ((Cursor = ne_response_header_iterate(NeonRequest, Cursor, &HeaderName, &HeaderValue)) != NULL)
  118. {
  119. FResponseHeaders->Values[StrFromNeon(HeaderName)] = StrFromNeon(HeaderValue);
  120. }
  121. }
  122. }
  123. __finally
  124. {
  125. ne_request_destroy(NeonRequest);
  126. }
  127. }
  128. __finally
  129. {
  130. DestroyNeonSession(NeonSession);
  131. ne_uri_free(&uri);
  132. }
  133. }
  134. while (Retry);
  135. }
  136. //---------------------------------------------------------------------------
  137. void THttp::Get()
  138. {
  139. SendRequest("GET", UnicodeString());
  140. }
  141. //---------------------------------------------------------------------------
  142. void THttp::Post(const UnicodeString & Request)
  143. {
  144. SendRequest("POST", Request);
  145. }
  146. //---------------------------------------------------------------------------
  147. UnicodeString THttp::GetResponse()
  148. {
  149. UTF8String UtfResponse(FResponse);
  150. return UnicodeString(UtfResponse);
  151. }
  152. //---------------------------------------------------------------------------
  153. int THttp::NeonBodyReaderImpl(const char * Buf, size_t Len)
  154. {
  155. bool Result = true;
  156. if ((FResponseLimit < 0) ||
  157. (FResponse.Length() + Len <= FResponseLimit))
  158. {
  159. FResponse += RawByteString(Buf, Len);
  160. if (FOnDownload != NULL)
  161. {
  162. bool Cancel = false;
  163. try
  164. {
  165. FOnDownload(this, ResponseLength, Cancel);
  166. }
  167. catch (Exception & E)
  168. {
  169. FException.reset(CloneException(&E));
  170. Result = false;
  171. }
  172. if (Cancel)
  173. {
  174. FException.reset(new EAbort(UnicodeString()));
  175. Result = false;
  176. }
  177. }
  178. }
  179. // neon wants 0 for success
  180. return Result ? 0 : 1;
  181. }
  182. //---------------------------------------------------------------------------
  183. int THttp::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  184. {
  185. THttp * Http = static_cast<THttp *>(UserData);
  186. return Http->NeonBodyReaderImpl(Buf, Len);
  187. }
  188. //---------------------------------------------------------------------------
  189. __int64 THttp::GetResponseLength()
  190. {
  191. return FResponse.Length();
  192. }
  193. //------------------------------------------------------------------------------
  194. void THttp::InitSslSession(ssl_st * Ssl, ne_session * /*Session*/)
  195. {
  196. SetupSsl(Ssl, tlsDefaultMin, tlsMax);
  197. }
  198. //---------------------------------------------------------------------------
  199. int THttp::NeonServerSSLCallback(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  200. {
  201. THttp * Http = static_cast<THttp *>(UserData);
  202. return Http->NeonServerSSLCallbackImpl(Failures, Certificate);
  203. }
  204. //---------------------------------------------------------------------------
  205. int THttp::NeonServerSSLCallbackImpl(int Failures, const ne_ssl_certificate * Certificate)
  206. {
  207. AnsiString AsciiCert = NeonExportCertificate(Certificate);
  208. UnicodeString WindowsCertificateError;
  209. if (Failures != 0)
  210. {
  211. AppLogFmt(L"TLS failure: %s (%d)", (NeonCertificateFailuresErrorStr(Failures, FHostName), Failures));
  212. AppLogFmt(L"Hostname: %s, Certificate: %s", (FHostName, AsciiCert, AsciiCert));
  213. if (NeonWindowsValidateCertificate(Failures, AsciiCert, WindowsCertificateError))
  214. {
  215. AppLogFmt(L"Certificate trusted by Windows certificate store (%d)", (Failures));
  216. }
  217. if (!WindowsCertificateError.IsEmpty())
  218. {
  219. AppLogFmt(L"Error from Windows certificate store: %s", (WindowsCertificateError));
  220. }
  221. }
  222. if (Failures != 0)
  223. {
  224. FCertificateError = NeonCertificateFailuresErrorStr(Failures, FHostName);
  225. AppLogFmt(L"TLS certificate error: %s", (FCertificateError));
  226. AddToList(FCertificateError, WindowsCertificateError, L"\n");
  227. }
  228. return (Failures == 0) ? NE_OK : NE_ERROR;
  229. }
  230. //---------------------------------------------------------------------------
  231. bool THttp::IsCertificateError()
  232. {
  233. return !FCertificateError.IsEmpty();
  234. }
  235. //---------------------------------------------------------------------------