luat_lib_libcoap.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. /*
  2. @module libcoap
  3. @summary coap数据处理
  4. @version 1.0
  5. @date 2020.06.30
  6. */
  7. #include "luat_base.h"
  8. #include "luat_timer.h"
  9. #include "luat_malloc.h"
  10. #include "luat_msgbus.h"
  11. #define LUAT_LOG_TAG "luat.libcoap"
  12. #include "luat_log.h"
  13. //---------------------------
  14. #ifndef COAP_OPTION_IF_MATCH
  15. #define COAP_OPTION_IF_MATCH 1 /* C, opaque, 0-8 B, (none) */
  16. #define COAP_OPTION_URI_HOST 3 /* C, String, 1-255 B, destination address */
  17. #define COAP_OPTION_ETAG 4 /* E, opaque, 1-8 B, (none) */
  18. #define COAP_OPTION_IF_NONE_MATCH 5 /* empty, 0 B, (none) */
  19. #define COAP_OPTION_URI_PORT 7 /* C, uint, 0-2 B, destination port */
  20. #define COAP_OPTION_LOCATION_PATH 8 /* E, String, 0-255 B, - */
  21. #define COAP_OPTION_URI_PATH 11 /* C, String, 0-255 B, (none) */
  22. #define COAP_OPTION_CONTENT_FORMAT 12 /* E, uint, 0-2 B, (none) */
  23. #define COAP_OPTION_CONTENT_TYPE COAP_OPTION_CONTENT_FORMAT
  24. #define COAP_OPTION_MAXAGE 14 /* E, uint, 0--4 B, 60 Seconds */
  25. #define COAP_OPTION_URI_QUERY 15 /* C, String, 1-255 B, (none) */
  26. #define COAP_OPTION_ACCEPT 17 /* C, uint, 0-2 B, (none) */
  27. #define COAP_OPTION_LOCATION_QUERY 20 /* E, String, 0-255 B, (none) */
  28. #define COAP_OPTION_SIZE2 28 /* E, uint, 0-4 B, (none) */
  29. #define COAP_OPTION_PROXY_URI 35 /* C, String, 1-1034 B, (none) */
  30. #define COAP_OPTION_PROXY_SCHEME 39 /* C, String, 1-255 B, (none) */
  31. #define COAP_OPTION_SIZE1 60 /* E, uint, 0-4 B, (none) */
  32. #define COAP_MEDIATYPE_TEXT_PLAIN 0 /* text/plain (UTF-8) */
  33. #define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT 40 /* application/link-format */
  34. #define COAP_MEDIATYPE_APPLICATION_XML 41 /* application/xml */
  35. #define COAP_MEDIATYPE_APPLICATION_OCTET_STREAM 42 /* application/octet-stream */
  36. #define COAP_MEDIATYPE_APPLICATION_RDF_XML 43 /* application/rdf+xml */
  37. #define COAP_MEDIATYPE_APPLICATION_EXI 47 /* application/exi */
  38. #define COAP_MEDIATYPE_APPLICATION_JSON 50 /* application/json */
  39. #define COAP_MEDIATYPE_APPLICATION_CBOR 60 /* application/cbor */
  40. #endif
  41. //---------------------------
  42. typedef struct libcoap_header
  43. {
  44. unsigned int tokenLen: 4 ;
  45. unsigned int type : 2 ; // 0 - CON, 1 - NON, 2 - ACK, 3 - RST
  46. unsigned int version : 2 ;
  47. uint8_t code;
  48. uint16_t msgid;
  49. }libcoap_header_t;
  50. typedef struct libcoap_opt_header
  51. {
  52. unsigned int opt_len : 4 ;
  53. unsigned int opt_delta : 4 ;
  54. }libcoap_opt_header_t;
  55. typedef struct luat_lib_libcoap
  56. {
  57. libcoap_header_t header;
  58. char token[9];
  59. size_t optSize;
  60. size_t dataSize;
  61. char opt[256];
  62. char data[512 - 128];
  63. }luat_lib_libcoap_t;
  64. static uint16_t c_msgid = 1;
  65. #define LUAT_COAP_HANDLE "COAP*"
  66. //-----------------------------------------------------------------
  67. static void addopt(luat_lib_libcoap_t* _coap, uint8_t opt_type, const char* value, size_t len) {
  68. if (_coap->optSize > 0) { // 检查需要之前的opt
  69. }
  70. int cur_opt = opt_type;
  71. // LLOGD("opt type=%d value len=%d", opt_type, len);
  72. // LLOGD("opt optSize cur=%d", _coap->optSize);
  73. size_t idx = _coap->optSize;
  74. if (len <= 12) {
  75. _coap->opt[idx++] = (cur_opt << 4) + (len & 0xF);
  76. }
  77. else if (len <= 268) {
  78. _coap->opt[idx++] = (cur_opt << 4) + (0x0D);
  79. _coap->opt[idx++] = len - 0x0D;
  80. } else {
  81. LLOGW("coap opt is too large!!! ignore!!!");
  82. return;
  83. }
  84. for (size_t i = 0; i < len; i++)
  85. {
  86. _coap->opt[idx++] = *(value + i);
  87. }
  88. _coap->optSize += idx;
  89. }
  90. /**
  91. 创建一个coap数据包
  92. @api libcoap.new(code, uri, headers, payload)
  93. @int coap的code, 例如libcoap.GET/libcoap.POST/libcoap.PUT/libcoap.DELETE
  94. @string 目标URI,必须填写, 不需要加上/开头
  95. @table 请求头,类似于http的headers,可选
  96. @string 请求体,类似于http的body,可选
  97. @return userdata coap数据包
  98. @usage
  99. -- 创建一个请求服务器time的数据包
  100. local coapdata = libcoap.new(libcoap.GET, "time")
  101. local data = coapdata:rawdata()
  102. */
  103. static int l_libcoap_new(lua_State* L) {
  104. luat_lib_libcoap_t* _coap;
  105. // 生成coap结构体
  106. _coap = (luat_lib_libcoap_t*)lua_newuserdata(L, sizeof(luat_lib_libcoap_t));
  107. if (_coap == NULL)
  108. {
  109. LLOGW("out of memory!!!");
  110. return 0;
  111. }
  112. memset(_coap, 0, sizeof(luat_lib_libcoap_t));
  113. _coap->header.version = 0x01;
  114. _coap->header.tokenLen = 0;
  115. _coap->header.msgid = c_msgid ++; // 设置msgid
  116. luaL_setmetatable(L, LUAT_COAP_HANDLE);
  117. // 然后根据用户参数设置
  118. // 首先,是code, 第1参数
  119. _coap->header.code = luaL_checkinteger(L, 1);
  120. // 肯定要设置URI的吧, 第2参数
  121. size_t len = 0;
  122. const char* uri = luaL_checklstring(L, 2, &len);
  123. addopt(_coap, 11, uri, len); // Uri-Path = 11
  124. // 设置其他OPT, 第3参数
  125. // TODO 是个table吧
  126. // 最后是data, 第4参数
  127. if (lua_isstring(L, 4)) {
  128. const char* payload = luaL_checklstring(L, 4, &len);
  129. if (len > 512) {
  130. LLOGE("data limit to 512 bytes");
  131. lua_pushstring(L, "data limit to 512 bytes");
  132. lua_error(L);
  133. }
  134. _coap->dataSize = len;
  135. memcpy(_coap->data, payload, len);
  136. }
  137. return 1;
  138. }
  139. /**
  140. 解析coap数据包
  141. @api libcoap.parse(str)
  142. @string coap数据包
  143. @return userdata coap数据包,如果解析失败会返回nil
  144. @usage
  145. -- 解析服务器传入的数据包
  146. local coapdata = libcoap.parse(indata)
  147. log.info("coapdata", coapdata:hcode(), coapdata:data())
  148. */
  149. static int l_libcoap_parse(lua_State* L) {
  150. size_t len;
  151. const char* buff = luaL_checklstring(L, 1, &len);
  152. if (len < 4) {
  153. return 0; // 最起码得有4个字节呀
  154. }
  155. libcoap_header_t *header = (libcoap_header_t *)buff; // 把头部搞一下
  156. if (header->version != 0x01) {
  157. LLOGW("bad coap version");
  158. return 0;
  159. }
  160. luat_lib_libcoap_t* _coap;
  161. // 生成coap结构体
  162. _coap = (luat_lib_libcoap_t*)lua_newuserdata(L, sizeof(luat_lib_libcoap_t));
  163. if (_coap == NULL)
  164. {
  165. LLOGE("out of memory at libcoap.parse");
  166. return 0;
  167. }
  168. memset(_coap, 0, sizeof(luat_lib_libcoap_t));
  169. memcpy(_coap, buff, 4);
  170. luaL_setmetatable(L, LUAT_COAP_HANDLE);
  171. int idx = 4;
  172. // 分析一下token
  173. if (_coap->header.tokenLen > 0) {
  174. memcpy(_coap->token, buff+len, _coap->header.tokenLen);
  175. idx += _coap->header.tokenLen;
  176. }
  177. // 准备一下指针
  178. char* ptr = (char*)buff;
  179. ptr += 4; // 跳过头部
  180. ptr += _coap->header.tokenLen;
  181. // 分析opt
  182. if (idx < len) {
  183. while (idx < len && *ptr != 0xFF) {
  184. libcoap_opt_header_t *opt_header = (libcoap_opt_header_t *)ptr;
  185. if (opt_header->opt_delta == 0xF)
  186. break;
  187. LLOGD("found opt %d %d", opt_header->opt_delta, opt_header->opt_len);
  188. if (opt_header->opt_len <= 12) {
  189. // nop
  190. }
  191. else if (opt_header->opt_len == 13) {
  192. opt_header->opt_len += (unsigned int)(*(ptr+1));
  193. }
  194. ptr += opt_header->opt_len + 1;
  195. idx += opt_header->opt_len + 1;
  196. _coap->optSize += opt_header->opt_len + 1;
  197. }
  198. LLOGD("opt size=%d", _coap->optSize);
  199. memcpy(_coap->opt, ptr - _coap->optSize, _coap->optSize);
  200. }
  201. // 分析一下data
  202. if (idx < len) {
  203. _coap->dataSize = len - idx - 1;
  204. LLOGD("data size=%d", _coap->dataSize);
  205. memcpy(_coap->data, ptr+1, _coap->dataSize);
  206. }
  207. return 1;
  208. }
  209. //---------------------------------------------
  210. #define tocoap(L) ((luat_lib_libcoap_t *)luaL_checkudata(L, 1, LUAT_COAP_HANDLE))
  211. /**
  212. 获取coap数据包的msgid
  213. @api coapdata:msgid()
  214. @return int coap数据包的msgid
  215. @usage
  216. -- 解析服务器传入的数据包
  217. local coapdata = libcoap.parse(indata)
  218. log.info("coapdata", coapdata:msgid())
  219. */
  220. static int libcoap_msgid(lua_State *L) {
  221. luat_lib_libcoap_t *_coap = tocoap(L);
  222. if (_coap == NULL) {
  223. LLOGE("coap sturt is NULL");
  224. lua_pushstring(L, "coap sturt is NULL");
  225. lua_error(L);
  226. return 0;
  227. }
  228. lua_pushinteger(L, _coap->header.msgid);
  229. return 1;
  230. }
  231. /**
  232. 获取coap数据包的token
  233. @api coapdata:token()
  234. @return string coap数据包的token
  235. @usage
  236. -- 解析服务器传入的数据包
  237. local coapdata = libcoap.parse(indata)
  238. log.info("coapdata", coapdata:token())
  239. */
  240. static int libcoap_token(lua_State *L) {
  241. luat_lib_libcoap_t *_coap = tocoap(L);
  242. if (_coap == NULL) {
  243. LLOGE("coap sturt is NULL");
  244. lua_pushstring(L, "coap sturt is NULL");
  245. lua_error(L);
  246. return 0;
  247. }
  248. _coap->token[8] = 0x00; // 确保有结束符
  249. lua_pushstring(L, _coap->token);
  250. return 1;
  251. }
  252. /**
  253. 获取coap数据包的二进制数据,用于发送到服务器
  254. @api coapdata:rawdata()
  255. @return string coap数据包的二进制数据
  256. @usage
  257. -- 解析服务器传入的数据包
  258. local coapdata = libcoap.new(libcoap.GET, "time")
  259. netc:send(coapdata:rawdata())
  260. */
  261. static int libcoap_rawdata(lua_State *L) {
  262. luat_lib_libcoap_t *_coap = tocoap(L);
  263. if (_coap == NULL) {
  264. LLOGE("coap sturt is NULL");
  265. lua_pushstring(L, "coap sturt is NULL");
  266. lua_error(L);
  267. return 0;
  268. }
  269. // 开始合成数据吧
  270. size_t len = 0;
  271. char buff[512] = {0}; // 最大长度暂定512
  272. // 首先, 拷贝头部
  273. _coap->header.version = 0x01;
  274. _coap->header.tokenLen = strlen(_coap->token);
  275. memcpy(buff, _coap, 4); // 头部固定4个字节
  276. len += 4;
  277. //LLOGD("libcoap header len=%d", len);
  278. // 有没有token呢?
  279. if (_coap->header.tokenLen > 0) {
  280. memcpy((char*)(buff) + len, _coap->token, _coap->header.tokenLen);
  281. len += _coap->header.tokenLen;
  282. //LLOGD("libcoap add token %ld", _coap->header.tokenLen);
  283. }
  284. // 然后处理opt
  285. if (_coap->optSize > 0) {
  286. memcpy((char*)(buff) + len, _coap->opt, _coap->optSize);
  287. len += _coap->optSize;
  288. //LLOGD("libcoap add opt %ld ,first=%d", _coap->optSize, _coap->opt[0]);
  289. }
  290. // 最后添加data
  291. if (_coap->dataSize > 0) {
  292. buff[len] = 0xFF;
  293. len ++;
  294. memcpy((char*)(buff) + len, _coap->data, _coap->dataSize);
  295. len += _coap->dataSize;
  296. //LLOGD("libcoap add data %ld", _coap->dataSize);
  297. }
  298. lua_pushlstring(L, buff, len);
  299. return 1;
  300. }
  301. /**
  302. 获取coap数据包的code
  303. @api coapdata:code()
  304. @return int coap数据包的code
  305. @usage
  306. -- 解析服务器传入的数据包
  307. local coapdata = libcoap.parse(indata)
  308. log.info("coapdata", coapdata:code())
  309. */
  310. static int libcoap_code(lua_State *L) {
  311. luat_lib_libcoap_t *_coap = tocoap(L);
  312. if (_coap == NULL) {
  313. LLOGE("coap sturt is NULL");
  314. lua_pushstring(L, "coap sturt is NULL");
  315. lua_error(L);
  316. return 0;
  317. }
  318. lua_pushinteger(L, _coap->header.code);
  319. return 1;
  320. }
  321. /**
  322. 获取coap数据包的http code, 比coap原始的code要友好
  323. @api coapdata:hcode()
  324. @return int coap数据包的http code,例如200,205,404
  325. @usage
  326. -- 解析服务器传入的数据包
  327. local coapdata = libcoap.parse(indata)
  328. log.info("coapdata", coapdata:hcode())
  329. */
  330. static int libcoap_httpcode(lua_State *L) {
  331. luat_lib_libcoap_t *_coap = tocoap(L);
  332. if (_coap == NULL) {
  333. LLOGE("coap sturt is NULL");
  334. lua_pushstring(L, "coap sturt is NULL");
  335. lua_error(L);
  336. return 0;
  337. }
  338. lua_pushinteger(L, (_coap->header.code >> 5) * 100 + (_coap->header.code & 0xF));
  339. return 1;
  340. }
  341. /**
  342. 获取coap数据包的type, 例如libcoap.CON/NON/ACK/RST
  343. @api coapdata:type(t)
  344. @int 新的type值,可选
  345. @return int coap数据包的type
  346. @usage
  347. -- 解析服务器传入的数据包
  348. local coapdata = libcoap.parse(indata)
  349. log.info("coapdata", coapdata:type())
  350. */
  351. static int libcoap_type(lua_State *L) {
  352. luat_lib_libcoap_t *_coap = tocoap(L);
  353. if (_coap == NULL) {
  354. LLOGE("coap sturt is NULL");
  355. lua_pushstring(L, "coap sturt is NULL");
  356. lua_error(L);
  357. return 0;
  358. }
  359. if (lua_isinteger(L, 1)) {
  360. _coap->header.type = luaL_checkinteger(L, 1);
  361. }
  362. lua_pushinteger(L, _coap->header.type);
  363. return 1;
  364. }
  365. /**
  366. 获取coap数据包的data
  367. @api coapdata:data()
  368. @return string coap数据包的data
  369. @usage
  370. -- 解析服务器传入的数据包
  371. local coapdata = libcoap.parse(indata)
  372. log.info("coapdata", coapdata:data())
  373. */
  374. static int libcoap_data(lua_State *L) {
  375. luat_lib_libcoap_t *_coap = tocoap(L);
  376. if (_coap == NULL) {
  377. LLOGE("coap sturt is NULL");
  378. lua_pushstring(L, "coap sturt is NULL");
  379. lua_error(L);
  380. return 0;
  381. }
  382. lua_pushlstring(L, _coap->data, _coap->dataSize);
  383. return 1;
  384. }
  385. static const luaL_Reg lib_libcoap[] = {
  386. {"tp", libcoap_type},
  387. {"msgid", libcoap_msgid},
  388. {"token", libcoap_token},
  389. {"code", libcoap_code},
  390. {"hcode", libcoap_httpcode},
  391. {"rawdata", libcoap_rawdata},
  392. {"data", libcoap_data},
  393. //{"__gc", libcoap_gc},
  394. //{"__tostring", libcoap_tostring},
  395. {NULL, NULL}
  396. };
  397. static void createmeta (lua_State *L) {
  398. luaL_newmetatable(L, LUAT_COAP_HANDLE); /* create metatable for file handles */
  399. lua_pushvalue(L, -1); /* push metatable */
  400. lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
  401. luaL_setfuncs(L, lib_libcoap, 0); /* add file methods to new metatable */
  402. lua_pop(L, 1); /* pop new metatable */
  403. }
  404. #include "rotable.h"
  405. #define CODE(H,L) (H << 5 + L)
  406. static const rotable_Reg reg_libcoap[] =
  407. {
  408. { "new", l_libcoap_new, 0},
  409. { "parse", l_libcoap_parse, 0},
  410. // ----- 类型常量
  411. { "CON", NULL, 0},
  412. { "NON", NULL, 1},
  413. { "ACK", NULL, 2},
  414. { "RST", NULL, 3},
  415. // 请求类
  416. { "NONE", NULL, 0},
  417. { "GET", NULL, 1},
  418. { "POST", NULL, 2},
  419. { "PUT", NULL, 3},
  420. { "DELETE", NULL, 4},
  421. // 响应类
  422. // { "Created", NULL, CODE(2,1)},
  423. // { "Deleted", NULL, CODE(2,2)},
  424. // { "Valid", NULL, CODE(2,3)},
  425. // { "Changed", NULL, CODE(2,4)},
  426. // { "Content", NULL, CODE(2,5)},
  427. // { "Bad Request",NULL, CODE(4,0)},
  428. // { "Unauthorized",NULL, CODE(4,1)},
  429. // { "Bad Option", NULL, CODE(4,2)},
  430. // { "Forbidden", NULL, CODE(4,3)},
  431. // { "Not Found", NULL, CODE(4,4)},
  432. // { "Method Not Allowed",NULL, CODE(4,5)},
  433. // { "Not Acceptable", NULL, CODE(4,6)},
  434. // { "Precondition Failed", NULL, CODE(4,12)},
  435. // { "Request Entity Too Large", NULL, CODE(4,13)},
  436. // { "Unsupported Content-Format", NULL, CODE(4,15)},
  437. // { "Internal Server Error", NULL, CODE(5,0)},
  438. // { "Not Implemented", NULL, CODE(5,1)},
  439. // { "Bad Gateway", NULL, CODE(5,2)},
  440. // { "Service Unavailable", NULL, CODE(5,3)},
  441. // { "Gateway Timeout", NULL, CODE(5,4)},
  442. // { "Proxying Not Supported", NULL, CODE(5,5)},
  443. { NULL, NULL , 0}
  444. };
  445. LUAMOD_API int luaopen_libcoap( lua_State *L ) {
  446. luat_newlib(L, reg_libcoap);
  447. createmeta(L);
  448. return 1;
  449. }