Http.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. void THttp::Put(const UnicodeString & Request)
  152. {
  153. SendRequest("PUT", Request);
  154. }
  155. //---------------------------------------------------------------------------
  156. UnicodeString THttp::GetResponse()
  157. {
  158. UTF8String UtfResponse(FResponse);
  159. return UnicodeString(UtfResponse);
  160. }
  161. //---------------------------------------------------------------------------
  162. int THttp::NeonBodyReaderImpl(const char * Buf, size_t Len)
  163. {
  164. bool Result = true;
  165. if ((FResponseLimit < 0) ||
  166. (FResponse.Length() + Len <= FResponseLimit))
  167. {
  168. FResponse += RawByteString(Buf, Len);
  169. if (FOnDownload != NULL)
  170. {
  171. bool Cancel = false;
  172. try
  173. {
  174. FOnDownload(this, ResponseLength, Cancel);
  175. }
  176. catch (Exception & E)
  177. {
  178. FException.reset(CloneException(&E));
  179. Result = false;
  180. }
  181. if (Cancel)
  182. {
  183. FException.reset(new EAbort(UnicodeString()));
  184. Result = false;
  185. }
  186. }
  187. }
  188. // neon wants 0 for success
  189. return Result ? 0 : 1;
  190. }
  191. //---------------------------------------------------------------------------
  192. int THttp::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  193. {
  194. THttp * Http = static_cast<THttp *>(UserData);
  195. return Http->NeonBodyReaderImpl(Buf, Len);
  196. }
  197. //---------------------------------------------------------------------------
  198. __int64 THttp::GetResponseLength()
  199. {
  200. return FResponse.Length();
  201. }
  202. //------------------------------------------------------------------------------
  203. void THttp::InitSslSession(ssl_st * Ssl, ne_session * /*Session*/)
  204. {
  205. SetupSsl(Ssl, tlsDefaultMin, tlsMax);
  206. }
  207. //---------------------------------------------------------------------------
  208. int THttp::NeonServerSSLCallback(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  209. {
  210. THttp * Http = static_cast<THttp *>(UserData);
  211. return Http->NeonServerSSLCallbackImpl(Failures, Certificate);
  212. }
  213. //---------------------------------------------------------------------------
  214. enum { hcvNoWindows = 0x01, hcvNoKnown = 0x02 };
  215. //---------------------------------------------------------------------------
  216. int THttp::NeonServerSSLCallbackImpl(int Failures, const ne_ssl_certificate * ACertificate)
  217. {
  218. AnsiString AsciiCert = NeonExportCertificate(ACertificate);
  219. UnicodeString WindowsCertificateError;
  220. if ((Failures != 0) && FLAGCLEAR(Configuration->HttpsCertificateValidation, hcvNoWindows))
  221. {
  222. AppLogFmt(L"TLS failure: %s (%d)", (NeonCertificateFailuresErrorStr(Failures, FHostName), Failures));
  223. AppLogFmt(L"Hostname: %s, Certificate: %s", (FHostName, AsciiCert, AsciiCert));
  224. if (NeonWindowsValidateCertificate(Failures, AsciiCert, WindowsCertificateError))
  225. {
  226. AppLogFmt(L"Certificate trusted by Windows certificate store (%d)", (Failures));
  227. }
  228. if (!WindowsCertificateError.IsEmpty())
  229. {
  230. AppLogFmt(L"Error from Windows certificate store: %s", (WindowsCertificateError));
  231. }
  232. }
  233. if ((Failures != 0) && FLAGSET(Failures, NE_SSL_UNTRUSTED) && FLAGCLEAR(Configuration->HttpsCertificateValidation, hcvNoKnown) &&
  234. !Certificate.IsEmpty())
  235. {
  236. const ne_ssl_certificate * RootCertificate = ACertificate;
  237. do
  238. {
  239. const ne_ssl_certificate * Issuer = ne_ssl_cert_signedby(RootCertificate);
  240. if (Issuer != NULL)
  241. {
  242. RootCertificate = Issuer;
  243. }
  244. else
  245. {
  246. break;
  247. }
  248. }
  249. while (true);
  250. UnicodeString RootCert = UnicodeString(NeonExportCertificate(RootCertificate));
  251. AppLogFmt(L"Root certificate: %s", (RootCert));
  252. if (RootCert == Certificate)
  253. {
  254. Failures &= ~NE_SSL_UNTRUSTED;
  255. AppLogFmt(L"Root certificate is known (%d)", (Failures));
  256. }
  257. }
  258. if (Failures != 0)
  259. {
  260. FCertificateError = NeonCertificateFailuresErrorStr(Failures, FHostName);
  261. AppLogFmt(L"TLS certificate error: %s", (FCertificateError));
  262. AddToList(FCertificateError, WindowsCertificateError, L"\n");
  263. }
  264. return (Failures == 0) ? NE_OK : NE_ERROR;
  265. }
  266. //---------------------------------------------------------------------------
  267. bool THttp::IsCertificateError()
  268. {
  269. return !FCertificateError.IsEmpty();
  270. }
  271. //---------------------------------------------------------------------------