http_request.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /*************************************************************************/
  2. /* http_request.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* */
  10. /* Permission is hereby granted, free of charge, to any person obtaining */
  11. /* a copy of this software and associated documentation files (the */
  12. /* "Software"), to deal in the Software without restriction, including */
  13. /* without limitation the rights to use, copy, modify, merge, publish, */
  14. /* distribute, sublicense, and/or sell copies of the Software, and to */
  15. /* permit persons to whom the Software is furnished to do so, subject to */
  16. /* the following conditions: */
  17. /* */
  18. /* The above copyright notice and this permission notice shall be */
  19. /* included in all copies or substantial portions of the Software. */
  20. /* */
  21. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  22. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  23. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  24. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  25. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  26. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  27. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  28. /*************************************************************************/
  29. #include "http_request.h"
  30. void HTTPRequest::set_ip_type(IP::Type p_type) {
  31. client->set_ip_type(p_type);
  32. }
  33. void HTTPRequest::_redirect_request(const String& p_new_url) {
  34. }
  35. Error HTTPRequest::_request() {
  36. //print_line("Requesting:\n\tURL: "+url+"\n\tString: "+request_string+"\n\tPort: "+itos(port)+"\n\tSSL: "+itos(use_ssl)+"\n\tValidate SSL: "+itos(validate_ssl));
  37. return client->connect_to_host(url,port,use_ssl,validate_ssl);
  38. }
  39. Error HTTPRequest::_parse_url(const String& p_url) {
  40. url=p_url;
  41. use_ssl=false;
  42. request_string="";
  43. port=80;
  44. request_sent=false;
  45. got_response=false;
  46. body_len=-1;
  47. body.resize(0);
  48. downloaded=0;
  49. redirections=0;
  50. //print_line("1 url: "+url);
  51. if (url.begins_with("http://")) {
  52. url=url.substr(7,url.length()-7);
  53. //print_line("no SSL");
  54. } else if (url.begins_with("https://")) {
  55. url=url.substr(8,url.length()-8);
  56. use_ssl=true;
  57. port=443;
  58. //print_line("yes SSL");
  59. } else {
  60. ERR_EXPLAIN("Malformed URL");
  61. ERR_FAIL_V(ERR_INVALID_PARAMETER);
  62. }
  63. //print_line("2 url: "+url);
  64. int slash_pos = url.find("/");
  65. if (slash_pos!=-1) {
  66. request_string=url.substr(slash_pos,url.length());
  67. url=url.substr(0,slash_pos);
  68. //print_line("request string: "+request_string);
  69. } else {
  70. request_string="/";
  71. //print_line("no request");
  72. }
  73. //print_line("3 url: "+url);
  74. int colon_pos = url.find(":");
  75. if (colon_pos!=-1) {
  76. port=url.substr(colon_pos+1,url.length()).to_int();
  77. url=url.substr(0,colon_pos);
  78. ERR_FAIL_COND_V(port<1 || port > 65535,ERR_INVALID_PARAMETER);
  79. }
  80. //print_line("4 url: "+url);
  81. return OK;
  82. }
  83. Error HTTPRequest::request(const String& p_url, const Vector<String>& p_custom_headers, bool p_ssl_validate_domain, HTTPClient::Method p_method, const String& p_request_data) {
  84. ERR_FAIL_COND_V(!is_inside_tree(),ERR_UNCONFIGURED);
  85. if ( requesting ) {
  86. ERR_EXPLAIN("HTTPRequest is processing a request. Wait for completion or cancel it before attempting a new one.");
  87. ERR_FAIL_V(ERR_BUSY);
  88. }
  89. method=p_method;
  90. Error err = _parse_url(p_url);
  91. if (err)
  92. return err;
  93. validate_ssl=p_ssl_validate_domain;
  94. bool has_user_agent=false;
  95. bool has_accept=false;
  96. headers=p_custom_headers;
  97. request_data = p_request_data;
  98. for(int i=0;i<headers.size();i++) {
  99. if (headers[i].findn("user-agent:")==0)
  100. has_user_agent=true;
  101. if (headers[i].findn("Accept:")==0)
  102. has_accept=true;
  103. }
  104. if (!has_user_agent) {
  105. headers.push_back("User-Agent: GodotEngine/"+String(VERSION_MKSTRING)+" ("+OS::get_singleton()->get_name()+")");
  106. }
  107. if (!has_accept) {
  108. headers.push_back("Accept: */*");
  109. }
  110. requesting=true;
  111. if (use_threads) {
  112. thread_done=false;
  113. thread_request_quit=false;
  114. client->set_blocking_mode(true);
  115. thread=Thread::create(_thread_func,this);
  116. } else {
  117. client->set_blocking_mode(false);
  118. err = _request();
  119. if (err!=OK) {
  120. call_deferred("_request_done",RESULT_CANT_CONNECT,0,PoolStringArray(),PoolByteArray());
  121. return ERR_CANT_CONNECT;
  122. }
  123. set_process_internal(true);
  124. }
  125. return OK;
  126. }
  127. void HTTPRequest::_thread_func(void *p_userdata) {
  128. HTTPRequest *hr = (HTTPRequest*)p_userdata;
  129. Error err = hr->_request();
  130. if (err!=OK) {
  131. hr->call_deferred("_request_done",RESULT_CANT_CONNECT,0,PoolStringArray(),PoolByteArray());
  132. } else {
  133. while(!hr->thread_request_quit) {
  134. bool exit = hr->_update_connection();
  135. if (exit)
  136. break;
  137. OS::get_singleton()->delay_usec(1);
  138. }
  139. }
  140. hr->thread_done=true;
  141. }
  142. void HTTPRequest::cancel_request() {
  143. if (!requesting)
  144. return;
  145. if (!use_threads) {
  146. set_process_internal(false);
  147. } else {
  148. thread_request_quit=true;
  149. Thread::wait_to_finish(thread);
  150. memdelete(thread);
  151. thread=NULL;
  152. }
  153. if (file) {
  154. memdelete(file);
  155. file=NULL;
  156. }
  157. client->close();
  158. body.resize(0);
  159. //downloaded=0;
  160. got_response=false;
  161. response_code=-1;
  162. //body_len=-1;
  163. request_sent=false;
  164. requesting=false;
  165. }
  166. bool HTTPRequest::_handle_response(bool *ret_value) {
  167. if (!client->has_response()) {
  168. call_deferred("_request_done",RESULT_NO_RESPONSE,0,PoolStringArray(),PoolByteArray());
  169. *ret_value=true;
  170. return true;
  171. }
  172. got_response=true;
  173. response_code=client->get_response_code();
  174. List<String> rheaders;
  175. client->get_response_headers(&rheaders);
  176. response_headers.resize(0);
  177. downloaded=0;
  178. for (List<String>::Element *E=rheaders.front();E;E=E->next()) {
  179. //print_line("HEADER: "+E->get());
  180. response_headers.push_back(E->get());
  181. }
  182. if (response_code==301 || response_code==302) {
  183. //redirect
  184. if (max_redirects>=0 && redirections>=max_redirects) {
  185. call_deferred("_request_done",RESULT_REDIRECT_LIMIT_REACHED,response_code,response_headers,PoolByteArray());
  186. *ret_value=true;
  187. return true;
  188. }
  189. String new_request;
  190. for (List<String>::Element *E=rheaders.front();E;E=E->next()) {
  191. if (E->get().findn("Location: ")!=-1) {
  192. new_request=E->get().substr(9,E->get().length()).strip_edges();
  193. }
  194. }
  195. //print_line("NEW LOCATION: "+new_request);
  196. if (new_request!="") {
  197. //process redirect
  198. client->close();
  199. int new_redirs=redirections+1; //because _request() will clear it
  200. Error err;
  201. if (new_request.begins_with("http")) {
  202. //new url, request all again
  203. err=_parse_url(new_request);
  204. } else {
  205. request_string=new_request;
  206. }
  207. err = _request();
  208. //print_line("new connection: "+itos(err));
  209. if (err==OK) {
  210. request_sent=false;
  211. got_response=false;
  212. body_len=-1;
  213. body.resize(0);
  214. downloaded=0;
  215. redirections=new_redirs;
  216. *ret_value=false;
  217. return true;
  218. }
  219. }
  220. }
  221. return false;
  222. }
  223. bool HTTPRequest::_update_connection() {
  224. switch( client->get_status() ) {
  225. case HTTPClient::STATUS_DISCONNECTED: {
  226. call_deferred("_request_done",RESULT_CANT_CONNECT,0,PoolStringArray(),PoolByteArray());
  227. return true; //end it, since it's doing something
  228. } break;
  229. case HTTPClient::STATUS_RESOLVING: {
  230. client->poll();
  231. //must wait
  232. return false;
  233. } break;
  234. case HTTPClient::STATUS_CANT_RESOLVE: {
  235. call_deferred("_request_done",RESULT_CANT_RESOLVE,0,PoolStringArray(),PoolByteArray());
  236. return true;
  237. } break;
  238. case HTTPClient::STATUS_CONNECTING: {
  239. client->poll();
  240. //must wait
  241. return false;
  242. } break; //connecting to ip
  243. case HTTPClient::STATUS_CANT_CONNECT: {
  244. call_deferred("_request_done",RESULT_CANT_CONNECT,0,PoolStringArray(),PoolByteArray());
  245. return true;
  246. } break;
  247. case HTTPClient::STATUS_CONNECTED: {
  248. if (request_sent) {
  249. if (!got_response) {
  250. //no body
  251. bool ret_value;
  252. if (_handle_response(&ret_value))
  253. return ret_value;
  254. call_deferred("_request_done",RESULT_SUCCESS,response_code,response_headers,PoolByteArray());
  255. return true;
  256. }
  257. if (got_response && body_len<0) {
  258. //chunked transfer is done
  259. call_deferred("_request_done",RESULT_SUCCESS,response_code,response_headers,body);
  260. return true;
  261. }
  262. call_deferred("_request_done",RESULT_CHUNKED_BODY_SIZE_MISMATCH,response_code,response_headers,PoolByteArray());
  263. return true;
  264. //request migh have been done
  265. } else {
  266. //did not request yet, do request
  267. Error err = client->request(method,request_string,headers,request_data);
  268. if (err!=OK) {
  269. call_deferred("_request_done",RESULT_CONNECTION_ERROR,0,PoolStringArray(),PoolByteArray());
  270. return true;
  271. }
  272. request_sent=true;
  273. return false;
  274. }
  275. } break; //connected: { } break requests only accepted here
  276. case HTTPClient::STATUS_REQUESTING: {
  277. //must wait, it's requesting
  278. client->poll();
  279. return false;
  280. } break; // request in progress
  281. case HTTPClient::STATUS_BODY: {
  282. if (!got_response) {
  283. bool ret_value;
  284. if (_handle_response(&ret_value))
  285. return ret_value;
  286. if (!client->is_response_chunked() && client->get_response_body_length()==0) {
  287. call_deferred("_request_done",RESULT_SUCCESS,response_code,response_headers,PoolByteArray());
  288. return true;
  289. }
  290. if (client->is_response_chunked()) {
  291. body_len=-1; //no body len because chunked, change your webserver configuration if you want body len
  292. } else {
  293. body_len=client->get_response_body_length();
  294. if (body_size_limit>=0 && body_len>body_size_limit) {
  295. call_deferred("_request_done",RESULT_BODY_SIZE_LIMIT_EXCEEDED,response_code,response_headers,PoolByteArray());
  296. return true;
  297. }
  298. }
  299. if (download_to_file!=String()) {
  300. file=FileAccess::open(download_to_file,FileAccess::WRITE);
  301. if (!file) {
  302. call_deferred("_request_done",RESULT_DOWNLOAD_FILE_CANT_OPEN,response_code,response_headers,PoolByteArray());
  303. return true;
  304. }
  305. }
  306. }
  307. //print_line("BODY: "+itos(body.size()));
  308. client->poll();
  309. PoolByteArray chunk = client->read_response_body_chunk();
  310. downloaded+=chunk.size();
  311. if (file) {
  312. PoolByteArray::Read r=chunk.read();
  313. file->store_buffer(r.ptr(),chunk.size());
  314. if (file->get_error()!=OK) {
  315. call_deferred("_request_done",RESULT_DOWNLOAD_FILE_WRITE_ERROR,response_code,response_headers,PoolByteArray());
  316. return true;
  317. }
  318. } else {
  319. body.append_array(chunk);
  320. }
  321. if (body_size_limit>=0 && downloaded>body_size_limit) {
  322. call_deferred("_request_done",RESULT_BODY_SIZE_LIMIT_EXCEEDED,response_code,response_headers,PoolByteArray());
  323. return true;
  324. }
  325. if (body_len>=0) {
  326. if (downloaded==body_len) {
  327. call_deferred("_request_done",RESULT_SUCCESS,response_code,response_headers,body);
  328. return true;
  329. }
  330. /*if (body.size()>=body_len) {
  331. call_deferred("_request_done",RESULT_BODY_SIZE_MISMATCH,response_code,response_headers,ByteArray());
  332. return true;
  333. }*/
  334. }
  335. return false;
  336. } break; // request resulted in body: { } break which must be read
  337. case HTTPClient::STATUS_CONNECTION_ERROR: {
  338. call_deferred("_request_done",RESULT_CONNECTION_ERROR,0,PoolStringArray(),PoolByteArray());
  339. return true;
  340. } break;
  341. case HTTPClient::STATUS_SSL_HANDSHAKE_ERROR: {
  342. call_deferred("_request_done",RESULT_SSL_HANDSHAKE_ERROR,0,PoolStringArray(),PoolByteArray());
  343. return true;
  344. } break;
  345. }
  346. ERR_FAIL_V(false);
  347. }
  348. void HTTPRequest::_request_done(int p_status, int p_code, const PoolStringArray& headers, const PoolByteArray& p_data) {
  349. cancel_request();
  350. emit_signal("request_completed",p_status,p_code,headers,p_data);
  351. }
  352. void HTTPRequest::_notification(int p_what) {
  353. if (p_what==NOTIFICATION_INTERNAL_PROCESS) {
  354. if (use_threads)
  355. return;
  356. bool done = _update_connection();
  357. if (done) {
  358. set_process_internal(false);
  359. //cancel_request(); called from _request done now
  360. }
  361. }
  362. if (p_what==NOTIFICATION_EXIT_TREE) {
  363. if (requesting) {
  364. cancel_request();
  365. }
  366. }
  367. }
  368. void HTTPRequest::set_use_threads(bool p_use) {
  369. ERR_FAIL_COND( status!=HTTPClient::STATUS_DISCONNECTED );
  370. use_threads=p_use;
  371. }
  372. bool HTTPRequest::is_using_threads() const {
  373. return use_threads;
  374. }
  375. void HTTPRequest::set_body_size_limit(int p_bytes) {
  376. ERR_FAIL_COND( status!=HTTPClient::STATUS_DISCONNECTED );
  377. body_size_limit=p_bytes;
  378. }
  379. int HTTPRequest::get_body_size_limit() const {
  380. return body_size_limit;
  381. }
  382. void HTTPRequest::set_download_file(const String& p_file) {
  383. ERR_FAIL_COND( status!=HTTPClient::STATUS_DISCONNECTED );
  384. download_to_file=p_file;
  385. }
  386. String HTTPRequest::get_download_file() const {
  387. return download_to_file;
  388. }
  389. HTTPClient::Status HTTPRequest::get_http_client_status() const {
  390. return client->get_status();
  391. }
  392. void HTTPRequest::set_max_redirects(int p_max) {
  393. max_redirects=p_max;
  394. }
  395. int HTTPRequest::get_max_redirects() const{
  396. return max_redirects;
  397. }
  398. int HTTPRequest::get_downloaded_bytes() const {
  399. return downloaded;
  400. }
  401. int HTTPRequest::get_body_size() const{
  402. return body_len;
  403. }
  404. void HTTPRequest::_bind_methods() {
  405. ClassDB::bind_method(_MD("set_ip_type","ip_type"),&HTTPRequest::set_ip_type);
  406. ClassDB::bind_method(_MD("request","url","custom_headers","ssl_validate_domain","method","request_data"),&HTTPRequest::request,DEFVAL(PoolStringArray()),DEFVAL(true),DEFVAL(HTTPClient::METHOD_GET),DEFVAL(String()));
  407. ClassDB::bind_method(_MD("cancel_request"),&HTTPRequest::cancel_request);
  408. ClassDB::bind_method(_MD("get_http_client_status"),&HTTPRequest::get_http_client_status);
  409. ClassDB::bind_method(_MD("set_use_threads","enable"),&HTTPRequest::set_use_threads);
  410. ClassDB::bind_method(_MD("is_using_threads"),&HTTPRequest::is_using_threads);
  411. ClassDB::bind_method(_MD("set_body_size_limit","bytes"),&HTTPRequest::set_body_size_limit);
  412. ClassDB::bind_method(_MD("get_body_size_limit"),&HTTPRequest::get_body_size_limit);
  413. ClassDB::bind_method(_MD("set_max_redirects","amount"),&HTTPRequest::set_max_redirects);
  414. ClassDB::bind_method(_MD("get_max_redirects"),&HTTPRequest::get_max_redirects);
  415. ClassDB::bind_method(_MD("set_download_file","path"),&HTTPRequest::set_download_file);
  416. ClassDB::bind_method(_MD("get_download_file"),&HTTPRequest::get_download_file);
  417. ClassDB::bind_method(_MD("get_downloaded_bytes"),&HTTPRequest::get_downloaded_bytes);
  418. ClassDB::bind_method(_MD("get_body_size"),&HTTPRequest::get_body_size);
  419. ClassDB::bind_method(_MD("_redirect_request"),&HTTPRequest::_redirect_request);
  420. ClassDB::bind_method(_MD("_request_done"),&HTTPRequest::_request_done);
  421. ADD_PROPERTY(PropertyInfo(Variant::BOOL,"use_threads"),_SCS("set_use_threads"),_SCS("is_using_threads"));
  422. ADD_PROPERTY(PropertyInfo(Variant::INT,"body_size_limit",PROPERTY_HINT_RANGE,"-1,2000000000"),_SCS("set_body_size_limit"),_SCS("get_body_size_limit"));
  423. ADD_PROPERTY(PropertyInfo(Variant::INT,"max_redirects",PROPERTY_HINT_RANGE,"-1,1024"),_SCS("set_max_redirects"),_SCS("get_max_redirects"));
  424. ADD_SIGNAL(MethodInfo("request_completed",PropertyInfo(Variant::INT,"result"),PropertyInfo(Variant::INT,"response_code"),PropertyInfo(Variant::POOL_STRING_ARRAY,"headers"),PropertyInfo(Variant::POOL_BYTE_ARRAY,"body")));
  425. BIND_CONSTANT( RESULT_SUCCESS );
  426. //BIND_CONSTANT( RESULT_NO_BODY );
  427. BIND_CONSTANT( RESULT_CHUNKED_BODY_SIZE_MISMATCH );
  428. BIND_CONSTANT( RESULT_CANT_CONNECT );
  429. BIND_CONSTANT( RESULT_CANT_RESOLVE );
  430. BIND_CONSTANT( RESULT_CONNECTION_ERROR );
  431. BIND_CONSTANT( RESULT_SSL_HANDSHAKE_ERROR );
  432. BIND_CONSTANT( RESULT_NO_RESPONSE );
  433. BIND_CONSTANT( RESULT_BODY_SIZE_LIMIT_EXCEEDED );
  434. BIND_CONSTANT( RESULT_REQUEST_FAILED );
  435. BIND_CONSTANT( RESULT_DOWNLOAD_FILE_CANT_OPEN );
  436. BIND_CONSTANT( RESULT_DOWNLOAD_FILE_WRITE_ERROR );
  437. BIND_CONSTANT( RESULT_REDIRECT_LIMIT_REACHED );
  438. }
  439. HTTPRequest::HTTPRequest()
  440. {
  441. thread=NULL;
  442. port=80;
  443. redirections=0;
  444. max_redirects=8;
  445. body_len=-1;
  446. got_response=false;
  447. validate_ssl=false;
  448. use_ssl=false;
  449. response_code=0;
  450. request_sent=false;
  451. requesting=false;
  452. client.instance();
  453. use_threads=false;
  454. thread_done=false;
  455. body_size_limit=-1;
  456. file=NULL;
  457. status=HTTPClient::STATUS_DISCONNECTED;
  458. }
  459. HTTPRequest::~HTTPRequest() {
  460. if (file)
  461. memdelete(file);
  462. }