Http.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. //---------------------------------------------------------------------------
  2. #include <CorePCH.h>
  3. #pragma hdrstop
  4. #include "Http.h"
  5. #include "NeonIntf.h"
  6. #include "Exceptions.h"
  7. #include "ne_request.h"
  8. #include <openssl/ssl.h>
  9. //---------------------------------------------------------------------------
  10. const int BasicHttpResponseLimit = 102400;
  11. //---------------------------------------------------------------------------
  12. THttp::THttp()
  13. {
  14. FProxyPort = 0;
  15. FOnDownload = NULL;
  16. FOnError = NULL;
  17. FResponseLimit = -1;
  18. FConnectTimeout = 0;
  19. FRequestHeaders = NULL;
  20. FResponseHeaders = new TStringList();
  21. }
  22. //---------------------------------------------------------------------------
  23. THttp::~THttp()
  24. {
  25. delete FResponseHeaders;
  26. }
  27. //---------------------------------------------------------------------------
  28. void THttp::SendRequest(const char * Method, const UnicodeString & Request)
  29. {
  30. std::unique_ptr<TStringList> AttemptedUrls(CreateSortedStringList());
  31. AttemptedUrls->Add(URL);
  32. UnicodeString RequestUrl = URL;
  33. bool WasTlsUri = false; // shut up
  34. bool Retry;
  35. do
  36. {
  37. ne_uri uri;
  38. NeonParseUrl(RequestUrl, uri);
  39. bool IsTls = IsTlsUri(uri);
  40. if (RequestUrl == URL)
  41. {
  42. WasTlsUri = IsTls;
  43. }
  44. else
  45. {
  46. if (!IsTls && WasTlsUri)
  47. {
  48. throw Exception(LoadStr(UNENCRYPTED_REDIRECT));
  49. }
  50. }
  51. FHostName = StrFromNeon(uri.host);
  52. UnicodeString Uri = StrFromNeon(uri.path);
  53. if (uri.query != NULL)
  54. {
  55. Uri += L"?" + StrFromNeon(uri.query);
  56. }
  57. FResponse.SetLength(0);
  58. FCertificateError.SetLength(0);
  59. FException.reset(NULL);
  60. ne_session_s * NeonSession = CreateNeonSession(uri);
  61. try
  62. {
  63. TProxyMethod ProxyMethod = ProxyHost.IsEmpty() ? ::pmNone : pmHTTP;
  64. InitNeonSession(NeonSession, ProxyMethod, ProxyHost, ProxyPort, UnicodeString(), UnicodeString(), NULL);
  65. ne_set_connect_timeout(NeonSession, ConnectTimeout);
  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. void THttp::Put(const UnicodeString & Request)
  150. {
  151. SendRequest("PUT", Request);
  152. }
  153. //---------------------------------------------------------------------------
  154. UnicodeString THttp::GetResponse()
  155. {
  156. return UTFToString(FResponse);
  157. }
  158. //---------------------------------------------------------------------------
  159. int THttp::NeonBodyReaderImpl(const char * Buf, size_t Len)
  160. {
  161. bool Result = true;
  162. if ((FResponseLimit < 0) ||
  163. (FResponse.Length() + Len <= FResponseLimit))
  164. {
  165. FResponse += RawByteString(Buf, Len);
  166. if (FOnDownload != NULL)
  167. {
  168. bool Cancel = false;
  169. try
  170. {
  171. FOnDownload(this, ResponseLength, Cancel);
  172. }
  173. catch (Exception & E)
  174. {
  175. FException.reset(CloneException(&E));
  176. Result = false;
  177. }
  178. if (Cancel)
  179. {
  180. FException.reset(new EAbort(UnicodeString()));
  181. Result = false;
  182. }
  183. }
  184. }
  185. // neon wants 0 for success
  186. return Result ? 0 : 1;
  187. }
  188. //---------------------------------------------------------------------------
  189. int THttp::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  190. {
  191. THttp * Http = static_cast<THttp *>(UserData);
  192. return Http->NeonBodyReaderImpl(Buf, Len);
  193. }
  194. //---------------------------------------------------------------------------
  195. __int64 THttp::GetResponseLength()
  196. {
  197. return FResponse.Length();
  198. }
  199. //------------------------------------------------------------------------------
  200. void THttp::InitSslSession(ssl_st * Ssl, ne_session * /*Session*/)
  201. {
  202. SetupSsl(Ssl, tlsDefaultMin, tlsMax);
  203. }
  204. //---------------------------------------------------------------------------
  205. int THttp::NeonServerSSLCallback(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  206. {
  207. THttp * Http = static_cast<THttp *>(UserData);
  208. return Http->NeonServerSSLCallbackImpl(Failures, Certificate);
  209. }
  210. //---------------------------------------------------------------------------
  211. enum { hcvNoWindows = 0x01, hcvNoKnown = 0x02 };
  212. //---------------------------------------------------------------------------
  213. int THttp::NeonServerSSLCallbackImpl(int Failures, const ne_ssl_certificate * ACertificate)
  214. {
  215. AnsiString AsciiCert = NeonExportCertificate(ACertificate);
  216. UnicodeString WindowsCertificateError;
  217. if ((Failures != 0) && FLAGCLEAR(Configuration->HttpsCertificateValidation, hcvNoWindows))
  218. {
  219. AppLogFmt(L"TLS failure: %s (%d)", (NeonCertificateFailuresErrorStr(Failures, FHostName), Failures));
  220. AppLogFmt(L"Hostname: %s, Certificate: %s", (FHostName, AsciiCert, AsciiCert));
  221. if (NeonWindowsValidateCertificate(Failures, AsciiCert, WindowsCertificateError))
  222. {
  223. AppLogFmt(L"Certificate trusted by Windows certificate store (%d)", (Failures));
  224. }
  225. if (!WindowsCertificateError.IsEmpty())
  226. {
  227. AppLogFmt(L"Error from Windows certificate store: %s", (WindowsCertificateError));
  228. }
  229. }
  230. if ((Failures != 0) && FLAGSET(Failures, NE_SSL_UNTRUSTED) && FLAGCLEAR(Configuration->HttpsCertificateValidation, hcvNoKnown) &&
  231. !Certificate.IsEmpty())
  232. {
  233. const ne_ssl_certificate * RootCertificate = ACertificate;
  234. do
  235. {
  236. const ne_ssl_certificate * Issuer = ne_ssl_cert_signedby(RootCertificate);
  237. if (Issuer != NULL)
  238. {
  239. RootCertificate = Issuer;
  240. }
  241. else
  242. {
  243. break;
  244. }
  245. }
  246. while (true);
  247. UnicodeString RootCert = UnicodeString(NeonExportCertificate(RootCertificate));
  248. AppLogFmt(L"Root certificate: %s", (RootCert));
  249. if (RootCert == Certificate)
  250. {
  251. Failures &= ~NE_SSL_UNTRUSTED;
  252. AppLogFmt(L"Root certificate is known (%d)", (Failures));
  253. }
  254. }
  255. if (Failures != 0)
  256. {
  257. FCertificateError = NeonCertificateFailuresErrorStr(Failures, FHostName);
  258. AppLogFmt(L"TLS certificate error: %s", (FCertificateError));
  259. AddToList(FCertificateError, WindowsCertificateError, L"\n");
  260. }
  261. return (Failures == 0) ? NE_OK : NE_ERROR;
  262. }
  263. //---------------------------------------------------------------------------
  264. bool THttp::IsCertificateError()
  265. {
  266. return !FCertificateError.IsEmpty();
  267. }
  268. //---------------------------------------------------------------------------