Commit fe602d2d authored by Johny Mattsson's avatar Johny Mattsson
Browse files

Removed all currently-unused code & docs.

Heading towards having only ESP32-aware/capable code in this branch.
parent ddeb26c4
#ifndef COAP_H
#define COAP_H 1
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "lualib.h"
#include "lauxlib.h"
#define MAXOPT 16
#define MAX_MESSAGE_SIZE 1152
#define MAX_PAYLOAD_SIZE 1024
#define MAX_REQUEST_SIZE 576
#define MAX_REQ_SCRATCH_SIZE 60
#define COAP_RESPONSE_CLASS(C) (((C) >> 5) & 0xFF)
//http://tools.ietf.org/html/rfc7252#section-3
typedef struct
{
uint8_t ver; /* CoAP version number */
uint8_t t; /* CoAP Message Type */
uint8_t tkl; /* Token length: indicates length of the Token field */
uint8_t code; /* CoAP status code. Can be request (0.xx), success reponse (2.xx),
* client error response (4.xx), or rever error response (5.xx)
* For possible values, see http://tools.ietf.org/html/rfc7252#section-12.1 */
uint8_t id[2];
} coap_header_t;
typedef struct
{
const uint8_t *p;
size_t len;
} coap_buffer_t;
typedef struct
{
uint8_t *p;
size_t len;
} coap_rw_buffer_t;
typedef struct
{
uint8_t num; /* Option number. See http://tools.ietf.org/html/rfc7252#section-5.10 */
coap_buffer_t buf; /* Option value */
} coap_option_t;
typedef struct
{
coap_header_t hdr; /* Header of the packet */
coap_buffer_t tok; /* Token value, size as specified by hdr.tkl */
uint8_t numopts; /* Number of options */
coap_option_t opts[MAXOPT]; /* Options of the packet. For possible entries see
* http://tools.ietf.org/html/rfc7252#section-5.10 */
coap_buffer_t payload; /* Payload carried by the packet */
coap_rw_buffer_t content; // content->p = malloc(...) , and free it when done.
} coap_packet_t;
/////////////////////////////////////////
//http://tools.ietf.org/html/rfc7252#section-12.2
typedef enum
{
COAP_OPTION_IF_MATCH = 1,
COAP_OPTION_URI_HOST = 3,
COAP_OPTION_ETAG = 4,
COAP_OPTION_IF_NONE_MATCH = 5,
COAP_OPTION_OBSERVE = 6,
COAP_OPTION_URI_PORT = 7,
COAP_OPTION_LOCATION_PATH = 8,
COAP_OPTION_URI_PATH = 11,
COAP_OPTION_CONTENT_FORMAT = 12,
COAP_OPTION_MAX_AGE = 14,
COAP_OPTION_URI_QUERY = 15,
COAP_OPTION_ACCEPT = 17,
COAP_OPTION_LOCATION_QUERY = 20,
COAP_OPTION_PROXY_URI = 35,
COAP_OPTION_PROXY_SCHEME = 39
} coap_option_num_t;
//http://tools.ietf.org/html/rfc7252#section-12.1.1
typedef enum
{
COAP_METHOD_GET = 1,
COAP_METHOD_POST = 2,
COAP_METHOD_PUT = 3,
COAP_METHOD_DELETE = 4
} coap_method_t;
//http://tools.ietf.org/html/rfc7252#section-12.1.1
typedef enum
{
COAP_TYPE_CON = 0,
COAP_TYPE_NONCON = 1,
COAP_TYPE_ACK = 2,
COAP_TYPE_RESET = 3
} coap_msgtype_t;
//http://tools.ietf.org/html/rfc7252#section-5.2
//http://tools.ietf.org/html/rfc7252#section-12.1.2
#define MAKE_RSPCODE(clas, det) ((clas << 5) | (det))
typedef enum
{
COAP_RSPCODE_CONTENT = MAKE_RSPCODE(2, 5),
COAP_RSPCODE_NOT_FOUND = MAKE_RSPCODE(4, 4),
COAP_RSPCODE_BAD_REQUEST = MAKE_RSPCODE(4, 0),
COAP_RSPCODE_CHANGED = MAKE_RSPCODE(2, 4)
} coap_responsecode_t;
//http://tools.ietf.org/html/rfc7252#section-12.3
typedef enum
{
COAP_CONTENTTYPE_NONE = -1, // bodge to allow us not to send option block
COAP_CONTENTTYPE_TEXT_PLAIN = 0,
COAP_CONTENTTYPE_APPLICATION_LINKFORMAT = 40,
COAP_CONTENTTYPE_APPLICATION_XML = 41,
COAP_CONTENTTYPE_APPLICATION_OCTET_STREAM = 42,
COAP_CONTENTTYPE_APPLICATION_EXI = 47,
COAP_CONTENTTYPE_APPLICATION_JSON = 50,
} coap_content_type_t;
///////////////////////
typedef enum
{
COAP_ERR_NONE = 0,
COAP_ERR_HEADER_TOO_SHORT = 1,
COAP_ERR_VERSION_NOT_1 = 2,
COAP_ERR_TOKEN_TOO_SHORT = 3,
COAP_ERR_OPTION_TOO_SHORT_FOR_HEADER = 4,
COAP_ERR_OPTION_TOO_SHORT = 5,
COAP_ERR_OPTION_OVERRUNS_PACKET = 6,
COAP_ERR_OPTION_TOO_BIG = 7,
COAP_ERR_OPTION_LEN_INVALID = 8,
COAP_ERR_BUFFER_TOO_SMALL = 9,
COAP_ERR_UNSUPPORTED = 10,
COAP_ERR_OPTION_DELTA_INVALID = 11,
} coap_error_t;
///////////////////////
typedef struct coap_endpoint_t coap_endpoint_t;
typedef int (*coap_endpoint_func)(const coap_endpoint_t *ep, coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo);
#define MAX_SEGMENTS 3 // 2 = /foo/bar, 3 = /foo/bar/baz
#define MAX_SEGMENTS_SIZE 16
typedef struct
{
int count;
const char *elems[MAX_SEGMENTS];
} coap_endpoint_path_t;
typedef struct coap_luser_entry coap_luser_entry;
struct coap_luser_entry{
lua_State *L;
// int ref;
// char name[MAX_SEGMENTS_SIZE+1]; // +1 for string '\0'
const char *name;
coap_luser_entry *next;
int content_type;
};
struct coap_endpoint_t{
coap_method_t method; /* (i.e. POST, PUT or GET) */
coap_endpoint_func handler; /* callback function which handles this
* type of endpoint (and calls
* coap_make_response() at some point) */
const coap_endpoint_path_t *path; /* path towards a resource (i.e. foo/bar/) */
const char *core_attr; /* the 'ct' attribute, as defined in RFC7252, section 7.2.1.:
* "The Content-Format code "ct" attribute
* provides a hint about the
* Content-Formats this resource returns."
* (Section 12.3. lists possible ct values.) */
coap_luser_entry *user_entry;
};
///////////////////////
void coap_dumpPacket(coap_packet_t *pkt);
int coap_parse(coap_packet_t *pkt, const uint8_t *buf, size_t buflen);
int coap_buffer_to_string(char *strbuf, size_t strbuflen, const coap_buffer_t *buf);
const coap_option_t *coap_findOptions(const coap_packet_t *pkt, uint8_t num, uint8_t *count);
int coap_build(uint8_t *buf, size_t *buflen, const coap_packet_t *pkt);
void coap_dump(const uint8_t *buf, size_t buflen, bool bare);
int coap_make_response(coap_rw_buffer_t *scratch, coap_packet_t *pkt, const uint8_t *content, size_t content_len, uint8_t msgid_hi, uint8_t msgid_lo, const coap_buffer_t* tok, coap_responsecode_t rspcode, coap_content_type_t content_type);
int coap_handle_req(coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt);
void coap_option_nibble(uint32_t value, uint8_t *nibble);
void coap_setup(void);
void endpoint_setup(void);
int coap_buildOptionHeader(uint32_t optDelta, size_t length, uint8_t *buf, size_t buflen);
int check_token(coap_packet_t *pkt);
#include "uri.h"
int coap_make_request(coap_rw_buffer_t *scratch, coap_packet_t *pkt, coap_msgtype_t t, coap_method_t m, coap_uri_t *uri, const uint8_t *payload, size_t payload_len);
#ifdef __cplusplus
}
#endif
#endif
#include "user_config.h"
#include "c_types.h"
#include "coap.h"
#include "coap_timer.h"
#include "hash.h"
#include "node.h"
extern coap_queue_t *gQueue;
void coap_client_response_handler(char *data, unsigned short len, unsigned short size, const uint32_t ip, const uint32_t port)
{
NODE_DBG("coap_client_response_handler is called.\n");
coap_packet_t pkt;
pkt.content.p = NULL;
pkt.content.len = 0;
int rc;
if (0 != (rc = coap_parse(&pkt, data, len))){
NODE_DBG("Bad packet rc=%d\n", rc);
}
else
{
#ifdef COAP_DEBUG
coap_dumpPacket(&pkt);
#endif
/* check if this is a response to our original request */
if (!check_token(&pkt)) {
/* drop if this was just some message, or send RST in case of notification */
if (pkt.hdr.t == COAP_TYPE_CON || pkt.hdr.t == COAP_TYPE_NONCON){
// coap_send_rst(pkt); // send RST response
// or, just ignore it.
}
goto end;
}
if (pkt.hdr.t == COAP_TYPE_RESET) {
NODE_DBG("got RST\n");
goto end;
}
coap_tid_t id = COAP_INVALID_TID;
coap_transaction_id(ip, port, &pkt, &id);
/* transaction done, remove the node from queue */
// stop timer
coap_timer_stop();
// remove the node
coap_remove_node(&gQueue, id);
// calculate time elapsed
coap_timer_update(&gQueue);
coap_timer_start(&gQueue);
if (COAP_RESPONSE_CLASS(pkt.hdr.code) == 2)
{
/* There is no block option set, just read the data and we are done. */
NODE_DBG("%d.%02d\t", (pkt.hdr.code >> 5), pkt.hdr.code & 0x1F);
NODE_DBG((char *)(pkt.payload.p));
}
else if (COAP_RESPONSE_CLASS(pkt.hdr.code) >= 4)
{
NODE_DBG("%d.%02d\t", (pkt.hdr.code >> 5), pkt.hdr.code & 0x1F);
NODE_DBG((char *)(pkt.payload.p));
}
}
end:
if(!gQueue){ // if there is no node pending in the queue, disconnect from host.
}
}
#ifndef _COAP_CLIENT_H
#define _COAP_CLIENT_H 1
#ifdef __cplusplus
extern "C" {
#endif
void coap_client_response_handler(char *data, unsigned short len, unsigned short size, const uint32_t ip, const uint32_t port);
#ifdef __cplusplus
}
#endif
#endif
// No espconn on ESP32
#ifdef __ESP8266__
#include <string.h>
#include "coap_io.h"
#include "node.h"
#include "espconn.h"
#include "coap_timer.h"
extern coap_queue_t *gQueue;
/* releases space allocated by PDU if free_pdu is set */
coap_tid_t coap_send(struct espconn *pesp_conn, coap_pdu_t *pdu) {
coap_tid_t id = COAP_INVALID_TID;
uint32_t ip = 0, port = 0;
if ( !pesp_conn || !pdu )
return id;
espconn_sent(pesp_conn, (unsigned char *)(pdu->msg.p), pdu->msg.len);
if(pesp_conn->type == ESPCONN_TCP){
memcpy(&ip, pesp_conn->proto.tcp->remote_ip, sizeof(ip));
port = pesp_conn->proto.tcp->remote_port;
}else{
memcpy(&ip, pesp_conn->proto.udp->remote_ip, sizeof(ip));
port = pesp_conn->proto.udp->remote_port;
}
coap_transaction_id(ip, port, pdu->pkt, &id);
return id;
}
coap_tid_t coap_send_confirmed(struct espconn *pesp_conn, coap_pdu_t *pdu) {
coap_queue_t *node;
coap_tick_t diff;
uint32_t r;
node = coap_new_node();
if (!node) {
NODE_DBG("coap_send_confirmed: insufficient memory\n");
return COAP_INVALID_TID;
}
node->retransmit_cnt = 0;
node->id = coap_send(pesp_conn, pdu);
if (COAP_INVALID_TID == node->id) {
NODE_DBG("coap_send_confirmed: error sending pdu\n");
coap_free_node(node);
return COAP_INVALID_TID;
}
r = rand();
/* add randomized RESPONSE_TIMEOUT to determine retransmission timeout */
node->timeout = COAP_DEFAULT_RESPONSE_TIMEOUT * COAP_TICKS_PER_SECOND +
(COAP_DEFAULT_RESPONSE_TIMEOUT >> 1) *
((COAP_TICKS_PER_SECOND * (r & 0xFF)) >> 8);
node->pconn = pesp_conn;
node->pdu = pdu;
/* Set timer for pdu retransmission. If this is the first element in
* the retransmission queue, the base time is set to the current
* time and the retransmission time is node->timeout. If there is
* already an entry in the sendqueue, we must check if this node is
* to be retransmitted earlier. Therefore, node->timeout is first
* normalized to the timeout and then inserted into the queue with
* an adjusted relative time.
*/
coap_timer_stop();
coap_timer_update(&gQueue);
node->t = node->timeout;
coap_insert_node(&gQueue, node);
coap_timer_start(&gQueue);
return node->id;
}
#endif
#ifndef _COAP_IO_H
#define _COAP_IO_H 1
#ifdef __cplusplus
extern "C" {
#endif
#include "c_types.h"
#include "lwip/ip_addr.h"
#include "espconn.h"
#include "pdu.h"
#include "hash.h"
coap_tid_t coap_send(struct espconn *pesp_conn, coap_pdu_t *pdu);
coap_tid_t coap_send_confirmed(struct espconn *pesp_conn, coap_pdu_t *pdu);
#ifdef __cplusplus
}
#endif
#endif
#include "user_config.h"
#include <ctype.h>
#include <stdlib.h>
#include "coap.h"
size_t coap_server_respond(char *req, unsigned short reqlen, char *rsp, unsigned short rsplen)
{
NODE_DBG("coap_server_respond is called.\n");
size_t rlen = rsplen;
coap_packet_t pkt;
pkt.content.p = NULL;
pkt.content.len = 0;
uint8_t scratch_raw[4];
coap_rw_buffer_t scratch_buf = {scratch_raw, sizeof(scratch_raw)};
int rc;
#ifdef COAP_DEBUG
NODE_DBG("Received: ");
coap_dump(req, reqlen, true);
NODE_DBG("\n");
#endif
if (0 != (rc = coap_parse(&pkt, req, reqlen))){
NODE_DBG("Bad packet rc=%d\n", rc);
return 0;
}
else
{
coap_packet_t rsppkt;
rsppkt.content.p = NULL;
rsppkt.content.len = 0;
#ifdef COAP_DEBUG
coap_dumpPacket(&pkt);
#endif
coap_handle_req(&scratch_buf, &pkt, &rsppkt);
if (0 != (rc = coap_build(rsp, &rlen, &rsppkt))){
NODE_DBG("coap_build failed rc=%d\n", rc);
// return 0;
rlen = 0;
}
else
{
#ifdef COAP_DEBUG
NODE_DBG("Responding: ");
coap_dump(rsp, rlen, true);
NODE_DBG("\n");
#endif
#ifdef COAP_DEBUG
coap_dumpPacket(&rsppkt);
#endif
}
if(rsppkt.content.p){
free(rsppkt.content.p);
rsppkt.content.p = NULL;
rsppkt.content.len = 0;
}
return rlen;
}
}
#ifndef _COAP_SERVER_H
#define _COAP_SERVER_H 1
#ifdef __cplusplus
extern "C" {
#endif
size_t coap_server_respond(char *req, unsigned short reqlen, char *rsp, unsigned short rsplen);
#ifdef __cplusplus
}
#endif
#endif
// No espconn on ESP32
#ifdef __ESP8266__
#include "node.h"
#include "coap_timer.h"
#include "coap_io.h"
#include "esp_timer.h"
#include "esp_system.h"
static os_timer_t coap_timer;
static coap_tick_t basetime = 0;
void coap_timer_elapsed(coap_tick_t *diff){
coap_tick_t now = system_get_time() / 1000; // coap_tick_t is in ms. also sys_timer
if(now>=basetime){
*diff = now-basetime;
} else {
*diff = now + SYS_TIME_MAX -basetime;
}
basetime = now;
}
void coap_timer_tick(void *arg){
if( !arg )
return;
coap_queue_t **queue = (coap_queue_t **)arg;
if( !(*queue) )
return;
coap_queue_t *node = coap_pop_next( queue );
/* re-initialize timeout when maximum number of retransmissions are not reached yet */
if (node->retransmit_cnt < COAP_DEFAULT_MAX_RETRANSMIT) {
node->retransmit_cnt++;
node->t = node->timeout << node->retransmit_cnt;
NODE_DBG("** retransmission #%d of transaction %d\n",
node->retransmit_cnt, (((uint16_t)(node->pdu->pkt->hdr.id[0]))<<8)+node->pdu->pkt->hdr.id[1]);
node->id = coap_send(node->pconn, node->pdu);
if (COAP_INVALID_TID == node->id) {
NODE_DBG("retransmission: error sending pdu\n");
coap_delete_node(node);
} else {
coap_insert_node(queue, node);
}
} else {
/* And finally delete the node */
coap_delete_node( node );
}
coap_timer_start(queue);
}
void coap_timer_setup(coap_queue_t ** queue, coap_tick_t t){
os_timer_disarm(&coap_timer);
os_timer_setfn(&coap_timer, (os_timer_func_t *)coap_timer_tick, queue);
os_timer_arm(&coap_timer, t, 0); // no repeat
}
void coap_timer_stop(void){
os_timer_disarm(&coap_timer);
}
void coap_timer_update(coap_queue_t ** queue){
if (!queue)
return;
coap_tick_t diff = 0;
coap_queue_t *first = *queue;
coap_timer_elapsed(&diff); // update: basetime = now, diff = now - oldbase, means time elapsed
if (first) {
// diff ms time is elapsed, re-calculate the first node->t
if (first->t >= diff){
first->t -= diff;
} else {
first->t = 0; // when timer enabled, time out almost immediately
}
}
}
void coap_timer_start(coap_queue_t ** queue){
if(*queue){ // if there is node in the queue, set timeout to its ->t.
coap_timer_setup(queue, (*queue)->t);
}
}
#endif
#ifndef _COAP_TIMER_H
#define _COAP_TIMER_H 1
#ifdef __cplusplus
extern "C" {
#endif
#include "node.h"
#define SYS_TIME_MAX (0xFFFFFFFF / 1000)
#define COAP_DEFAULT_RESPONSE_TIMEOUT 2 /* response timeout in seconds */
#define COAP_DEFAULT_MAX_RETRANSMIT 4 /* max number of retransmissions */
#define COAP_TICKS_PER_SECOND 1000 // ms
#define DEFAULT_MAX_TRANSMIT_WAIT 90
void coap_timer_elapsed(coap_tick_t *diff);
void coap_timer_setup(coap_queue_t ** queue, coap_tick_t t);
void coap_timer_stop(void);
void coap_timer_update(coap_queue_t ** queue);
void coap_timer_start(coap_queue_t ** queue);
#ifdef __cplusplus
}
#endif
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "esp_libc.h"
#include "coap.h"
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "os_type.h"
#include "user_interface.h"
#include "user_config.h"
void build_well_known_rsp(char *rsp, uint16_t rsplen);
void endpoint_setup(void)
{
coap_setup();
}
static const coap_endpoint_path_t path_well_known_core = {2, {".well-known", "core"}};
static int handle_get_well_known_core(const coap_endpoint_t *ep, coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo)
{
outpkt->content.p = (uint8_t *)zalloc(MAX_PAYLOAD_SIZE); // this should be free-ed when outpkt is built in coap_server_respond()
if(outpkt->content.p == NULL){
NODE_DBG("not enough memory\n");
return COAP_ERR_BUFFER_TOO_SMALL;
}
outpkt->content.len = MAX_PAYLOAD_SIZE;
build_well_known_rsp(outpkt->content.p, outpkt->content.len);
return coap_make_response(scratch, outpkt, (const uint8_t *)outpkt->content.p, strlen(outpkt->content.p), id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_APPLICATION_LINKFORMAT);
}
static const coap_endpoint_path_t path_variable = {2, {"v1", "v"}};
static int handle_get_variable(const coap_endpoint_t *ep, coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo)
{
const coap_option_t *opt;
uint8_t count;
int n;
if (NULL != (opt = coap_findOptions(inpkt, COAP_OPTION_URI_PATH, &count)))
{
if ((count != ep->path->count ) && (count != ep->path->count + 1)) // +1 for /f/[function], /v/[variable]
{
NODE_DBG("should never happen.\n");
goto end;
}
if (count == ep->path->count + 1)
{
coap_luser_entry *h = ep->user_entry->next; // ->next: skip the first entry(head)
while(NULL != h){
if (opt[count-1].buf.len != strlen(h->name))
{
h = h->next;
continue;
}
if (0 == memcmp(h->name, opt[count-1].buf.p, opt[count-1].buf.len))
{
NODE_DBG("/v1/v/");
NODE_DBG((char *)h->name);
NODE_DBG(" match.\n");
if(h->L == NULL)
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE);
if(strlen(h->name))
{
n = lua_gettop(h->L);
lua_getglobal(h->L, h->name);
if (!lua_isnumber(h->L, -1) && !lua_isstring(h->L, -1)) {
NODE_DBG ("should be a number or string.\n");
lua_settop(h->L, n);
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE);
} else {
const char *res = lua_tostring(h->L,-1);
lua_settop(h->L, n);
return coap_make_response(scratch, outpkt, (const uint8_t *)res, strlen(res), id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, h->content_type);
}
}
} else {
h = h->next;
}
}
}else{
NODE_DBG("/v1/v match.\n");
goto end;
}
}
NODE_DBG("none match.\n");
end:
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_TEXT_PLAIN);
}
static const coap_endpoint_path_t path_function = {2, {"v1", "f"}};
static int handle_post_function(const coap_endpoint_t *ep, coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo)
{
const coap_option_t *opt;
uint8_t count;
int n;
if (NULL != (opt = coap_findOptions(inpkt, COAP_OPTION_URI_PATH, &count)))
{
if ((count != ep->path->count ) && (count != ep->path->count + 1)) // +1 for /f/[function], /v/[variable]
{
NODE_DBG("should never happen.\n");
goto end;
}
if (count == ep->path->count + 1)
{
coap_luser_entry *h = ep->user_entry->next; // ->next: skip the first entry(head)
while(NULL != h){
if (opt[count-1].buf.len != strlen(h->name))
{
h = h->next;
continue;
}
if (0 == memcmp(h->name, opt[count-1].buf.p, opt[count-1].buf.len))
{
NODE_DBG("/v1/f/");
NODE_DBG((char *)h->name);
NODE_DBG(" match.\n");
if(h->L == NULL)
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE);
if(strlen(h->name))
{
n = lua_gettop(h->L);
lua_getglobal(h->L, h->name);
if (lua_type(h->L, -1) != LUA_TFUNCTION) {
NODE_DBG ("should be a function\n");
lua_settop(h->L, n);
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE);
} else {
lua_pushlstring(h->L, inpkt->payload.p, inpkt->payload.len); // make sure payload.p is filled with '\0' after payload.len, or use lua_pushlstring
lua_call(h->L, 1, 1);
if (!lua_isnil(h->L, -1)){ /* get return? */
if( lua_isstring(h->L, -1) ) // deal with the return string
{
size_t len = 0;
const char *ret = luaL_checklstring( h->L, -1, &len );
if(len > MAX_PAYLOAD_SIZE){
lua_settop(h->L, n);
luaL_error( h->L, "return string:<MAX_PAYLOAD_SIZE" );
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE);
}
NODE_DBG((char *)ret);
NODE_DBG("\n");
lua_settop(h->L, n);
return coap_make_response(scratch, outpkt, ret, len, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_TEXT_PLAIN);
}
} else {
lua_settop(h->L, n);
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_TEXT_PLAIN);
}
}
}
} else {
h = h->next;
}
}
}else{
NODE_DBG("/v1/f match.\n");
goto end;
}
}
NODE_DBG("none match.\n");
end:
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE);
}
extern lua_Load gLoad;
static const coap_endpoint_path_t path_command = {2, {"v1", "c"}};
static int handle_post_command(const coap_endpoint_t *ep, coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo)
{
if (inpkt->payload.len == 0)
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_BAD_REQUEST, COAP_CONTENTTYPE_TEXT_PLAIN);
if (inpkt->payload.len > 0)
{
lua_Load *load = &gLoad;
if(load->line_position == 0){
coap_buffer_to_string(load->line, load->len,&inpkt->payload);
load->line_position = strlen(load->line)+1;
// load->line[load->line_position-1] = '\n';
// load->line[load->line_position] = 0;
// load->line_position++;
load->done = 1;
NODE_DBG("Get command:\n");
NODE_DBG(load->line); // buggy here
NODE_DBG("\nResult(if any):\n");
#if 0 // FIXME
system_os_post (LUA_TASK_PRIO, LUA_PROCESS_LINE_SIG, 0);
#endif
}
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_TEXT_PLAIN);
}
}
static uint32_t id = 0;
static const coap_endpoint_path_t path_id = {2, {"v1", "id"}};
static int handle_get_id(const coap_endpoint_t *ep, coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo)
{
#if defined(__ESP8266__)
id = system_get_chip_id();
#elif defined(__ESP32__)
uint8_t tmp;
system_get_chip_id (&tmp); // TODO: deal with failure
id = tmp;
#endif
return coap_make_response(scratch, outpkt, (const uint8_t *)(&id), sizeof(uint32_t), id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_TEXT_PLAIN);
}
coap_luser_entry var_head = {NULL,NULL,NULL,0};
coap_luser_entry *variable_entry = &var_head;
coap_luser_entry func_head = {NULL,NULL,NULL,0};
coap_luser_entry *function_entry = &func_head;
const coap_endpoint_t endpoints[] =
{
{COAP_METHOD_GET, handle_get_well_known_core, &path_well_known_core, "ct=40", NULL},
{COAP_METHOD_GET, handle_get_variable, &path_variable, "ct=0", &var_head},
{COAP_METHOD_POST, handle_post_function, &path_function, NULL, &func_head},
{COAP_METHOD_POST, handle_post_command, &path_command, NULL, NULL},
{COAP_METHOD_GET, handle_get_id, &path_id, "ct=0", NULL},
{(coap_method_t)0, NULL, NULL, NULL, NULL}
};
void build_well_known_rsp(char *rsp, uint16_t rsplen)
{
const coap_endpoint_t *ep = endpoints;
int i;
uint16_t len = rsplen;
memset(rsp, 0, len);
len--; // Null-terminated string
while(NULL != ep->handler)
{
if (NULL == ep->core_attr) {
ep++;
continue;
}
if (NULL == ep->user_entry){
if (0 < strlen(rsp)) {
strncat(rsp, ",", len);
len--;
}
strncat(rsp, "<", len);
len--;
for (i = 0; i < ep->path->count; i++) {
strncat(rsp, "/", len);
len--;
strncat(rsp, ep->path->elems[i], len);
len -= strlen(ep->path->elems[i]);
}
strncat(rsp, ">;", len);
len -= 2;
strncat(rsp, ep->core_attr, len);
len -= strlen(ep->core_attr);
} else {
coap_luser_entry *h = ep->user_entry->next; // ->next: skip the first entry(head)
while(NULL != h){
if (0 < strlen(rsp)) {
strncat(rsp, ",", len);
len--;
}
strncat(rsp, "<", len);
len--;
for (i = 0; i < ep->path->count; i++) {
strncat(rsp, "/", len);
len--;
strncat(rsp, ep->path->elems[i], len);
len -= strlen(ep->path->elems[i]);
}
strncat(rsp, "/", len);
len--;
strncat(rsp, h->name, len);
len -= strlen(h->name);
strncat(rsp, ">;", len);
len -= 2;
strncat(rsp, ep->core_attr, len);
len -= strlen(ep->core_attr);
h = h->next;
}
}
ep++;
}
}
#include "hash.h"
#include <string.h>
/* Caution: When changing this, update COAP_DEFAULT_WKC_HASHKEY
* accordingly (see int coap_hash_path());
*/
void coap_hash(const unsigned char *s, unsigned int len, coap_key_t h) {
size_t j;
while (len--) {
j = sizeof(coap_key_t)-1;
while (j) {
h[j] = ((h[j] << 7) | (h[j-1] >> 1)) + h[j];
--j;
}
h[0] = (h[0] << 7) + h[0] + *s++;
}
}
void coap_transaction_id(const uint32_t ip, const uint32_t port, const coap_packet_t *pkt, coap_tid_t *id) {
coap_key_t h;
memset(h, 0, sizeof(coap_key_t));
/* Compare the transport address. */
coap_hash((const unsigned char *)&(port), sizeof(port), h);
coap_hash((const unsigned char *)&(ip), sizeof(ip), h);
coap_hash((const unsigned char *)(pkt->hdr.id), sizeof(pkt->hdr.id), h);
*id = ((h[0] << 8) | h[1]) ^ ((h[2] << 8) | h[3]);
}
#ifndef _HASH_H
#define _HASH_H 1
#ifdef __cplusplus
extern "C" {
#endif
#include "coap.h"
typedef unsigned char coap_key_t[4];
/* CoAP transaction id */
/*typedef unsigned short coap_tid_t; */
typedef int coap_tid_t;
#define COAP_INVALID_TID -1
void coap_transaction_id(const uint32_t ip, const uint32_t port, const coap_packet_t *pkt, coap_tid_t *id);
#ifdef __cplusplus
}
#endif
#endif
#include <string.h>
#include <stdlib.h>
#include "esp_libc.h"
#include "node.h"
static inline coap_queue_t *
coap_malloc_node(void) {
return (coap_queue_t *)zalloc(sizeof(coap_queue_t));
}
void coap_free_node(coap_queue_t *node) {
free(node);
}
int coap_insert_node(coap_queue_t **queue, coap_queue_t *node) {
coap_queue_t *p, *q;
if ( !queue || !node )
return 0;
/* set queue head if empty */
if ( !*queue ) {
*queue = node;
return 1;
}
/* replace queue head if PDU's time is less than head's time */
q = *queue;
if (node->t < q->t) {
node->next = q;
*queue = node;
q->t -= node->t; /* make q->t relative to node->t */
return 1;
}
/* search for right place to insert */
do {
node->t -= q->t; /* make node-> relative to q->t */
p = q;
q = q->next;
} while (q && q->t <= node->t);
/* insert new item */
if (q) {
q->t -= node->t; /* make q->t relative to node->t */
}
node->next = q;
p->next = node;
return 1;
}
int coap_delete_node(coap_queue_t *node) {
if ( !node )
return 0;
coap_delete_pdu(node->pdu);
coap_free_node(node);
return 1;
}
void coap_delete_all(coap_queue_t *queue) {
if ( !queue )
return;
coap_delete_all( queue->next );
coap_delete_node( queue );
}
coap_queue_t * coap_new_node(void) {
coap_queue_t *node;
node = coap_malloc_node();
if ( ! node ) {
return NULL;
}
memset(node, 0, sizeof(*node));
return node;
}
coap_queue_t * coap_peek_next( coap_queue_t *queue ) {
if ( !queue )
return NULL;
return queue;
}
coap_queue_t * coap_pop_next( coap_queue_t **queue ) { // this function is called inside timeout callback only.
coap_queue_t *next;
if ( !(*queue) )
return NULL;
next = *queue;
*queue = (*queue)->next;
// if (queue) {
// queue->t += next->t;
// }
next->next = NULL;
return next;
}
int coap_remove_node( coap_queue_t **queue, const coap_tid_t id){
coap_queue_t *p, *q, *node;
if ( !queue )
return 0;
if ( !*queue ) // if empty
return 0;
q = *queue;
if (q->id == id) {
node = q;
*queue = q->next;
node->next = NULL;
if(*queue){
(*queue)->t += node->t;
}
coap_delete_node(node);
return 1;
}
/* search for right node to remove */
while (q && q->id != id) {
p = q;
q = q->next;
}
/* find the node */
if (q) {
node = q; /* save the node */
p->next = q->next; /* remove the node */
q = q->next;
node->next = NULL;
if (q) // add node->t to the node after.
{
q->t += node->t;
}
coap_delete_node(node);
return 1;
}
return 0;
}
#ifndef _NODE_H
#define _NODE_H 1
#ifdef __cplusplus
extern "C" {
#endif
#include "hash.h"
#include "pdu.h"
struct coap_queue_t;
typedef uint32_t coap_tick_t;
/*
1. queue(first)->t store when to send PDU for the next time, it's a base(absolute) time
2. queue->next->t store the delta between time and base-time. queue->next->t = timeout + now - basetime
3. node->next->t store the delta between time and previous->t. node->next->t = timeout + now - node->t - basetime
4. time to fire: 10, 15, 18, 25
node->t: 10, 5, 3, 7
*/
typedef struct coap_queue_t {
struct coap_queue_t *next;
coap_tick_t t; /**< when to send PDU for the next time */
unsigned char retransmit_cnt; /**< retransmission counter, will be removed when zero */
unsigned int timeout; /**< the randomized timeout value */
coap_tid_t id; /**< unique transaction id */
// coap_packet_t *pkt;
coap_pdu_t *pdu; /**< the CoAP PDU to send */
struct espconn *pconn;
} coap_queue_t;
void coap_free_node(coap_queue_t *node);
/** Adds node to given queue, ordered by node->t. */
int coap_insert_node(coap_queue_t **queue, coap_queue_t *node);
/** Destroys specified node. */
int coap_delete_node(coap_queue_t *node);
/** Removes all items from given queue and frees the allocated storage. */
void coap_delete_all(coap_queue_t *queue);
/** Creates a new node suitable for adding to the CoAP sendqueue. */
coap_queue_t *coap_new_node(void);
coap_queue_t *coap_pop_next( coap_queue_t **queue );
int coap_remove_node( coap_queue_t **queue, const coap_tid_t id);
#ifdef __cplusplus
}
#endif
#endif
#include <stdlib.h>
#include "pdu.h"
#include "esp_libc.h"
coap_pdu_t * coap_new_pdu(void) {
coap_pdu_t *pdu = NULL;
pdu = (coap_pdu_t *)zalloc(sizeof(coap_pdu_t));
if(!pdu){
NODE_DBG("coap_new_pdu malloc error.\n");
return NULL;
}
pdu->scratch.p = (uint8_t *)zalloc(MAX_REQ_SCRATCH_SIZE);
if(!pdu->scratch.p){
NODE_DBG("coap_new_pdu malloc error.\n");
free(pdu);
return NULL;
}
pdu->scratch.len = MAX_REQ_SCRATCH_SIZE;
pdu->pkt = (coap_packet_t *)zalloc(sizeof(coap_packet_t));
if(!pdu->pkt){
NODE_DBG("coap_new_pdu malloc error.\n");
free(pdu->scratch.p);
free(pdu);
return NULL;
}
pdu->pkt->content.p = NULL;
pdu->pkt->content.len = 0;
pdu->msg.p = (uint8_t *)zalloc(MAX_REQUEST_SIZE+1); // +1 for string '\0'
if(!pdu->msg.p){
NODE_DBG("coap_new_pdu malloc error.\n");
free(pdu->pkt);
free(pdu->scratch.p);
free(pdu);
return NULL;
}
pdu->msg.len = MAX_REQUEST_SIZE;
return pdu;
}
void coap_delete_pdu(coap_pdu_t *pdu){
if(!pdu)
return;
if(pdu->scratch.p){
free(pdu->scratch.p);
pdu->scratch.p = NULL;
pdu->scratch.len = 0;
}
if(pdu->pkt){
free(pdu->pkt);
pdu->pkt = NULL;
}
if(pdu->msg.p){
free(pdu->msg.p);
pdu->msg.p = NULL;
pdu->msg.len = 0;
}
free(pdu);
pdu = NULL;
}
#ifndef _PDU_H
#define _PDU_H 1
#ifdef __cplusplus
extern "C" {
#endif
#include "coap.h"
/** Header structure for CoAP PDUs */
typedef struct {
coap_rw_buffer_t scratch;
coap_packet_t *pkt;
coap_rw_buffer_t msg; /**< the CoAP msg to send */
} coap_pdu_t;
coap_pdu_t *coap_new_pdu(void);
void coap_delete_pdu(coap_pdu_t *pdu);
#ifdef __cplusplus
}
#endif
#endif
/* str.c -- strings to be used in the CoAP library
*
* Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include <stdlib.h>
#include <ctype.h>
#include "str.h"
str * coap_new_string(size_t size) {
str *s = (str *)malloc(sizeof(str) + size + 1);
if ( !s ) {
return NULL;
}
memset(s, 0, sizeof(str));
s->s = ((unsigned char *)s) + sizeof(str);
return s;
}
void coap_delete_string(str *s) {
free(s);
}
/* str.h -- strings to be used in the CoAP library
*
* Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#ifndef _COAP_STR_H_
#define _COAP_STR_H_
#include <string.h>
typedef struct {
size_t length; /* length of string */
unsigned char *s; /* string data */
} str;
#define COAP_SET_STR(st,l,v) { (st)->length = (l), (st)->s = (v); }
/**
* Returns a new string object with at least size bytes storage
* allocated. The string must be released using coap_delete_string();
*/
str *coap_new_string(size_t size);
/** Deletes the given string and releases any memory allocated. */
void coap_delete_string(str *);
#endif /* _COAP_STR_H_ */
/* uri.c -- helper functions for URI treatment
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "coap.h"
#include "uri.h"
#ifndef assert
// #warning "assertions are disabled"
# define assert(x) do { \
if(!x) NODE_ERR("uri.c assert!\n"); \
} while (0)
#endif
/**
* A length-safe version of strchr(). This function returns a pointer
* to the first occurrence of @p c in @p s, or @c NULL if not found.
*
* @param s The string to search for @p c.
* @param len The length of @p s.
* @param c The character to search.
*
* @return A pointer to the first occurence of @p c, or @c NULL
* if not found.
*/
static inline unsigned char *
strnchr(unsigned char *s, size_t len, unsigned char c) {
while (len && *s++ != c)
--len;
return len ? s : NULL;
}
int coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri) {
unsigned char *p, *q;
int secure = 0, res = 0;
if (!str_var || !uri)
return -1;
memset(uri, 0, sizeof(coap_uri_t));
uri->port = COAP_DEFAULT_PORT;
/* search for scheme */
p = str_var;
if (*p == '/') {
q = p;
goto path;
}
q = (unsigned char *)COAP_DEFAULT_SCHEME;
while (len && *q && tolower(*p) == *q) {
++p; ++q; --len;
}
/* If q does not point to the string end marker '\0', the schema
* identifier is wrong. */
if (*q) {
res = -1;
goto error;
}
/* There might be an additional 's', indicating the secure version: */
if (len && (secure = tolower(*p) == 's')) {
++p; --len;
}
q = (unsigned char *)"://";
while (len && *q && tolower(*p) == *q) {
++p; ++q; --len;
}
if (*q) {
res = -2;
goto error;
}
/* p points to beginning of Uri-Host */
q = p;
if (len && *p == '[') { /* IPv6 address reference */
++p;
while (len && *q != ']') {
++q; --len;
}
if (!len || *q != ']' || p == q) {
res = -3;
goto error;
}
COAP_SET_STR(&uri->host, q - p, p);
++q; --len;
} else { /* IPv4 address or FQDN */
while (len && *q != ':' && *q != '/' && *q != '?') {
*q = tolower(*q);
++q;
--len;
}
if (p == q) {
res = -3;
goto error;
}
COAP_SET_STR(&uri->host, q - p, p);
}
/* check for Uri-Port */
if (len && *q == ':') {
p = ++q;
--len;
while (len && isdigit(*q)) {
++q;
--len;
}
if (p < q) { /* explicit port number given */
int uri_port = 0;
while (p < q)
uri_port = uri_port * 10 + (*p++ - '0');
uri->port = uri_port;
}
}
path: /* at this point, p must point to an absolute path */
if (!len)
goto end;
if (*q == '/') {
p = ++q;
--len;
while (len && *q != '?') {
++q;
--len;
}
if (p < q) {
COAP_SET_STR(&uri->path, q - p, p);
p = q;
}
}
/* Uri_Query */
if (len && *p == '?') {
++p;
--len;
COAP_SET_STR(&uri->query, len, p);
len = 0;
}
end:
return len ? -1 : 0;
error:
return res;
}
/**
* Calculates decimal value from hexadecimal ASCII character given in
* @p c. The caller must ensure that @p c actually represents a valid
* heaxdecimal character, e.g. with isxdigit(3).
*
* @hideinitializer
*/
#define hexchar_to_dec(c) ((c) & 0x40 ? ((c) & 0x0F) + 9 : ((c) & 0x0F))
/**
* Decodes percent-encoded characters while copying the string @p seg
* of size @p length to @p buf. The caller of this function must
* ensure that the percent-encodings are correct (i.e. the character
* '%' is always followed by two hex digits. and that @p buf provides
* sufficient space to hold the result. This function is supposed to
* be called by make_decoded_option() only.
*
* @param seg The segment to decode and copy.
* @param length Length of @p seg.
* @param buf The result buffer.
*/
void decode_segment(const unsigned char *seg, size_t length, unsigned char *buf) {
while (length--) {
if (*seg == '%') {
*buf = (hexchar_to_dec(seg[1]) << 4) + hexchar_to_dec(seg[2]);
seg += 2; length -= 2;
} else {
*buf = *seg;
}
++buf; ++seg;
}
}
/**
* Runs through the given path (or query) segment and checks if
* percent-encodings are correct. This function returns @c -1 on error
* or the length of @p s when decoded.
*/
int check_segment(const unsigned char *s, size_t length) {
size_t n = 0;
while (length) {
if (*s == '%') {
if (length < 2 || !(isxdigit(s[1]) && isxdigit(s[2])))
return -1;
s += 2;
length -= 2;
}
++s; ++n; --length;
}
return n;
}
/**
* Writes a coap option from given string @p s to @p buf. @p s should
* point to a (percent-encoded) path or query segment of a coap_uri_t
* object. The created option will have type @c 0, and the length
* parameter will be set according to the size of the decoded string.
* On success, this function returns the option's size, or a value
* less than zero on error. This function must be called from
* coap_split_path_impl() only.
*
* @param s The string to decode.
* @param length The size of the percent-encoded string @p s.
* @param buf The buffer to store the new coap option.
* @param buflen The maximum size of @p buf.
*
* @return The option's size, or @c -1 on error.
*
* @bug This function does not split segments that are bigger than 270
* bytes.
*/
int make_decoded_option(const unsigned char *s, size_t length,
unsigned char *buf, size_t buflen) {
int res;
size_t written;
if (!buflen) {
NODE_DBG("make_decoded_option(): buflen is 0!\n");
return -1;
}
res = check_segment(s, length);
if (res < 0)
return -1;
/* write option header using delta 0 and length res */
// written = coap_opt_setheader(buf, buflen, 0, res);
written = coap_buildOptionHeader(0, res, buf, buflen);
assert(written <= buflen);
if (!written) /* encoding error */
return -1;
buf += written; /* advance past option type/length */
buflen -= written;
if (buflen < (size_t)res) {
NODE_DBG("buffer too small for option\n");
return -1;
}
decode_segment(s, length, buf);
return written + res;
}
#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif
typedef void (*segment_handler_t)(unsigned char *, size_t, void *);
/**
* Splits the given string into segments. You should call one of the
* macros coap_split_path() or coap_split_query() instead.
*
* @param parse_iter The iterator used for tokenizing.
* @param h A handler that is called with every token.
* @param data Opaque data that is passed to @p h when called.
*
* @return The number of characters that have been parsed from @p s.
*/
size_t coap_split_path_impl(coap_parse_iterator_t *parse_iter,
segment_handler_t h, void *data) {
unsigned char *seg;
size_t length;
assert(parse_iter);
assert(h);
length = parse_iter->n;
while ( (seg = coap_parse_next(parse_iter)) ) {
/* any valid path segment is handled here: */
h(seg, parse_iter->segment_length, data);
}
return length - (parse_iter->n - parse_iter->segment_length);
}
struct pkt_scr {
coap_packet_t *pkt;
coap_rw_buffer_t *scratch;
int n;
};
void write_option(unsigned char *s, size_t len, void *data) {
struct pkt_scr *state = (struct pkt_scr *)data;
int res;
assert(state);
/* skip empty segments and those that consist of only one or two dots */
if (memcmp(s, "..", min(len,2)) == 0)
return;
res = check_segment(s, len);
if (res < 0){
NODE_DBG("not a valid segment\n");
return;
}
if (state->scratch->len < (size_t)res) {
NODE_DBG("buffer too small for option\n");
return;
}
decode_segment(s, len, state->scratch->p);
if (res > 0) {
state->pkt->opts[state->pkt->numopts].buf.p = state->scratch->p;
state->pkt->opts[state->pkt->numopts].buf.len = res;
state->scratch->p += res;
state->scratch->len -= res;
state->pkt->numopts++;
state->n++;
}
}
int coap_split_path(coap_rw_buffer_t *scratch, coap_packet_t *pkt, const unsigned char *s, size_t length) {
struct pkt_scr tmp = { pkt, scratch, 0 };
coap_parse_iterator_t pi;
coap_parse_iterator_init((unsigned char *)s, length,
'/', (unsigned char *)"?#", 2, &pi);
coap_split_path_impl(&pi, write_option, &tmp);
int i;
for(i=0;i<tmp.n;i++){
pkt->opts[pkt->numopts - i - 1].num = COAP_OPTION_URI_PATH;
}
return tmp.n;
}
int coap_split_query(coap_rw_buffer_t *scratch, coap_packet_t *pkt, const unsigned char *s, size_t length) {
struct pkt_scr tmp = { pkt, scratch, 0 };
coap_parse_iterator_t pi;
coap_parse_iterator_init((unsigned char *)s, length,
'&', (unsigned char *)"#", 1, &pi);
coap_split_path_impl(&pi, write_option, &tmp);
int i;
for(i=0;i<tmp.n;i++){
pkt->opts[pkt->numopts - i - 1].num = COAP_OPTION_URI_QUERY;
}
return tmp.n;
}
#define URI_DATA(uriobj) ((unsigned char *)(uriobj) + sizeof(coap_uri_t))
coap_uri_t * coap_new_uri(const unsigned char *uri, unsigned int length) {
unsigned char *result;
result = (unsigned char *)malloc(length + 1 + sizeof(coap_uri_t));
if (!result)
return NULL;
memcpy(URI_DATA(result), uri, length);
URI_DATA(result)[length] = '\0'; /* make it zero-terminated */
if (coap_split_uri(URI_DATA(result), length, (coap_uri_t *)result) < 0) {
free(result);
return NULL;
}
return (coap_uri_t *)result;
}
/* iterator functions */
coap_parse_iterator_t * coap_parse_iterator_init(unsigned char *s, size_t n,
unsigned char separator,
unsigned char *delim, size_t dlen,
coap_parse_iterator_t *pi) {
assert(pi);
assert(separator);
pi->separator = separator;
pi->delim = delim;
pi->dlen = dlen;
pi->pos = s;
pi->n = n;
pi->segment_length = 0;
return pi;
}
unsigned char * coap_parse_next(coap_parse_iterator_t *pi) {
unsigned char *p;
if (!pi)
return NULL;
/* proceed to the next segment */
pi->n -= pi->segment_length;
pi->pos += pi->segment_length;
pi->segment_length = 0;
/* last segment? */
if (!pi->n || strnchr(pi->delim, pi->dlen, *pi->pos)) {
pi->pos = NULL;
return NULL;
}
/* skip following separator (the first segment might not have one) */
if (*pi->pos == pi->separator) {
++pi->pos;
--pi->n;
}
p = pi->pos;
while (pi->segment_length < pi->n && *p != pi->separator &&
!strnchr(pi->delim, pi->dlen, *p)) {
++p;
++pi->segment_length;
}
if (!pi->n) {
pi->pos = NULL;
pi->segment_length = 0;
}
return pi->pos;
}
/* uri.h -- helper functions for URI treatment
*
* Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#ifndef _COAP_URI_H_
#define _COAP_URI_H_
#define COAP_DEFAULT_SCHEME "coap" /* the default scheme for CoAP URIs */
#define COAP_DEFAULT_PORT 5683
#include "str.h"
/** Representation of parsed URI. Components may be filled from a
* string with coap_split_uri() and can be used as input for
* option-creation functions. */
typedef struct {
str host; /**< host part of the URI */
unsigned short port; /**< The port in host byte order */
str path; /**< Beginning of the first path segment.
Use coap_split_path() to create Uri-Path options */
str query; /**< The query part if present */
} coap_uri_t;
/**
* Creates a new coap_uri_t object from the specified URI. Returns the new
* object or NULL on error. The memory allocated by the new coap_uri_t
* must be released using coap_free().
* @param uri The URI path to copy.
* @para length The length of uri.
*
* @return New URI object or NULL on error.
*/
coap_uri_t *coap_new_uri(const unsigned char *uri, unsigned int length);
/**
* @defgroup uri_parse URI Parsing Functions
*
* CoAP PDUs contain normalized URIs with their path and query split into
* multiple segments. The functions in this module help splitting strings.
* @{
*/
/**
* Iterator to for tokenizing a URI path or query. This structure must
* be initialized with coap_parse_iterator_init(). Call
* coap_parse_next() to walk through the tokens.
*
* @code
* unsigned char *token;
* coap_parse_iterator_t pi;
* coap_parse_iterator_init(uri.path.s, uri.path.length, '/', "?#", 2, &pi);
*
* while ((token = coap_parse_next(&pi))) {
* ... do something with token ...
* }
* @endcode
*/
typedef struct {
size_t n; /**< number of remaining characters in buffer */
unsigned char separator; /**< segment separators */
unsigned char *delim; /**< delimiters where to split the string */
size_t dlen; /**< length of separator */
unsigned char *pos; /**< current position in buffer */
size_t segment_length; /**< length of current segment */
} coap_parse_iterator_t;
/**
* Initializes the given iterator @p pi.
*
* @param s The string to tokenize.
* @param n The length of @p s.
* @param separator The separator character that delimits tokens.
* @param delim A set of characters that delimit @s.
* @param dlen The length of @p delim.
* @param pi The iterator object to initialize.
*
* @return The initialized iterator object @p pi.
*/
coap_parse_iterator_t *
coap_parse_iterator_init(unsigned char *s, size_t n,
unsigned char separator,
unsigned char *delim, size_t dlen,
coap_parse_iterator_t *pi);
/**
* Updates the iterator @p pi to point to the next token. This
* function returns a pointer to that token or @c NULL if no more
* tokens exist. The contents of @p pi will be updated. In particular,
* @c pi->segment_length specifies the length of the current token, @c
* pi->pos points to its beginning.
*
* @param pi The iterator to update.
*
* @return The next token or @c NULL if no more tokens exist.
*/
unsigned char *coap_parse_next(coap_parse_iterator_t *pi);
/**
* Parses a given string into URI components. The identified syntactic
* components are stored in the result parameter @p uri. Optional URI
* components that are not specified will be set to { 0, 0 }, except
* for the port which is set to @c COAP_DEFAULT_PORT. This function
* returns @p 0 if parsing succeeded, a value less than zero
* otherwise.
*
* @param str_var The string to split up.
* @param len The actual length of @p str_var
* @param uri The coap_uri_t object to store the result.
* @return @c 0 on success, or < 0 on error.
*
* @note The host name part will be converted to lower case by this
* function.
*/
int
coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri);
/**
* Splits the given URI path into segments. Each segment is preceded
* by an option pseudo-header with delta-value 0 and the actual length
* of the respective segment after percent-decoding.
*
* @param s The path string to split.
* @param length The actual length of @p s.
* @param buf Result buffer for parsed segments.
* @param buflen Maximum length of @p buf. Will be set to the actual number
* of bytes written into buf on success.
*
* @return The number of segments created or @c -1 on error.
*/
#if 0
int coap_split_path(const unsigned char *s, size_t length,
unsigned char *buf, size_t *buflen);
#else
int
coap_split_path(coap_rw_buffer_t *scratch, coap_packet_t *pkt,
const unsigned char *s, size_t length);
#endif
/**
* Splits the given URI query into segments. Each segment is preceded
* by an option pseudo-header with delta-value 0 and the actual length
* of the respective query term.
*
* @param s The query string to split.
* @param length The actual length of @p s.
* @param buf Result buffer for parsed segments.
* @param buflen Maximum length of @p buf. Will be set to the actual number
* of bytes written into buf on success.
*
* @return The number of segments created or @c -1 on error.
*
* @bug This function does not reserve additional space for delta > 12.
*/
#if 0
int coap_split_query(const unsigned char *s, size_t length,
unsigned char *buf, size_t *buflen);
#else
int coap_split_query(coap_rw_buffer_t *scratch, coap_packet_t *pkt,
const unsigned char *s, size_t length);
#endif
/** @} */
#endif /* _COAP_URI_H_ */
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment