http_server.cpp 16 KB

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