Http.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. FRequestHeaders = NULL;
  21. FResponseHeaders = new TStringList();
  22. }
  23. //---------------------------------------------------------------------------
  24. THttp::~THttp()
  25. {
  26. delete FResponseHeaders;
  27. }
  28. //---------------------------------------------------------------------------
  29. void THttp::SendRequest(const char * Method, const UnicodeString & Request)
  30. {
  31. std::unique_ptr<TStringList> AttemptedUrls(CreateSortedStringList());
  32. AttemptedUrls->Add(URL);
  33. UnicodeString RequestUrl = URL;
  34. bool WasTlsUri = false; // shut up
  35. bool Retry;
  36. do
  37. {
  38. ne_uri uri;
  39. NeonParseUrl(RequestUrl, uri);
  40. bool IsTls = IsTlsUri(uri);
  41. if (RequestUrl == URL)
  42. {
  43. WasTlsUri = IsTls;
  44. }
  45. else
  46. {
  47. if (!IsTls && WasTlsUri)
  48. {
  49. throw Exception(LoadStr(UNENCRYPTED_REDIRECT));
  50. }
  51. }
  52. FHostName = StrFromNeon(uri.host);
  53. UnicodeString Uri = StrFromNeon(uri.path);
  54. if (uri.query != NULL)
  55. {
  56. Uri += L"?" + StrFromNeon(uri.query);
  57. }
  58. FResponse.SetLength(0);
  59. FCertificateError.SetLength(0);
  60. FException.reset(NULL);
  61. ne_session_s * NeonSession = CreateNeonSession(uri);
  62. try
  63. {
  64. TProxyMethod ProxyMethod = ProxyHost.IsEmpty() ? ::pmNone : pmHTTP;
  65. InitNeonSession(NeonSession, ProxyMethod, ProxyHost, ProxyPort, UnicodeString(), UnicodeString(), NULL);
  66. if (IsTls)
  67. {
  68. InitNeonTls(NeonSession, InitSslSession, NeonServerSSLCallback, this, NULL);
  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. SetupSsl(Ssl, tlsDefaultMin, tlsMax);
  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. enum { hcvNoWindows = 0x01, hcvNoKnown = 0x02 };
  208. //---------------------------------------------------------------------------
  209. int THttp::NeonServerSSLCallbackImpl(int Failures, const ne_ssl_certificate * ACertificate)
  210. {
  211. AnsiString AsciiCert = NeonExportCertificate(ACertificate);
  212. UnicodeString WindowsCertificateError;
  213. if ((Failures != 0) && FLAGCLEAR(Configuration->HttpsCertificateValidation, hcvNoWindows))
  214. {
  215. AppLogFmt(L"TLS failure: %s (%d)", (NeonCertificateFailuresErrorStr(Failures, FHostName), Failures));
  216. AppLogFmt(L"Hostname: %s, Certificate: %s", (FHostName, AsciiCert, AsciiCert));
  217. if (NeonWindowsValidateCertificate(Failures, AsciiCert, WindowsCertificateError))
  218. {
  219. AppLogFmt(L"Certificate trusted by Windows certificate store (%d)", (Failures));
  220. }
  221. if (!WindowsCertificateError.IsEmpty())
  222. {
  223. AppLogFmt(L"Error from Windows certificate store: %s", (WindowsCertificateError));
  224. }
  225. }
  226. if ((Failures != 0) && FLAGSET(Failures, NE_SSL_UNTRUSTED) && FLAGCLEAR(Configuration->HttpsCertificateValidation, hcvNoKnown) &&
  227. !Certificate.IsEmpty())
  228. {
  229. const ne_ssl_certificate * RootCertificate = ACertificate;
  230. do
  231. {
  232. const ne_ssl_certificate * Issuer = ne_ssl_cert_signedby(RootCertificate);
  233. if (Issuer != NULL)
  234. {
  235. RootCertificate = Issuer;
  236. }
  237. else
  238. {
  239. break;
  240. }
  241. }
  242. while (true);
  243. UnicodeString RootCert = UnicodeString(NeonExportCertificate(RootCertificate));
  244. if (RootCert == Certificate)
  245. {
  246. Failures &= ~NE_SSL_UNTRUSTED;
  247. AppLogFmt(L"Certificate is known (%d)", (Failures));
  248. }
  249. }
  250. if (Failures != 0)
  251. {
  252. FCertificateError = NeonCertificateFailuresErrorStr(Failures, FHostName);
  253. AppLogFmt(L"TLS certificate error: %s", (FCertificateError));
  254. AddToList(FCertificateError, WindowsCertificateError, L"\n");
  255. }
  256. return (Failures == 0) ? NE_OK : NE_ERROR;
  257. }
  258. //---------------------------------------------------------------------------
  259. bool THttp::IsCertificateError()
  260. {
  261. return !FCertificateError.IsEmpty();
  262. }
  263. //---------------------------------------------------------------------------