Http.cpp 8.9 KB

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