http_request.cpp 16 KB

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