http_request.cpp 16 KB

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