coap.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. // Module for coapwork
  2. #include "module.h"
  3. #include "lauxlib.h"
  4. #include "platform.h"
  5. #include "c_string.h"
  6. #include "c_stdlib.h"
  7. #include "c_types.h"
  8. #include "mem.h"
  9. #include "lwip/ip_addr.h"
  10. #include "espconn.h"
  11. #include "driver/uart.h"
  12. #include "coap.h"
  13. #include "uri.h"
  14. #include "node.h"
  15. #include "coap_timer.h"
  16. #include "coap_io.h"
  17. #include "coap_server.h"
  18. coap_queue_t *gQueue = NULL;
  19. typedef struct lcoap_userdata
  20. {
  21. struct espconn *pesp_conn;
  22. int self_ref;
  23. }lcoap_userdata;
  24. static void coap_received(void *arg, char *pdata, unsigned short len)
  25. {
  26. NODE_DBG("coap_received is called.\n");
  27. struct espconn *pesp_conn = arg;
  28. lcoap_userdata *cud = (lcoap_userdata *)pesp_conn->reverse;
  29. // static uint8_t buf[MAX_MESSAGE_SIZE+1] = {0}; // +1 for string '\0'
  30. uint8_t buf[MAX_MESSAGE_SIZE+1] = {0}; // +1 for string '\0'
  31. c_memset(buf, 0, sizeof(buf)); // wipe prev data
  32. if (len > MAX_MESSAGE_SIZE) {
  33. NODE_DBG("Request Entity Too Large.\n"); // NOTE: should response 4.13 to client...
  34. return;
  35. }
  36. // c_memcpy(buf, pdata, len);
  37. size_t rsplen = coap_server_respond(pdata, len, buf, MAX_MESSAGE_SIZE+1);
  38. // SDK 1.4.0 changed behaviour, for UDP server need to look up remote ip/port
  39. remot_info *pr = 0;
  40. if (espconn_get_connection_info (pesp_conn, &pr, 0) != ESPCONN_OK)
  41. return;
  42. pesp_conn->proto.udp->remote_port = pr->remote_port;
  43. os_memmove (pesp_conn->proto.udp->remote_ip, pr->remote_ip, 4);
  44. // The remot_info apparently should *not* be os_free()d, fyi
  45. espconn_sent(pesp_conn, (unsigned char *)buf, rsplen);
  46. // c_memset(buf, 0, sizeof(buf));
  47. }
  48. static void coap_sent(void *arg)
  49. {
  50. NODE_DBG("coap_sent is called.\n");
  51. }
  52. // Lua: s = coap.create(function(conn))
  53. static int coap_create( lua_State* L, const char* mt )
  54. {
  55. struct espconn *pesp_conn = NULL;
  56. lcoap_userdata *cud;
  57. unsigned type;
  58. int stack = 1;
  59. // create a object
  60. cud = (lcoap_userdata *)lua_newuserdata(L, sizeof(lcoap_userdata));
  61. // pre-initialize it, in case of errors
  62. cud->self_ref = LUA_NOREF;
  63. cud->pesp_conn = NULL;
  64. // set its metatable
  65. luaL_getmetatable(L, mt);
  66. lua_setmetatable(L, -2);
  67. // create the espconn struct
  68. pesp_conn = (struct espconn *)c_zalloc(sizeof(struct espconn));
  69. if(!pesp_conn)
  70. return luaL_error(L, "not enough memory");
  71. cud->pesp_conn = pesp_conn;
  72. pesp_conn->type = ESPCONN_UDP;
  73. pesp_conn->proto.tcp = NULL;
  74. pesp_conn->proto.udp = NULL;
  75. pesp_conn->proto.udp = (esp_udp *)c_zalloc(sizeof(esp_udp));
  76. if(!pesp_conn->proto.udp){
  77. c_free(pesp_conn);
  78. cud->pesp_conn = pesp_conn = NULL;
  79. return luaL_error(L, "not enough memory");
  80. }
  81. pesp_conn->state = ESPCONN_NONE;
  82. NODE_DBG("UDP server/client is set.\n");
  83. pesp_conn->reverse = cud;
  84. NODE_DBG("coap_create is called.\n");
  85. return 1;
  86. }
  87. // Lua: server:delete()
  88. static int coap_delete( lua_State* L, const char* mt )
  89. {
  90. struct espconn *pesp_conn = NULL;
  91. lcoap_userdata *cud;
  92. cud = (lcoap_userdata *)luaL_checkudata(L, 1, mt);
  93. luaL_argcheck(L, cud, 1, "Server/Client expected");
  94. if(cud==NULL){
  95. NODE_DBG("userdata is nil.\n");
  96. return 0;
  97. }
  98. // free (unref) callback ref
  99. if(LUA_NOREF!=cud->self_ref){
  100. luaL_unref(L, LUA_REGISTRYINDEX, cud->self_ref);
  101. cud->self_ref = LUA_NOREF;
  102. }
  103. if(cud->pesp_conn)
  104. {
  105. if(cud->pesp_conn->proto.udp->remote_port || cud->pesp_conn->proto.udp->local_port)
  106. espconn_delete(cud->pesp_conn);
  107. c_free(cud->pesp_conn->proto.udp);
  108. cud->pesp_conn->proto.udp = NULL;
  109. c_free(cud->pesp_conn);
  110. cud->pesp_conn = NULL;
  111. }
  112. NODE_DBG("coap_delete is called.\n");
  113. return 0;
  114. }
  115. // Lua: server:listen( port, ip )
  116. static int coap_start( lua_State* L, const char* mt )
  117. {
  118. struct espconn *pesp_conn = NULL;
  119. lcoap_userdata *cud;
  120. unsigned port;
  121. size_t il;
  122. ip_addr_t ipaddr;
  123. cud = (lcoap_userdata *)luaL_checkudata(L, 1, mt);
  124. luaL_argcheck(L, cud, 1, "Server/Client expected");
  125. if(cud==NULL){
  126. NODE_DBG("userdata is nil.\n");
  127. return 0;
  128. }
  129. pesp_conn = cud->pesp_conn;
  130. port = luaL_checkinteger( L, 2 );
  131. pesp_conn->proto.udp->local_port = port;
  132. NODE_DBG("UDP port is set: %d.\n", port);
  133. if( lua_isstring(L,3) ) // deal with the ip string
  134. {
  135. const char *ip = luaL_checklstring( L, 3, &il );
  136. if (ip == NULL)
  137. {
  138. ip = "0.0.0.0";
  139. }
  140. ipaddr.addr = ipaddr_addr(ip);
  141. c_memcpy(pesp_conn->proto.udp->local_ip, &ipaddr.addr, 4);
  142. NODE_DBG("UDP ip is set: ");
  143. NODE_DBG(IPSTR, IP2STR(&ipaddr.addr));
  144. NODE_DBG("\n");
  145. }
  146. if(LUA_NOREF==cud->self_ref){
  147. lua_pushvalue(L, 1); // copy to the top of stack
  148. cud->self_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  149. }
  150. espconn_regist_recvcb(pesp_conn, coap_received);
  151. espconn_regist_sentcb(pesp_conn, coap_sent);
  152. espconn_create(pesp_conn);
  153. NODE_DBG("Coap Server started on port: %d\n", port);
  154. NODE_DBG("coap_start is called.\n");
  155. return 0;
  156. }
  157. // Lua: server:close()
  158. static int coap_close( lua_State* L, const char* mt )
  159. {
  160. struct espconn *pesp_conn = NULL;
  161. lcoap_userdata *cud;
  162. cud = (lcoap_userdata *)luaL_checkudata(L, 1, mt);
  163. luaL_argcheck(L, cud, 1, "Server/Client expected");
  164. if(cud==NULL){
  165. NODE_DBG("userdata is nil.\n");
  166. return 0;
  167. }
  168. if(cud->pesp_conn)
  169. {
  170. if(cud->pesp_conn->proto.udp->remote_port || cud->pesp_conn->proto.udp->local_port)
  171. espconn_delete(cud->pesp_conn);
  172. }
  173. if(LUA_NOREF!=cud->self_ref){
  174. luaL_unref(L, LUA_REGISTRYINDEX, cud->self_ref);
  175. cud->self_ref = LUA_NOREF;
  176. }
  177. NODE_DBG("coap_close is called.\n");
  178. return 0;
  179. }
  180. // Lua: server/client:on( "method", function(s) )
  181. static int coap_on( lua_State* L, const char* mt )
  182. {
  183. NODE_DBG("coap_on is called.\n");
  184. return 0;
  185. }
  186. static void coap_response_handler(void *arg, char *pdata, unsigned short len)
  187. {
  188. NODE_DBG("coap_response_handler is called.\n");
  189. struct espconn *pesp_conn = arg;
  190. coap_packet_t pkt;
  191. pkt.content.p = NULL;
  192. pkt.content.len = 0;
  193. // static uint8_t buf[MAX_MESSAGE_SIZE+1] = {0}; // +1 for string '\0'
  194. uint8_t buf[MAX_MESSAGE_SIZE+1] = {0}; // +1 for string '\0'
  195. c_memset(buf, 0, sizeof(buf)); // wipe prev data
  196. int rc;
  197. if( len > MAX_MESSAGE_SIZE )
  198. {
  199. NODE_DBG("Request Entity Too Large.\n"); // NOTE: should response 4.13 to client...
  200. return;
  201. }
  202. c_memcpy(buf, pdata, len);
  203. if (0 != (rc = coap_parse(&pkt, buf, len))){
  204. NODE_DBG("Bad packet rc=%d\n", rc);
  205. }
  206. else
  207. {
  208. #ifdef COAP_DEBUG
  209. coap_dumpPacket(&pkt);
  210. #endif
  211. /* check if this is a response to our original request */
  212. if (!check_token(&pkt)) {
  213. /* drop if this was just some message, or send RST in case of notification */
  214. if (pkt.hdr.t == COAP_TYPE_CON || pkt.hdr.t == COAP_TYPE_NONCON){
  215. // coap_send_rst(pkt); // send RST response
  216. // or, just ignore it.
  217. }
  218. goto end;
  219. }
  220. if (pkt.hdr.t == COAP_TYPE_RESET) {
  221. NODE_DBG("got RST\n");
  222. goto end;
  223. }
  224. uint32_t ip = 0, port = 0;
  225. coap_tid_t id = COAP_INVALID_TID;
  226. c_memcpy(&ip, pesp_conn->proto.udp->remote_ip, sizeof(ip));
  227. port = pesp_conn->proto.udp->remote_port;
  228. coap_transaction_id(ip, port, &pkt, &id);
  229. /* transaction done, remove the node from queue */
  230. // stop timer
  231. coap_timer_stop();
  232. // remove the node
  233. coap_remove_node(&gQueue, id);
  234. // calculate time elapsed
  235. coap_timer_update(&gQueue);
  236. coap_timer_start(&gQueue);
  237. if (COAP_RESPONSE_CLASS(pkt.hdr.code) == 2)
  238. {
  239. /* There is no block option set, just read the data and we are done. */
  240. NODE_DBG("%d.%02d\t", (pkt.hdr.code >> 5), pkt.hdr.code & 0x1F);
  241. NODE_DBG((char *)pkt.payload.p);
  242. }
  243. else if (COAP_RESPONSE_CLASS(pkt.hdr.code) >= 4)
  244. {
  245. NODE_DBG("%d.%02d\t", (pkt.hdr.code >> 5), pkt.hdr.code & 0x1F);
  246. NODE_DBG((char *)pkt.payload.p);
  247. }
  248. }
  249. end:
  250. if(!gQueue){ // if there is no node pending in the queue, disconnect from host.
  251. if(pesp_conn->proto.udp->remote_port || pesp_conn->proto.udp->local_port)
  252. espconn_delete(pesp_conn);
  253. }
  254. // c_memset(buf, 0, sizeof(buf));
  255. }
  256. // Lua: client:request( [CON], uri, [payload] )
  257. static int coap_request( lua_State* L, coap_method_t m )
  258. {
  259. struct espconn *pesp_conn = NULL;
  260. lcoap_userdata *cud;
  261. int stack = 1;
  262. cud = (lcoap_userdata *)luaL_checkudata(L, stack, "coap_client");
  263. luaL_argcheck(L, cud, stack, "Server/Client expected");
  264. if(cud==NULL){
  265. NODE_DBG("userdata is nil.\n");
  266. return 0;
  267. }
  268. stack++;
  269. pesp_conn = cud->pesp_conn;
  270. ip_addr_t ipaddr;
  271. uint8_t host[64];
  272. unsigned t;
  273. if ( lua_isnumber(L, stack) )
  274. {
  275. t = lua_tointeger(L, stack);
  276. stack++;
  277. if ( t != COAP_TYPE_CON && t != COAP_TYPE_NONCON )
  278. return luaL_error( L, "wrong arg type" );
  279. } else {
  280. t = COAP_TYPE_CON; // default to CON
  281. }
  282. size_t l;
  283. const char *url = luaL_checklstring( L, stack, &l );
  284. stack++;
  285. if (url == NULL)
  286. return luaL_error( L, "wrong arg type" );
  287. coap_uri_t *uri = coap_new_uri(url, l); // should call free(uri) somewhere
  288. if (uri == NULL)
  289. return luaL_error( L, "uri wrong format." );
  290. if (uri->host.length + 1 /* for the null */ > sizeof(host)) {
  291. return luaL_error(L, "host too long");
  292. }
  293. pesp_conn->proto.udp->remote_port = uri->port;
  294. NODE_DBG("UDP port is set: %d.\n", uri->port);
  295. pesp_conn->proto.udp->local_port = espconn_port();
  296. if(uri->host.length){
  297. c_memcpy(host, uri->host.s, uri->host.length);
  298. host[uri->host.length] = '\0';
  299. ipaddr.addr = ipaddr_addr(host);
  300. NODE_DBG("Host len(%d):", uri->host.length);
  301. NODE_DBG(host);
  302. NODE_DBG("\n");
  303. c_memcpy(pesp_conn->proto.udp->remote_ip, &ipaddr.addr, 4);
  304. NODE_DBG("UDP ip is set: ");
  305. NODE_DBG(IPSTR, IP2STR(&ipaddr.addr));
  306. NODE_DBG("\n");
  307. }
  308. coap_pdu_t *pdu = coap_new_pdu(); // should call coap_delete_pdu() somewhere
  309. if(!pdu){
  310. if(uri)
  311. c_free(uri);
  312. return luaL_error (L, "alloc fail");
  313. }
  314. const char *payload = NULL;
  315. l = 0;
  316. if( lua_isstring(L, stack) ){
  317. payload = luaL_checklstring( L, stack, &l );
  318. if (payload == NULL)
  319. l = 0;
  320. }
  321. coap_make_request(&(pdu->scratch), pdu->pkt, t, m, uri, payload, l);
  322. #ifdef COAP_DEBUG
  323. coap_dumpPacket(pdu->pkt);
  324. #endif
  325. int rc;
  326. if (0 != (rc = coap_build(pdu->msg.p, &(pdu->msg.len), pdu->pkt))){
  327. NODE_DBG("coap_build failed rc=%d\n", rc);
  328. }
  329. else
  330. {
  331. #ifdef COAP_DEBUG
  332. NODE_DBG("Sending: ");
  333. coap_dump(pdu->msg.p, pdu->msg.len, true);
  334. NODE_DBG("\n");
  335. #endif
  336. espconn_regist_recvcb(pesp_conn, coap_response_handler);
  337. sint8_t con = espconn_create(pesp_conn);
  338. if( ESPCONN_OK != con){
  339. NODE_DBG("Connect to host. code:%d\n", con);
  340. // coap_delete_pdu(pdu);
  341. }
  342. // else
  343. {
  344. coap_tid_t tid = COAP_INVALID_TID;
  345. if (pdu->pkt->hdr.t == COAP_TYPE_CON){
  346. tid = coap_send_confirmed(pesp_conn, pdu);
  347. }
  348. else {
  349. tid = coap_send(pesp_conn, pdu);
  350. }
  351. if (pdu->pkt->hdr.t != COAP_TYPE_CON || tid == COAP_INVALID_TID){
  352. coap_delete_pdu(pdu);
  353. }
  354. }
  355. }
  356. if(uri)
  357. c_free((void *)uri);
  358. NODE_DBG("coap_request is called.\n");
  359. return 0;
  360. }
  361. extern coap_luser_entry *variable_entry;
  362. extern coap_luser_entry *function_entry;
  363. // Lua: coap:var/func( string )
  364. static int coap_regist( lua_State* L, const char* mt, int isvar )
  365. {
  366. size_t l;
  367. const char *name = luaL_checklstring( L, 2, &l );
  368. int content_type = luaL_optint(L, 3, COAP_CONTENTTYPE_TEXT_PLAIN);
  369. if (name == NULL)
  370. return luaL_error( L, "name must be set." );
  371. coap_luser_entry *h = NULL;
  372. // if(lua_isstring(L, 3))
  373. if(isvar)
  374. h = variable_entry;
  375. else
  376. h = function_entry;
  377. while(NULL!=h->next){ // goto the end of the list
  378. if(h->name!= NULL && c_strcmp(h->name, name)==0) // key exist, override it
  379. break;
  380. h = h->next;
  381. }
  382. if(h->name==NULL || c_strcmp(h->name, name)!=0){ // not exists. make a new one.
  383. h->next = (coap_luser_entry *)c_zalloc(sizeof(coap_luser_entry));
  384. h = h->next;
  385. if(h == NULL)
  386. return luaL_error(L, "not enough memory");
  387. h->next = NULL;
  388. h->name = NULL;
  389. }
  390. h->name = name;
  391. h->content_type = content_type;
  392. NODE_DBG("coap_regist is called.\n");
  393. return 0;
  394. }
  395. // Lua: s = coap.createServer(function(conn))
  396. static int coap_createServer( lua_State* L )
  397. {
  398. const char *mt = "coap_server";
  399. return coap_create(L, mt);
  400. }
  401. // Lua: server:delete()
  402. static int coap_server_delete( lua_State* L )
  403. {
  404. const char *mt = "coap_server";
  405. return coap_delete(L, mt);
  406. }
  407. // Lua: server:listen( port, ip, function(err) )
  408. static int coap_server_listen( lua_State* L )
  409. {
  410. const char *mt = "coap_server";
  411. return coap_start(L, mt);
  412. }
  413. // Lua: server:close()
  414. static int coap_server_close( lua_State* L )
  415. {
  416. const char *mt = "coap_server";
  417. return coap_close(L, mt);
  418. }
  419. // Lua: server:on( "method", function(server) )
  420. static int coap_server_on( lua_State* L )
  421. {
  422. const char *mt = "coap_server";
  423. return coap_on(L, mt);
  424. }
  425. // Lua: server:var( "name" )
  426. static int coap_server_var( lua_State* L )
  427. {
  428. const char *mt = "coap_server";
  429. return coap_regist(L, mt, 1);
  430. }
  431. // Lua: server:func( "name" )
  432. static int coap_server_func( lua_State* L )
  433. {
  434. const char *mt = "coap_server";
  435. return coap_regist(L, mt, 0);
  436. }
  437. // Lua: s = coap.createClient(function(conn))
  438. static int coap_createClient( lua_State* L )
  439. {
  440. const char *mt = "coap_client";
  441. return coap_create(L, mt);
  442. }
  443. // Lua: client:gcdelete()
  444. static int coap_client_gcdelete( lua_State* L )
  445. {
  446. const char *mt = "coap_client";
  447. return coap_delete(L, mt);
  448. }
  449. // client:get( string, function(sent) )
  450. static int coap_client_get( lua_State* L )
  451. {
  452. return coap_request(L, COAP_METHOD_GET);
  453. }
  454. // client:post( string, function(sent) )
  455. static int coap_client_post( lua_State* L )
  456. {
  457. return coap_request(L, COAP_METHOD_POST);
  458. }
  459. // client:put( string, function(sent) )
  460. static int coap_client_put( lua_State* L )
  461. {
  462. return coap_request(L, COAP_METHOD_PUT);
  463. }
  464. // client:delete( string, function(sent) )
  465. static int coap_client_delete( lua_State* L )
  466. {
  467. return coap_request(L, COAP_METHOD_DELETE);
  468. }
  469. // Module function map
  470. static const LUA_REG_TYPE coap_server_map[] = {
  471. { LSTRKEY( "listen" ), LFUNCVAL( coap_server_listen ) },
  472. { LSTRKEY( "close" ), LFUNCVAL( coap_server_close ) },
  473. { LSTRKEY( "var" ), LFUNCVAL( coap_server_var ) },
  474. { LSTRKEY( "func" ), LFUNCVAL( coap_server_func ) },
  475. { LSTRKEY( "__gc" ), LFUNCVAL( coap_server_delete ) },
  476. { LSTRKEY( "__index" ), LROVAL( coap_server_map ) },
  477. { LNILKEY, LNILVAL }
  478. };
  479. static const LUA_REG_TYPE coap_client_map[] = {
  480. { LSTRKEY( "get" ), LFUNCVAL( coap_client_get ) },
  481. { LSTRKEY( "post" ), LFUNCVAL( coap_client_post ) },
  482. { LSTRKEY( "put" ), LFUNCVAL( coap_client_put ) },
  483. { LSTRKEY( "delete" ), LFUNCVAL( coap_client_delete ) },
  484. { LSTRKEY( "__gc" ), LFUNCVAL( coap_client_gcdelete ) },
  485. { LSTRKEY( "__index" ), LROVAL( coap_client_map ) },
  486. { LNILKEY, LNILVAL }
  487. };
  488. static const LUA_REG_TYPE coap_map[] =
  489. {
  490. { LSTRKEY( "Server" ), LFUNCVAL( coap_createServer ) },
  491. { LSTRKEY( "Client" ), LFUNCVAL( coap_createClient ) },
  492. { LSTRKEY( "CON" ), LNUMVAL( COAP_TYPE_CON ) },
  493. { LSTRKEY( "NON" ), LNUMVAL( COAP_TYPE_NONCON ) },
  494. { LSTRKEY( "TEXT_PLAIN"), LNUMVAL( COAP_CONTENTTYPE_TEXT_PLAIN ) },
  495. { LSTRKEY( "LINKFORMAT"), LNUMVAL( COAP_CONTENTTYPE_APPLICATION_LINKFORMAT ) },
  496. { LSTRKEY( "XML"), LNUMVAL( COAP_CONTENTTYPE_APPLICATION_XML ) },
  497. { LSTRKEY( "OCTET_STREAM"), LNUMVAL( COAP_CONTENTTYPE_APPLICATION_OCTET_STREAM ) },
  498. { LSTRKEY( "EXI"), LNUMVAL( COAP_CONTENTTYPE_APPLICATION_EXI ) },
  499. { LSTRKEY( "JSON"), LNUMVAL( COAP_CONTENTTYPE_APPLICATION_JSON) },
  500. { LSTRKEY( "__metatable" ), LROVAL( coap_map ) },
  501. { LNILKEY, LNILVAL }
  502. };
  503. int luaopen_coap( lua_State *L )
  504. {
  505. endpoint_setup();
  506. luaL_rometatable(L, "coap_server", (void *)coap_server_map); // create metatable for coap_server
  507. luaL_rometatable(L, "coap_client", (void *)coap_client_map); // create metatable for coap_client
  508. return 0;
  509. }
  510. NODEMCU_MODULE(COAP, "coap", coap_map, luaopen_coap);