http_server.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. #include "http_server.h"
  2. #include <stdarg.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <sys/wait.h>
  7. #include <sys/reboot.h>
  8. #include <iostream>
  9. #include <fstream>
  10. #include <sstream>
  11. #include <string.h>
  12. #include "shttpd/shttpd.h"
  13. #include "storage/StoragePreferences.h"
  14. #include "service/BusinessConfig.h"
  15. #include "manager/ConfigManager.h"
  16. #include "utils/Log.h"
  17. #include "shttpd/multipart_reader.h"
  18. #include "os/MountMonitor.h"
  19. #include "net/NetManager.h"
  20. #define ETHERNETMANAGER NETMANAGER->getEthernetManager()
  21. namespace srv {
  22. class MyThread: public Thread {
  23. public:
  24. virtual bool readyToRun() {
  25. return true;
  26. }
  27. virtual bool threadLoop() {
  28. //检查是否有退出线程的请求,如果有,则返回false,立即退出线程
  29. if (exitPending()) {
  30. return false;
  31. }
  32. //休眠5s
  33. usleep(5000 * 1000);
  34. //重启
  35. sync();
  36. reboot(RB_AUTOBOOT);
  37. //返回真,继续下次线程循环
  38. return false;
  39. }
  40. };
  41. static MyThread my_thread;
  42. //地址总长
  43. #define ADDRLEN 15
  44. //定义字符串数组保存IP地址、掩码地址、网关地址、首选DNS服务器地址以及备选DNS服务器地址
  45. static std::string addr[5];
  46. /**
  47. * 字符长度是否正确
  48. * */
  49. const bool isLengthCorrect(const std::string addr)
  50. {
  51. return addr.size() <= ADDRLEN;
  52. }
  53. /**
  54. * 检查是不是最多只有3个.字符
  55. * */
  56. const bool noMoreThan3charactor(const std::string addr)
  57. {
  58. //.字符个数
  59. int count = 0;
  60. for(unsigned int level1 = 0; level1 < addr.size(); ++level1)
  61. {
  62. if('.' == addr[level1])
  63. {
  64. ++count;
  65. }
  66. }
  67. return 3 >= count;
  68. }
  69. /*
  70. * 判断所有字符是不是由0~9和.组成
  71. * */
  72. const bool allCharacterIsLegal(const std::string addr)
  73. {
  74. for(unsigned int level1 = 0; level1 < addr.size(); ++level1)
  75. {
  76. if(false == (('0' <= addr[level1] && addr[level1] <= '9') || '.' == addr[level1]))
  77. {
  78. return false;
  79. }
  80. }
  81. return true;
  82. }
  83. /**
  84. * 判断开头是否是1`9
  85. * */
  86. const bool headIsCorrect(std::string addr, unsigned int pos = 0)
  87. {
  88. //查找到达末尾,直接返回true
  89. if(addr.size() == pos)
  90. {
  91. return true;
  92. }
  93. //查找.字符
  94. if(std::string::npos == addr.find('.', pos))
  95. {
  96. if('0' < addr[pos] && addr[pos] <= '9')
  97. {
  98. return true;
  99. }
  100. //如果开头为字符'0'且其后没有字符,那么返回true
  101. else if(addr.size()-1 == pos)
  102. {
  103. return true;
  104. }
  105. return false;
  106. }
  107. else
  108. {
  109. //开头为0~9
  110. if('0' > addr[pos] || addr[pos] > '9')
  111. {
  112. return false;
  113. }
  114. //开头为0,后面没有字符返回false
  115. if('0' == addr[pos] && addr.size()-1 <= pos)
  116. {
  117. return false;
  118. }
  119. //跳过.字符继续查找
  120. return headIsCorrect(addr, addr.find('.', pos)+1);
  121. }
  122. return true; //默认返回true
  123. }
  124. /**
  125. * 检查地址每一小段的长度,最长为3个字符
  126. * */
  127. const bool partCheractorCorrect(const std::string addr, unsigned int pos = 0)
  128. {
  129. //查找到达末尾,直接返回true
  130. if(addr.size() == pos)
  131. {
  132. return true;
  133. }
  134. //查找.字符
  135. if(std::string::npos == addr.find('.', pos))
  136. {
  137. if(3 >= addr.size()-pos)
  138. {
  139. return true;
  140. }
  141. return false;
  142. }
  143. else
  144. {
  145. //由于跳过了.字符进行查找,因此判断条件应该是>3
  146. if(3 < addr.find('.', pos) - pos)
  147. {
  148. return false;
  149. }
  150. //跳过.字符继续查找
  151. return partCheractorCorrect(addr, addr.find('.', pos)+1);
  152. }
  153. return true; //默认返回true
  154. }
  155. /**
  156. * 检测地址是否有误
  157. * */
  158. const bool checkAddr(std::string addr)
  159. {
  160. return (true == headIsCorrect(addr))? //地址每小段开头是否为0~9
  161. (true == partCheractorCorrect(addr))? //每小段字符串最大长度是否为3
  162. (true == noMoreThan3charactor(addr))? //最多是否只有3个.字符
  163. (true == isLengthCorrect(addr))? //地址最大长度是否为15
  164. (true == allCharacterIsLegal(addr))? //所有的字符是否都由0~9和.组成
  165. true: false: false: false: false: false;
  166. }
  167. struct NetworkConfiguration {
  168. std::string ip;
  169. std::string sub_network_mask;
  170. std::string gateway;
  171. std::string dns1;
  172. std::string dns2;
  173. };
  174. NetworkConfiguration GetNetworkConfiguration() {
  175. char ip[64] = {0};
  176. char mask[64] = {0};
  177. char gateway[64] = {0};
  178. char dns1[64] = {0};
  179. char dns2[64] = {0};
  180. if (ETHERNETMANAGER->isAutoMode()) {
  181. ETHERNETMANAGER->getConfigureInfo(ip, mask, gateway, dns1, dns2);
  182. } else {
  183. ETHERNETMANAGER->getStaticConfigureInfo(ip, mask, gateway, dns1, dns2);
  184. }
  185. return NetworkConfiguration{ip, mask, gateway, dns1, dns2};
  186. }
  187. std::string read_file(const std::string &file) {
  188. std::ifstream ifs(file.c_str(), std::ios::binary | std::ios::in);
  189. if (!ifs.is_open()) {
  190. return "";
  191. }
  192. std::stringstream ss;
  193. ss << ifs.rdbuf();
  194. ifs.close();
  195. std::string content(ss.str());
  196. return content;
  197. }
  198. // Content-Type: multipart/form-data; boundary=----WebKitFormBoundary4MxyDJzPWCVPEFFc
  199. std::string get_boundary(shttpd_arg *arg) {
  200. int len = 0;
  201. const char* boundary = shttpd_get_boundary(arg, &len);
  202. if (boundary) {
  203. return std::string(boundary, len);
  204. }
  205. return "";
  206. }
  207. /*
  208. * This callback function is attached to the "/" and "/abc.html" URIs,
  209. * thus is acting as "index.html" file. It shows a bunch of links
  210. * to other URIs, and allows to change the value of program's
  211. * internal variable. The pointer to that variable is passed to the
  212. * callback function as arg->user_data.
  213. */
  214. static void
  215. show_index(struct shttpd_arg *arg)
  216. {
  217. // int *p = arg->user_data; /* integer passed to us */
  218. char wifi_name[128] = {0};
  219. char wifi_password[128] = {0};
  220. const char *request_method, *query_string;
  221. request_method = shttpd_get_env(arg, "REQUEST_METHOD");
  222. // request_uri = shttpd_get_env(arg, "REQUEST_URI");
  223. query_string = shttpd_get_env(arg, "QUERY_STRING");
  224. /* Change the value of integer variable */
  225. if (!strcmp(request_method, "POST")) {
  226. /* If not all data is POSTed, wait for the rest */
  227. if (arg->flags & SHTTPD_MORE_POST_DATA)
  228. return;
  229. shttpd_get_var("wifi_name", arg->in.buf, arg->in.len,
  230. wifi_name, sizeof(wifi_name));
  231. shttpd_get_var("wifi_password", arg->in.buf, arg->in.len,
  232. wifi_password, sizeof(wifi_password));
  233. // mTextViewSetupNamePtr->setText(wifi_name);
  234. // mTextViewSetupPasswordPtr->setText(wifi_password);
  235. // StoragePreferences::putString(PROP_WIFI_NAME, wifi_name);
  236. // StoragePreferences::putString(PROP_WIFI_PASSWORD, wifi_password);
  237. } else if (query_string != NULL) { // GET
  238. // (void) shttpd_get_var("name1", query_string,
  239. // strlen(query_string), wifi_name, sizeof(wifi_name));
  240. }
  241. shttpd_printf(arg, "%s", "HTTP/1.1 200 OK\r\n");
  242. shttpd_printf(arg, "%s", "Content-Type: text/html\r\n\r\n");
  243. std::string content = read_file(CONFIGMANAGER->getResFilePath("html/index.html"));
  244. std::string serverIp = StoragePreferences::getString(STORE_GATEWAY, serverIP);
  245. content = srv::format(content.c_str(),
  246. NETMANAGER->getEthernetManager()->getMacAddr(),
  247. NETMANAGER->getEthernetManager()->getIp(),
  248. GetNetworkConfiguration().sub_network_mask.c_str(),
  249. GetNetworkConfiguration().gateway.c_str(),
  250. GetNetworkConfiguration().dns1.c_str(),
  251. GetNetworkConfiguration().dns2.c_str(),
  252. serverIp.c_str());
  253. std::string html(content);
  254. shttpd_printf(arg, "%s", html.c_str());
  255. if (html.empty()) {
  256. shttpd_printf(arg, "%s", "read file failed");
  257. }
  258. arg->flags |= SHTTPD_END_OF_OUTPUT;
  259. }
  260. struct state {
  261. size_t cl; /* Content-Length */
  262. size_t nread; /* Number of bytes read */
  263. FILE *fp;
  264. size_t file_length;
  265. multipart_reader *reader;
  266. HttpServer* server;
  267. bool is_tf_mounted;
  268. };
  269. static void
  270. on_form_data_receive(const multipart_reader* reader, const char* data, uint64_t data_length) {
  271. // LOGD("write form data [%s], filename = [%s] length %lld", reader->form_data_name, reader->form_data_filename, data_length);
  272. if (strcmp(reader->form_data_name, "uploadFile") != 0) {
  273. return;
  274. }
  275. if (data_length == 0) {
  276. return;
  277. }
  278. if (reader->user_data == NULL) {
  279. return;
  280. }
  281. struct state* state = (struct state*)reader->user_data;
  282. if (state->fp == NULL) {
  283. if (!state->is_tf_mounted) {
  284. LOGD("未插入SD卡");
  285. return;
  286. }
  287. state->fp = fopen(srv::format("/mnt/extsd/%s", reader->form_data_filename).c_str(), "wb");
  288. if (state->fp == NULL) {
  289. LOGE("创建文件失败");
  290. return;
  291. }
  292. }
  293. state->file_length += data_length;
  294. if (data_length != fwrite(data, 1, data_length, state->fp)) {
  295. LOGE("write form data failed");
  296. return;
  297. }
  298. }
  299. static void
  300. upload_file(struct shttpd_arg *arg)
  301. {
  302. const char *s;
  303. const char* request_method = shttpd_get_env(arg, "REQUEST_METHOD");
  304. if (strcmp(request_method, "POST") != 0) {
  305. return;
  306. }
  307. /* If the connection was broken prematurely, cleanup */
  308. if ((arg->flags & SHTTPD_CONNECTION_ERROR) && arg->state) {
  309. struct state* state = (struct state*) arg->state;
  310. if (state->fp) {
  311. fclose(state->fp);
  312. }
  313. sync();
  314. multipart_reader_destroy(state->reader);
  315. free(state);
  316. } else if ((s = shttpd_get_header(arg, "Content-Length")) == NULL) {
  317. shttpd_printf(arg, "HTTP/1.0 411 Length Required\n\n");
  318. arg->flags |= SHTTPD_END_OF_OUTPUT;
  319. } else if (arg->state == NULL) {
  320. /* New request. Allocate a state structure, and open a file */
  321. struct state* state = (struct state*)calloc(1, sizeof(*state));
  322. arg->state = state;
  323. state->cl = strtoul(s, NULL, 10);
  324. state->server = (HttpServer*)arg->user_data;
  325. state->is_tf_mounted = MOUNTMONITOR->isMount();
  326. std::string boundary = get_boundary(arg);
  327. if (!boundary.empty()) {
  328. LOGD("boundary=%s", boundary.c_str());
  329. }
  330. state->reader = multipart_reader_create(boundary.c_str(), on_form_data_receive, state);
  331. shttpd_printf(arg, "HTTP/1.0 200 OK\n"
  332. "Content-Type: text/plain\n\n");
  333. } else {
  334. struct state* state = (struct state*)arg->state;
  335. if(0 != multipart_reader_execute(state->reader, arg->in.buf, arg->in.len)) {
  336. LOGE("multipart_parser failed");
  337. }
  338. state->nread += arg->in.len;
  339. /* Tell SHTTPD we have processed all data */
  340. arg->in.num_bytes = arg->in.len;
  341. if (state->server->upload_filename_listener()) {
  342. state->server->upload_filename_listener()(state->reader->form_data_filename);
  343. }
  344. if (state->server->upload_progress_listener()) {
  345. state->server->upload_progress_listener()(
  346. (state->nread > state->cl) ? state->cl : state->nread,
  347. state->cl);
  348. }
  349. /* Data stream finished? Close the file, and free the state */
  350. if (state->nread >= state->cl) {
  351. shttpd_printf(arg, "Written %d bytes", state->file_length);
  352. if (!state->is_tf_mounted) {
  353. shttpd_printf(arg, ", No TF card is mounted!");
  354. }
  355. LOGD("file length = %d", state->file_length);
  356. if (state->fp) {
  357. fflush(state->fp);
  358. fclose(state->fp);
  359. }
  360. sync();
  361. free(state);
  362. arg->flags |= SHTTPD_END_OF_OUTPUT;
  363. }
  364. }
  365. }
  366. static void
  367. setting(struct shttpd_arg *arg){
  368. char dhcp[10] = {0};
  369. char ip[64] = {0};
  370. char netmask[64] = {0};
  371. char gateway[64] = {0};
  372. char dns1[64] = {0};
  373. char dns2[64] = {0};
  374. char serverIp[64] = {0};
  375. const char *s;
  376. const char* request_method = shttpd_get_env(arg, "REQUEST_METHOD");
  377. //仅接受post
  378. if (strcmp(request_method, "POST") != 0) {
  379. return;
  380. }
  381. /* If the connection was broken prematurely, cleanup */
  382. if ((arg->flags & SHTTPD_CONNECTION_ERROR) && arg->state) {
  383. struct state* state = (struct state*) arg->state;
  384. if (state->fp) {
  385. fclose(state->fp);
  386. }
  387. sync();
  388. free(state);
  389. } else if ((s = shttpd_get_header(arg, "Content-Length")) == NULL) {
  390. shttpd_printf(arg, "HTTP/1.0 411 Length Required\n\n");
  391. arg->flags |= SHTTPD_END_OF_OUTPUT;
  392. } else if (arg->state == NULL) {
  393. /* New request. Allocate a state structure, and open a file */
  394. struct state* state = (struct state*)calloc(1, sizeof(*state));
  395. arg->state = state;
  396. state->cl = strtoul(s, NULL, 10);
  397. state->server = (HttpServer*)arg->user_data;
  398. shttpd_get_var("dhcp", arg->in.buf, arg->in.len,
  399. dhcp, sizeof(dhcp));
  400. LOGD(">>>>>>>>>>>>> dhcp %s", dhcp);
  401. shttpd_get_var("ip", arg->in.buf, arg->in.len,
  402. ip, sizeof(ip));
  403. LOGD(">>>>>>>>>>>>> ip %s", ip);
  404. shttpd_get_var("netmask", arg->in.buf, arg->in.len,
  405. netmask, sizeof(netmask));
  406. LOGD(">>>>>>>>>>>>> netmask %s", netmask);
  407. shttpd_get_var("gateway", arg->in.buf, arg->in.len,
  408. gateway, sizeof(gateway));
  409. LOGD(">>>>>>>>>>>>> gateway %s", gateway);
  410. shttpd_get_var("dns1", arg->in.buf, arg->in.len,
  411. dns1, sizeof(dns1));
  412. LOGD(">>>>>>>>>>>>> dns1 %s", dns1);
  413. shttpd_get_var("dns2", arg->in.buf, arg->in.len,
  414. dns2, sizeof(dns2));
  415. LOGD(">>>>>>>>>>>>> dns2 %s", dns2);
  416. shttpd_get_var("server_ip", arg->in.buf, arg->in.len,
  417. serverIp, sizeof(serverIp));
  418. LOGD(">>>>>>>>>>>>> server ip %s", serverIp);
  419. std::string content = read_file(CONFIGMANAGER->getResFilePath("html/setting_result.html"));
  420. // std::string _ip = ip;
  421. // std::string _netmask = netmask;
  422. // std::string _gateway = gateway;
  423. // std::string _dns1 = dns1;
  424. // std::string _dns2 = dns2;
  425. // std::string _serverIp = serverIp;
  426. std::string msg = "setting ok. rebooting... pls wait.";
  427. if (!checkAddr(ip)){
  428. msg = "ip wrong input";
  429. } else if (!checkAddr(netmask)){
  430. msg = "netmask wrong input";
  431. } else if (!checkAddr(gateway)){
  432. msg = "gateway wrong input";
  433. } else if (!checkAddr(serverIp)){
  434. msg = "server_ip wrong input";
  435. } else {
  436. std::string _dhcp = dhcp;
  437. if (_dhcp == "1"){
  438. ETHERNETMANAGER->setAutoMode(true);
  439. } else {
  440. ETHERNETMANAGER->setAutoMode(false);
  441. ETHERNETMANAGER->configure(ip, netmask, gateway, dns1, dns2);
  442. }
  443. StoragePreferences::putString(STORE_GATEWAY, serverIp);
  444. }
  445. content = srv::format(content.c_str(), msg.c_str());
  446. shttpd_printf(arg, "%s", "HTTP/1.1 200 OK\r\n");
  447. shttpd_printf(arg, "%s", "Content-Type: text/html\r\n\r\n");
  448. std::string html(content);
  449. shttpd_printf(arg, "%s", html.c_str());
  450. if (html.empty()) {
  451. shttpd_printf(arg, "%s", "read file failed");
  452. }
  453. arg->flags |= SHTTPD_END_OF_OUTPUT;
  454. my_thread.run("reboot");
  455. } else {
  456. }
  457. }
  458. /*
  459. * This callback function is used to show how to handle 404 error
  460. */
  461. static void
  462. show_404(struct shttpd_arg *arg)
  463. {
  464. shttpd_printf(arg, "%s", "HTTP/1.1 200 OK\r\n");
  465. shttpd_printf(arg, "%s", "Content-Type: text/plain\r\n\r\n");
  466. shttpd_printf(arg, "%s", "Oops. File not found! ");
  467. shttpd_printf(arg, "%s", "This is a custom error handler.");
  468. arg->flags |= SHTTPD_END_OF_OUTPUT;
  469. }
  470. /*
  471. * Make sure we have ho zombies from CGIs
  472. */
  473. static void
  474. signal_handler(int sig_num)
  475. {
  476. switch (sig_num) {
  477. #ifndef _WIN32
  478. case SIGCHLD:
  479. while (waitpid(-1, &sig_num, WNOHANG) > 0) ;
  480. break;
  481. #endif /* !_WIN32 */
  482. default:
  483. break;
  484. }
  485. }
  486. HttpServer::HttpServer() {
  487. stop_ = false;
  488. port_ = 80;
  489. upload_filename_listener_ = NULL;
  490. upload_progress_listener_ = NULL;
  491. }
  492. HttpServer::~HttpServer() {
  493. }
  494. bool HttpServer::threadLoop() {
  495. stop_ = false;
  496. RunSync(port_);
  497. return false;
  498. }
  499. void HttpServer::RunAsync(int port) {
  500. port_ = port;
  501. stop_ = false;
  502. run("shttpd");
  503. }
  504. int HttpServer::RunSync(int port) {
  505. struct shttpd_ctx *ctx;
  506. #ifndef _WIN32
  507. signal(SIGPIPE, SIG_IGN);
  508. signal(SIGCHLD, &signal_handler);
  509. #endif /* !_WIN32 */
  510. /*
  511. * Initialize SHTTPD context.
  512. * Start listening on ports 8080 and 8081
  513. */
  514. ctx = shttpd_init(0, NULL);
  515. shttpd_set_option(ctx, "ports", format("%d", port).c_str());
  516. /* 注册uri和它的回调函数*/
  517. shttpd_register_uri(ctx, "/", &show_index, NULL);
  518. shttpd_register_uri(ctx, "/setting", &setting, this);
  519. shttpd_handle_error(ctx, 404, show_404, NULL);
  520. /* Serve connections infinitely until someone kills us */
  521. while (!stop_) {
  522. shttpd_poll(ctx, 1000);
  523. }
  524. /* Probably unreached, because we will be killed by a signal */
  525. shttpd_fini(ctx);
  526. return 0;
  527. }
  528. void HttpServer::Stop() {
  529. stop_ = true;
  530. requestExitAndWait();
  531. stop_ = false;
  532. }
  533. void HttpServer::set_upload_filename_listener(UploadFilenameListener listener) {
  534. upload_filename_listener_ = listener;
  535. }
  536. void HttpServer::set_upload_progress_listener(UploadProgressListener listener) {
  537. upload_progress_listener_ = listener;
  538. }
  539. HttpServer::UploadFilenameListener HttpServer::upload_filename_listener() {
  540. return upload_filename_listener_;
  541. }
  542. HttpServer::UploadProgressListener HttpServer::upload_progress_listener() {
  543. return upload_progress_listener_;
  544. }
  545. } /* namespace srv */