diff --git a/examples/client.c b/examples/client.c index c0b42168..e00b7468 100644 --- a/examples/client.c +++ b/examples/client.c @@ -56,6 +56,8 @@ static FILE *file = NULL; /* output file stream */ static str payload = { 0, NULL }; /* optional payload to send */ +static int reliable = 0; + unsigned char msgtype = COAP_MESSAGE_CON; /* usually, requests are sent confirmable */ typedef unsigned char method_t; @@ -150,7 +152,7 @@ coap_new_request(coap_context_t *ctx, coap_list_t *opt; (void)ctx; - if ( ! ( pdu = coap_new_pdu() ) ) + if (!(pdu = coap_new_pdu(session))) return NULL; pdu->type = msgtype; @@ -545,7 +547,7 @@ usage( const char *program, const char *version) { "usage: %s [-A type...] [-t type] [-b [num,]size] [-B seconds] [-e text]\n" "\t\t[-m method] [-N] [-o file] [-P addr[:port]] [-p port]\n" "\t\t[-s duration] [-O num,text] [-T string] [-v num] [-a addr] [-U]\n\n" - "\t\t[-u user] [-k key] URI\n\n" + "\t\t[-u user] [-k key] [-r] URI\n\n" "\tURI can be an absolute or relative coap URI,\n" "\t-a addr\tthe local interface address to use\n" "\t-A type...\taccepted media types as comma-separated list of\n" @@ -575,6 +577,7 @@ usage( const char *program, const char *version) { "\t\t\trequest)\n" "\t-T token\tinclude specified token\n" "\t-U\t\tnever include Uri-Host or Uri-Port options\n" + "\t-r\t\tUse reliable protocol (TCP or TLS)\n" "\t-l list\t\tFail to send some datagram specified by a comma separated list of number or number intervals(for debugging only)\n" "\t-l loss%%\t\tRandmoly fail to send datagrams with the specified probability(for debugging only)\n" "\n" @@ -1057,7 +1060,7 @@ get_session( memset( &hints, 0, sizeof( struct addrinfo ) ); hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ - hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */ + hints.ai_socktype = COAP_PROTO_RELIABLE(proto) ? SOCK_STREAM : SOCK_DGRAM; /* Coap uses UDP */ hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV | AI_ALL; s = getaddrinfo( local_addr, local_port, &hints, &result ); @@ -1073,7 +1076,7 @@ get_session( coap_address_init( &bind_addr ); bind_addr.size = rp->ai_addrlen; memcpy( &bind_addr.addr, rp->ai_addr, rp->ai_addrlen ); - if ( identity && key && proto == COAP_PROTO_DTLS ) + if ( identity && key && (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS) ) session = coap_new_client_session_psk( ctx, &bind_addr, dst, proto, identity, key, key_len ); else session = coap_new_client_session( ctx, &bind_addr, dst, proto ); @@ -1083,7 +1086,7 @@ get_session( } freeaddrinfo( result ); } else { - if ( identity && key && proto == COAP_PROTO_DTLS ) + if ( identity && key && (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS) ) session = coap_new_client_session_psk( ctx, NULL, dst, proto, identity, key, key_len ); else session = coap_new_client_session( ctx, NULL, dst, proto ); @@ -1110,7 +1113,7 @@ main(int argc, char **argv) { ssize_t user_length = 0, key_length = 0; int create_uri_opts = 1; - while ((opt = getopt(argc, argv, "Na:b:e:f:g:k:m:p:s:t:o:v:A:B:O:P:T:u:U:l:")) != -1) { + while ((opt = getopt(argc, argv, "Nra:b:e:f:g:k:m:p:s:t:o:v:A:B:O:P:T:u:U:l:")) != -1) { switch (opt) { case 'a': strncpy(node_str, optarg, NI_MAXHOST - 1); @@ -1193,6 +1196,9 @@ main(int argc, char **argv) { exit(1); } break; + case 'r': + reliable = 1; + break; default: usage( argv[0], LIBCOAP_PACKAGE_VERSION ); exit( 1 ); @@ -1245,7 +1251,9 @@ main(int argc, char **argv) { session = get_session( ctx, node_str[0] ? node_str : NULL, port_str, - coap_uri_scheme_is_secure( &uri ) ? COAP_PROTO_DTLS : COAP_PROTO_UDP, + reliable ? + coap_uri_scheme_is_secure(&uri) ? COAP_PROTO_TLS : COAP_PROTO_TCP + : coap_uri_scheme_is_secure(&uri) ? COAP_PROTO_DTLS : COAP_PROTO_UDP, &dst, user_length > 0 ? (const char *)user : NULL, key_length > 0 ? key : NULL, (unsigned)key_length diff --git a/examples/coap-server.c b/examples/coap-server.c index 2fc29385..658df00b 100644 --- a/examples/coap-server.c +++ b/examples/coap-server.c @@ -365,42 +365,51 @@ get_context(const char *node, const char *port) { /* iterate through results until success */ for (rp = result; rp != NULL; rp = rp->ai_next) { - coap_address_t addr; - coap_endpoint_t *endpoint; + coap_address_t addr, addrs; + coap_endpoint_t *ep_udp = NULL, *ep_dtls = NULL, *ep_tcp = NULL, *ep_tls = NULL; if (rp->ai_addrlen <= sizeof(addr.addr)) { coap_address_init(&addr); addr.size = rp->ai_addrlen; memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen); - - endpoint = coap_new_endpoint(ctx, &addr, COAP_PROTO_UDP); - if (endpoint) { - if (coap_dtls_is_supported()) { - if (addr.addr.sa.sa_family == AF_INET) { - addr.addr.sin.sin_port = htons(ntohs(addr.addr.sin.sin_port) + 1); - } else if (addr.addr.sa.sa_family == AF_INET6) { - addr.addr.sin6.sin6_port = - htons(ntohs(addr.addr.sin6.sin6_port) + 1); - } else { - goto finish; - } - - endpoint = coap_new_endpoint(ctx, &addr, COAP_PROTO_DTLS); - if (!endpoint) { - coap_log(LOG_CRIT, "cannot create DTLS endpoint\n"); - } - } - goto finish; + addrs = addr; + if (addr.addr.sa.sa_family == AF_INET) { + addrs.addr.sin.sin_port = htons(ntohs(addr.addr.sin.sin_port) + 1); + } else if (addr.addr.sa.sa_family == AF_INET6) { + addrs.addr.sin6.sin6_port = htons(ntohs(addr.addr.sin6.sin6_port) + 1); } else { - coap_log(LOG_CRIT, "cannot create endpoint\n"); + goto finish; + } + + ep_udp = coap_new_endpoint(ctx, &addr, COAP_PROTO_UDP); + if (ep_udp) { + if (coap_dtls_is_supported()) { + ep_dtls = coap_new_endpoint(ctx, &addrs, COAP_PROTO_DTLS); + if (!ep_dtls) + coap_log(LOG_CRIT, "cannot create DTLS endpoint\n"); + } + } else { + coap_log(LOG_CRIT, "cannot create UDP endpoint\n"); continue; } + ep_tcp = coap_new_endpoint(ctx, &addr, COAP_PROTO_TCP); + if (ep_tcp) { + if (coap_tls_is_supported()) { + ep_tls = coap_new_endpoint(ctx, &addrs, COAP_PROTO_TLS); + if (!ep_tls) + coap_log(LOG_CRIT, "cannot create TLS endpoint\n"); + } + } else { + coap_log(LOG_CRIT, "cannot create TCP endpoint\n"); + } + if (ep_udp) + goto finish; } } fprintf(stderr, "no context available for interface '%s'\n", node); - finish: +finish: freeaddrinfo(result); return ctx; } diff --git a/examples/contiki/coap-observer.c b/examples/contiki/coap-observer.c index 7d612f01..b71cab4c 100644 --- a/examples/contiki/coap-observer.c +++ b/examples/contiki/coap-observer.c @@ -133,7 +133,7 @@ PROCESS_THREAD(coap_server_process, ev, data) request = coap_pdu_init(COAP_MESSAGE_CON, COAP_REQUEST_GET, coap_new_message_id(coap_context), - COAP_DEFFAULT_PDU_SIZE); + COAP_PDU_SIZE_DYNAMIC); coap_split_uri((unsigned char *)resource, strlen(resource), &uri); diff --git a/examples/contiki/server.c b/examples/contiki/server.c index 7d33235b..bd23756b 100644 --- a/examples/contiki/server.c +++ b/examples/contiki/server.c @@ -134,11 +134,8 @@ hnd_get_time(coap_context_t *ctx, struct coap_resource_t *resource, && memcmp(COAP_OPT_VALUE(option), "ticks", min(5, COAP_OPT_LENGTH(option))) == 0) { /* output ticks */ - len = snprintf((char *)buf, - min(sizeof(buf), response->max_size - response->length), - "%u", (unsigned int)now); + len = snprintf((char *)buf, sizeof(buf), "%u", (unsigned int)now); coap_add_data(response, len, buf); - } } } diff --git a/examples/tiny.c b/examples/tiny.c index f83b1c26..5a196a64 100644 --- a/examples/tiny.c +++ b/examples/tiny.c @@ -29,7 +29,7 @@ make_pdu( unsigned int value ) { static unsigned char buf[20]; int len, ls; - if ( ! ( pdu = coap_new_pdu() ) ) + if (!(pdu = coap_pdu_init(0, 0, 0, COAP_PDU_SIZE_DYNAMIC))) return NULL; pdu->type = COAP_MESSAGE_NON; diff --git a/include/coap/coap_dtls.h b/include/coap/coap_dtls.h index 9bcf4a86..db658141 100644 --- a/include/coap/coap_dtls.h +++ b/include/coap/coap_dtls.h @@ -23,6 +23,9 @@ /** Returns 1 if support for DTLS is enabled, or 0 otherwise. */ int coap_dtls_is_supported(void); +/** Returns 1 if support for TLS is enabled, or 0 otherwise. */ +int coap_tls_is_supported( void ); + /** Sets the log level to the specified value. */ void coap_dtls_set_log_level(int level); @@ -86,20 +89,6 @@ int coap_dtls_send(coap_session_t *session, const uint8_t *data, size_t data_len); -/** - * Send data to a TLS peer. - * - * @param session The CoAP session - * @param data pointer to data - * @param size number of bytes to send - * @param flush set to non-zero if the message should be sent now - * @return 0 if this would be blocking, -1 if there is an error or the number of cleartext bytes sent - */ -int coap_tls_send(coap_session_t *session, - const uint8_t *data, - size_t data_len, - int flush); - /** * Check if timeout is handled per session or per context. * @@ -137,7 +126,7 @@ void coap_dtls_handle_timeout(coap_session_t *session); * @param session The CoAP session * @param data Encrypted datagram * @param data_len Encrypted datagram size -* @return result of coap_handle_message on the decrypted CoAP PDU or -1 for error. +* @return result of coap_handle_dgram on the decrypted CoAP PDU or -1 for error. */ int coap_dtls_receive(coap_session_t *session, const uint8_t *data, @@ -165,6 +154,22 @@ int coap_dtls_hello(coap_session_t *session, unsigned int coap_dtls_get_overhead(coap_session_t *session); +/** + * Send data to a TLS peer. + * + * @param session The CoAP session + * @param data pointer to data + * @param size number of bytes to send + * @param flush set to non-zero if the message should be sent now + * @return 0 if this would be blocking, -1 if there is an error or the number of cleartext bytes sent + */ +int coap_tls_send(coap_session_t *session, + const uint8_t *data, + size_t data_len, + int flush); + + + /** @} */ void coap_dtls_startup( void ); diff --git a/include/coap/coap_io.h b/include/coap/coap_io.h index 30666f36..4edd80f3 100644 --- a/include/coap/coap_io.h +++ b/include/coap/coap_io.h @@ -51,37 +51,70 @@ typedef struct coap_socket_t { /** * coap_socket_flags_t values */ -#define COAP_SOCKET_EMPTY 0x0000 /**< the socket is not used */ -#define COAP_SOCKET_NOT_EMPTY 0x0001 /**< the socket is not empty */ -#define COAP_SOCKET_BOUND 0x0002 /**< the socket is bound */ -#define COAP_SOCKET_CONNECTED 0x0004 /**< the socket is connected */ -#define COAP_SOCKET_WANT_DATA 0x0010 /**< non blocking socket is waiting for reading */ -#define COAP_SOCKET_WANT_WRITE 0x0020 /**< non blocking socket is waiting for writing */ -#define COAP_SOCKET_HAS_DATA 0x0100 /**< non blocking socket can now read without blocking */ -#define COAP_SOCKET_CAN_WRITE 0x0200 /**< non blocking socket can now write without blocking */ +#define COAP_SOCKET_EMPTY 0x0000 /**< the socket is not used */ +#define COAP_SOCKET_NOT_EMPTY 0x0001 /**< the socket is not empty */ +#define COAP_SOCKET_BOUND 0x0002 /**< the socket is bound */ +#define COAP_SOCKET_CONNECTED 0x0004 /**< the socket is connected */ +#define COAP_SOCKET_WANT_READ 0x0010 /**< non blocking socket is waiting for reading */ +#define COAP_SOCKET_WANT_WRITE 0x0020 /**< non blocking socket is waiting for writing */ +#define COAP_SOCKET_WANT_ACCEPT 0x0040 /**< non blocking server socket is waiting for accept */ +#define COAP_SOCKET_WANT_CONNECT 0x0080 /**< non blocking client socket is waiting for connect */ +#define COAP_SOCKET_CAN_READ 0x0100 /**< non blocking socket can now read without blocking */ +#define COAP_SOCKET_CAN_WRITE 0x0200 /**< non blocking socket can now write without blocking */ +#define COAP_SOCKET_CAN_ACCEPT 0x0400 /**< non blocking server socket can now accept without blocking */ +#define COAP_SOCKET_CAN_CONNECT 0x0800 /**< non blocking client socket can now connect without blocking */ struct coap_endpoint_t *coap_malloc_endpoint( void ); void coap_mfree_endpoint( struct coap_endpoint_t *ep ); int -coap_socket_connect_udp( coap_socket_t *sock, +coap_socket_connect_udp(coap_socket_t *sock, + const coap_address_t *local_if, + const coap_address_t *server, + int default_port, + coap_address_t *local_addr, + coap_address_t *remote_addr); + +int +coap_socket_bind_udp(coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr ); + +int +coap_socket_connect_tcp1(coap_socket_t *sock, const coap_address_t *local_if, const coap_address_t *server, int default_port, coap_address_t *local_addr, - coap_address_t *remote_addr ); + coap_address_t *remote_addr); int -coap_socket_bind_udp( coap_socket_t *sock, - const coap_address_t *listen_addr, - coap_address_t *bound_addr ); +coap_socket_connect_tcp2(coap_socket_t *sock, + coap_address_t *local_addr, + coap_address_t *remote_addr); -void coap_socket_close( coap_socket_t *sock ); +int +coap_socket_bind_tcp(coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr); + +int +coap_socket_accept_tcp(coap_socket_t *server, + coap_socket_t *new_client, + coap_address_t *local_addr, + coap_address_t *remote_addr); + +void coap_socket_close(coap_socket_t *sock); ssize_t coap_socket_send( coap_socket_t *sock, struct coap_session_t *session, const uint8_t *data, size_t data_len ); +ssize_t +coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len); + +ssize_t +coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len); #ifdef WITH_LWIP ssize_t diff --git a/include/coap/coap_session.h b/include/coap/coap_session.h index 7137a141..3ac173b0 100644 --- a/include/coap/coap_session.h +++ b/include/coap/coap_session.h @@ -48,6 +48,7 @@ typedef struct coap_session_t { uint8_t ref; /**< reference count from queues */ uint16_t mtu; /**< path mtu */ uint16_t tls_overhead; /**< overhead of TLS layer */ + coap_address_t local_if; /**< optional local interface address */ coap_address_t remote_addr; /**< remote address and port */ coap_address_t local_addr; /**< local address and port */ int ifindex; /**< interface index */ @@ -57,6 +58,10 @@ typedef struct coap_session_t { void *tls; /**< security parameters */ uint16_t tx_mid; /**< the last message id that was used in this session */ struct coap_queue_t *sendqueue; /**< list of messages waiting to be sent */ + size_t partial_write; /**< if > 0 indicates number of bytes already written from the pdu at the head of sendqueue */ + uint8_t read_header[8]; /**< storage space for header of incoming message header */ + size_t partial_read; /**< if > 0 indicates number of bytes already read for an incoming message */ + coap_pdu_t *partial_pdu; /**< incomplete incoming pdu */ coap_tick_t last_rx_tx; uint8_t *psk_identity; size_t psk_identity_len; @@ -131,7 +136,7 @@ void coap_session_set_mtu(coap_session_t *session, unsigned mtu); * @param session The CoAP session. * @return maximum PDU size */ -unsigned int coap_session_max_pdu_size(coap_session_t *session); +size_t coap_session_max_pdu_size(coap_session_t *session); /** * Creates a new client session to the designated server. @@ -172,6 +177,18 @@ coap_session_t *coap_new_client_session_psk( unsigned key_len ); +/** +* Creates a new server session for the specified endpoint. +* @param ctx The CoAP context. +* @param ep An endpoint where an incoming connection request is pending. +* +* @return A new CoAP session or NULL if failed. Call coap_session_release to free. +*/ +coap_session_t *coap_new_server_session( + struct coap_context_t *ctx, + struct coap_endpoint_t *ep +); + /** * Function interface for data transmission. This function returns the number of * bytes that have been transmitted, or a value less than zero on error. diff --git a/include/coap/net.h b/include/coap/net.h index 2d4ebbd6..5e9faefa 100644 --- a/include/coap/net.h +++ b/include/coap/net.h @@ -372,10 +372,12 @@ coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node); * For applications with their own message loop, send all pending retransmits and * return the list of sockets with events to wait for and the next timeout * The application should call coap_read, then coap_write again when any condition below is true: -* - data is available on any of the sockets with the COAP_SOCKET_WANT_DATA flag set +* - data is available on any of the sockets with the COAP_SOCKET_WANT_READ +* - an incoming connection is pending in the listen queue and the COAP_SOCKET_WANT_ACCEPT flag is set * - at least some data can be written without blocking on any of the sockets with the COAP_SOCKET_WANT_WRITE flag set +* - a connection event occured (success or failure) and the COAP_SOCKET_WANT_CONNECT flag is set * - the timeout has expired -* Before calling coap_read or coap_write again, the application should position COAP_SOCKET_HAS_DATA and COAP_SOCKET_CAN_WRITE flags as applicable. +* Before calling coap_read or coap_write again, the application should position COAP_SOCKET_CAN_READ and COAP_SOCKET_CAN_WRITE flags as applicable. * * @param ctx The CoAP context * @param sockets array of socket descriptors, filled on output @@ -422,7 +424,7 @@ int coap_run_once( coap_context_t *ctx, unsigned int timeout_ms ); * @return @c 0 if message was handled successfully, or less than zero on * error. */ -int coap_handle_message(coap_context_t *ctx, coap_session_t *session, uint8_t *data, size_t data_len); +int coap_handle_dgram(coap_context_t *ctx, coap_session_t *session, uint8_t *data, size_t data_len); /** * Invokes the event handler of @p context for the given @p event and @@ -501,7 +503,8 @@ coap_cancel_session_messages(coap_context_t *context, /** * Dispatches the PDUs from the receive queue in given context. */ -void coap_dispatch(coap_context_t *context, coap_queue_t *rcvd); +void coap_dispatch(coap_context_t *context, coap_session_t *session, + coap_pdu_t *pdu); /** * Returns 1 if there are no messages to send or to dispatch in the context's diff --git a/include/coap/pdu.h b/include/coap/pdu.h index 5f19db20..bd11aad6 100644 --- a/include/coap/pdu.h +++ b/include/coap/pdu.h @@ -248,11 +248,13 @@ typedef struct coap_pdu_t { uint8_t type; /**< message type */ uint8_t code; /**< request method (value 1--10) or response code (value 40-255) */ uint8_t max_hdr_size; /**< space reserved for protocol-specific header */ + uint8_t hdr_size; /**< actaul size used for protocol-specific header */ uint8_t token_length; /**< length of Token */ uint16_t tid; /**< transaction id, if any, in regular host byte order */ uint16_t max_delta; /**< highest option number */ - size_t max_size; /**< allocated storage for token, options and payload */ + size_t alloc_size; /**< allocated storage for token, options and payload */ size_t used_size; /**< used bytes of storage for token, options and payload */ + size_t max_size; /**< maximum size for token, options and payload, or zero for variable size pdu */ uint8_t *token; /**< first byte of token, if any, or options */ uint8_t *data; /**< first byte of payload, if any */ #ifdef LWIP @@ -304,6 +306,7 @@ typedef uint8_t coap_proto_t; #define COAP_PROTO_TCP 3 #define COAP_PROTO_TLS 4 +#define COAP_PDU_SIZE_DYNAMIC ((size_t)-1) /** * Creates a new CoAP PDU with at least enough storage space for the given @@ -316,17 +319,17 @@ typedef uint8_t coap_proto_t; * COAP_MESSAGE_ACK, COAP_MESSAGE_RST). * @param code The message code. * @param tid The transcation id to set or 0 if unknown / not applicable. - * @param size The number of bytes to allocate for the message, or zero to use - * a reasonable start size. - * + * @param size The maximum allowed number of byte for the message. + * Use COAP_PDU_SIZE_DYNAMIC to get a variable size PDU that + * will grow automatically. * @return A pointer to the new PDU object or @c NULL on error. */ coap_pdu_t * coap_pdu_init(uint8_t type, uint8_t code, uint16_t tid, size_t size); /** - * Clears any contents from @p pdu and resets @c version field, @c - * length and @c data pointers. @c max_size is set to @p size, any + * Clears any contents from @p pdu and resets @c used_size, + * and @c data pointers. @c max_size is set to @p size, any * other field is set to @c 0. Note that @p pdu must be a valid * pointer to a coap_pdu_t object created e.g. by coap_pdu_init(). */ @@ -335,7 +338,7 @@ void coap_pdu_clear(coap_pdu_t *pdu, size_t size); /** * Creates a new CoAP PDU. */ -coap_pdu_t *coap_new_pdu(); +coap_pdu_t *coap_new_pdu(struct coap_session_t *session); /** * Dispose of an CoAP PDU and frees associated storage. @@ -374,32 +377,27 @@ size_t coap_pdu_parse_size(coap_proto_t proto, size_t length); /** - * Parses @p data into the CoAP PDU structure given in @p result. + * Decode the protocol specific header for the specified PDU. + * @param pdu A newly received PDU. + * @param proto The target wire protocol. + * @return 1 for success or 0 on error. + */ + +int coap_pdu_parse_header(coap_pdu_t *pdu, coap_proto_t proto); + +/** + * Verify consistency in the given CoAP PDU structure and locate the data. * This function returns @c 0 on error or a number greater than zero on * success. - * This function only parses the header, token and options, up to the - * payload start marker. - * The payload itself is not copied, only its start position is returned. - * It need not be present in the supplied data. - * coap_add_data() or coap_add_data_after() must be called later to add the - * data to the pdu if the payload is not empty. + * This function only parses the token and options, up to the payload start + * marker. * * @param proto Session's protocol - * @param data The raw data to parse as CoAP PDU. - * @param length The actual size of @p data. - * @param pdu The PDU structure to fill. Note that the structure must - * provide space to hold at least the token and options - * part of the message. - * @param offset Position of payload inside data or 0 if message has an - * empty payload. + * @param pdu The PDU structure to. * * @return 1 on success or @c 0 on error. */ -int coap_pdu_parse_opt(coap_proto_t proto, - const uint8_t *data, - size_t length, - coap_pdu_t *pdu, - size_t *offset); +int coap_pdu_parse_opt(coap_pdu_t *pdu, coap_proto_t proto); /** * Parses @p data into the CoAP PDU structure given in @p result. diff --git a/libcoap-1.sym b/libcoap-1.sym index afcda40c..6c82dcf2 100644 --- a/libcoap-1.sym +++ b/libcoap-1.sym @@ -72,7 +72,6 @@ coap_get_query coap_get_resource_from_key coap_handle_event coap_handle_failed_notify -coap_handle_message coap_hash_impl coap_hash_path coap_hash_request_uri @@ -168,6 +167,7 @@ coap_ticks coap_ticks_from_rt_us coap_ticks_to_rt coap_ticks_to_rt_us +coap_tls_is_supported coap_touch_observer coap_wait_ack coap_wellknown_response diff --git a/src/block.c b/src/block.c index 932a3599..cbf6100e 100644 --- a/src/block.c +++ b/src/block.c @@ -82,6 +82,7 @@ coap_write_block_opt(coap_block_t *block, uint16_t type, return -2; } + assert(pdu->max_size > 0); avail = pdu->max_size - pdu->used_size - 4; want = (size_t)1 << (block->szx + 4); diff --git a/src/coap_io.c b/src/coap_io.c index 85c09878..419e6d32 100644 --- a/src/coap_io.c +++ b/src/coap_io.c @@ -18,6 +18,7 @@ #ifdef HAVE_SYS_SOCKET_H # include # define OPTVAL_T(t) (t) +# define OPTVAL_GT(t) (t) #endif #ifdef HAVE_SYS_IOCTL_H #include @@ -28,6 +29,7 @@ #ifdef HAVE_WS2TCPIP_H #include # define OPTVAL_T(t) (const char*)(t) +# define OPTVAL_GT(t) (char*)(t) # undef CMSG_DATA # define CMSG_DATA WSA_CMSG_DATA #endif @@ -121,6 +123,48 @@ coap_socket_connect_udp(coap_socket_t *sock, return 0; } +int +coap_socket_connect_tcp1(coap_socket_t *sock, + const coap_address_t *local_if, + const coap_address_t *server, + int default_port, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + return 0; +} + +int +coap_socket_connect_tcp2(coap_socket_t *sock, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + return 0; +} + +int +coap_socket_bind_tcp(coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr) { + return 0; +} + +int +coap_socket_accept_tcp(coap_socket_t *server, + coap_socket_t *new_client, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + return 0; +} + +ssize_t +coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) { + return -1; +} + +ssize_t +coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) { + return -1; +} + void coap_socket_close(coap_socket_t *sock) { if (sock->conn) uip_udp_remove((struct uip_udp_conn *)sock->conn); @@ -128,6 +172,8 @@ void coap_socket_close(coap_socket_t *sock) { #else +static const char *coap_socket_format_errno( int error ); + struct coap_endpoint_t * coap_malloc_endpoint(void) { return (struct coap_endpoint_t *)coap_malloc_type(COAP_ENDPOINT, sizeof(struct coap_endpoint_t)); @@ -180,6 +226,7 @@ coap_socket_bind_udp(coap_socket_t *sock, break; default: coap_log(LOG_ALERT, "coap_socket_bind_udp: unsupported sa_family\n"); + break; } if (bind(sock->fd, &listen_addr->addr.sa, listen_addr->size) == COAP_SOCKET_ERROR) { @@ -200,6 +247,227 @@ error: return 0; } +int +coap_socket_connect_tcp1(coap_socket_t *sock, + const coap_address_t *local_if, + const coap_address_t *server, + int default_port, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + int on = 1, off = 0; +#ifdef _WIN32 + u_long u_on = 1; +#endif + coap_address_t connect_addr; + coap_address_copy( &connect_addr, server ); + + sock->fd = socket(server->addr.sa.sa_family, SOCK_STREAM, 0); + + if (sock->fd == COAP_INVALID_SOCKET) { + coap_log(LOG_WARNING, "coap_socket_connect_tcp1: socket: %s\n", coap_socket_strerror()); + goto error; + } + +#ifdef _WIN32 + if (ioctlsocket(sock->fd, FIONBIO, &u_on) == COAP_SOCKET_ERROR) { +#else + if (ioctl(sock->fd, FIONBIO, &on) == COAP_SOCKET_ERROR) { +#endif + coap_log(LOG_WARNING, "coap_socket_connect_tcp1: ioctl FIONBIO: %s\n", coap_socket_strerror()); + } + + switch (server->addr.sa.sa_family) { + case AF_INET: + if (connect_addr.addr.sin.sin_port == 0) + connect_addr.addr.sin.sin_port = htons(default_port); + break; + case AF_INET6: + if (connect_addr.addr.sin6.sin6_port == 0) + connect_addr.addr.sin6.sin6_port = htons(default_port); + /* Configure the socket as dual-stacked */ + if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&off), sizeof(off)) == COAP_SOCKET_ERROR) + coap_log(LOG_WARNING, "coap_socket_connect_tcp1: setsockopt IPV6_V6ONLY: %s\n", coap_socket_strerror()); + break; + default: + coap_log(LOG_ALERT, "coap_socket_connect_tcp1: unsupported sa_family\n"); + break; + } + + if (local_if && local_if->addr.sa.sa_family) { + coap_address_copy(local_addr, local_if); + if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR) + coap_log(LOG_WARNING, "coap_socket_connect_tcp1: setsockopt SO_REUSEADDR: %s\n", coap_socket_strerror()); + if (bind(sock->fd, &local_if->addr.sa, local_if->size) == COAP_SOCKET_ERROR) { + coap_log(LOG_WARNING, "coap_socket_connect_tcp1: bind: %s\n", coap_socket_strerror()); + goto error; + } + } else { + local_addr->addr.sa.sa_family = server->addr.sa.sa_family; + } + + if (connect(sock->fd, &connect_addr.addr.sa, connect_addr.size) == COAP_SOCKET_ERROR) { +#ifdef _WIN32 + if (WSAGetLastError() == WSAEWOULDBLOCK) { +#else + if (errno == EINPROGRESS) { +#endif + sock->flags |= COAP_SOCKET_WANT_CONNECT; + return 1; + } + coap_log(LOG_WARNING, "coap_socket_connect_tcp1: connect: %s\n", coap_socket_strerror()); + return 0; + } + + if (getsockname(sock->fd, &local_addr->addr.sa, &local_addr->size) == COAP_SOCKET_ERROR) { + coap_log(LOG_WARNING, "coap_socket_connect_tcp1: getsockname: %s\n", coap_socket_strerror()); + } + + if (getpeername(sock->fd, &remote_addr->addr.sa, &remote_addr->size) == COAP_SOCKET_ERROR) { + coap_log(LOG_WARNING, "coap_socket_connect_tcp1: getpeername: %s\n", coap_socket_strerror()); + } + + return 1; + +error: + coap_socket_close(sock); + return 0; +} + +int +coap_socket_connect_tcp2(coap_socket_t *sock, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + int error = 0; +#ifdef _WIN32 + int optlen = (int)sizeof( error ); +#else + socklen_t optlen = (socklen_t)sizeof( error ); +#endif + + sock->flags &= ~(COAP_SOCKET_WANT_CONNECT | COAP_SOCKET_CAN_CONNECT); + + if (getsockopt(sock->fd, SOL_SOCKET, SO_ERROR, OPTVAL_GT(&error), + &optlen) == COAP_SOCKET_ERROR) { + coap_log(LOG_WARNING, "coap_socket_finish_connect_tcp: getsockopt: %s\n", + coap_socket_strerror()); + } + + if (error) { + coap_log(LOG_WARNING, "coap_socket_finish_connect_tcp: connect failed: %s\n", + coap_socket_format_errno(error)); + coap_socket_close(sock); + return 0; + } + + if (getsockname(sock->fd, &local_addr->addr.sa, &local_addr->size) == COAP_SOCKET_ERROR) { + coap_log(LOG_WARNING, "coap_socket_connect_tcp: getsockname: %s\n", coap_socket_strerror()); + } + + if (getpeername(sock->fd, &remote_addr->addr.sa, &remote_addr->size) == COAP_SOCKET_ERROR) { + coap_log(LOG_WARNING, "coap_socket_connect_tcp: getpeername: %s\n", coap_socket_strerror()); + } + + return 1; +} + +int +coap_socket_bind_tcp(coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr) { + int on = 1, off = 0; +#ifdef _WIN32 + u_long u_on = 1; +#endif + + sock->fd = socket(listen_addr->addr.sa.sa_family, SOCK_STREAM, 0); + + if (sock->fd == COAP_INVALID_SOCKET) { + coap_log(LOG_WARNING, "coap_socket_bind_tcp: socket: %s\n", coap_socket_strerror()); + goto error; + } + +#ifdef _WIN32 + if (ioctlsocket(sock->fd, FIONBIO, &u_on) == COAP_SOCKET_ERROR) { +#else + if (ioctl(sock->fd, FIONBIO, &on) == COAP_SOCKET_ERROR) { +#endif + coap_log(LOG_WARNING, "coap_socket_bind_tcp: ioctl FIONBIO: %s\n", coap_socket_strerror()); + } + + if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR) + coap_log(LOG_WARNING, "coap_socket_bind_tcp: setsockopt SO_REUSEADDR: %s\n", coap_socket_strerror()); + + switch (listen_addr->addr.sa.sa_family) { + case AF_INET: + break; + case AF_INET6: + /* Configure the socket as dual-stacked */ + if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&off), sizeof(off)) == COAP_SOCKET_ERROR) + coap_log(LOG_ALERT, "coap_socket_bind_tcp: setsockopt IPV6_V6ONLY: %s\n", coap_socket_strerror()); + break; + default: + coap_log(LOG_ALERT, "coap_socket_bind_tcp: unsupported sa_family\n"); + } + + if (bind(sock->fd, &listen_addr->addr.sa, listen_addr->size) == COAP_SOCKET_ERROR) { + coap_log(LOG_ALERT, "coap_socket_bind_tcp: bind: %s\n", coap_socket_strerror()); + goto error; + } + + bound_addr->size = (socklen_t)sizeof(*bound_addr); + if (getsockname(sock->fd, &bound_addr->addr.sa, &bound_addr->size) < 0) { + coap_log(LOG_WARNING, "coap_socket_bind_tcp: getsockname: %s\n", coap_socket_strerror()); + goto error; + } + + if (listen(sock->fd, 5) == COAP_SOCKET_ERROR) { + coap_log(LOG_ALERT, "coap_socket_bind_tcp: listen: %s\n", coap_socket_strerror()); + goto error; + } + + return 1; + +error: + coap_socket_close(sock); + return 0; +} + +int +coap_socket_accept_tcp(coap_socket_t *server, + coap_socket_t *new_client, + coap_address_t *local_addr, + coap_address_t *remote_addr) { +#ifdef _WIN32 + u_long u_on = 1; +#else + int on = 1; +#endif + + server->flags &= ~COAP_SOCKET_CAN_ACCEPT; + + new_client->fd = accept(server->fd, &remote_addr->addr.sa, + &remote_addr->size); + if (new_client->fd == COAP_INVALID_SOCKET) { + coap_log(LOG_WARNING, "coap_socket_accept_tcp: accept: %s\n", + coap_socket_strerror()); + return 0; + } + + if (getsockname( new_client->fd, &local_addr->addr.sa, &local_addr->size) < 0) + coap_log(LOG_WARNING, "coap_socket_accept_tcp: getsockname: %s\n", coap_socket_strerror()); + + #ifdef _WIN32 + if (ioctlsocket(new_client->fd, FIONBIO, &u_on) == COAP_SOCKET_ERROR) { +#else + if (ioctl(new_client->fd, FIONBIO, &on) == COAP_SOCKET_ERROR) { +#endif + coap_log(LOG_WARNING, "coap_socket_accept_tcp: ioctl FIONBIO: %s\n", + coap_socket_strerror()); + } + + return 1; +} + int coap_socket_connect_udp(coap_socket_t *sock, const coap_address_t *local_if, @@ -243,9 +511,10 @@ coap_socket_connect_udp(coap_socket_t *sock, break; default: coap_log(LOG_ALERT, "coap_socket_connect_udp: unsupported sa_family\n"); + break; } - if (local_if) { + if (local_if && local_if->addr.sa.sa_family) { if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR) coap_log(LOG_WARNING, "coap_socket_connect_udp: setsockopt SO_REUSEADDR: %s\n", coap_socket_strerror()); if (bind(sock->fd, &local_if->addr.sa, local_if->size) == COAP_SOCKET_ERROR) { @@ -260,11 +529,11 @@ coap_socket_connect_udp(coap_socket_t *sock, } if (getsockname(sock->fd, &local_addr->addr.sa, &local_addr->size) == COAP_SOCKET_ERROR) { - coap_log(LOG_WARNING, "coap_new_session: getsockname: %s\n", coap_socket_strerror()); + coap_log(LOG_WARNING, "coap_socket_connect_udp: getsockname: %s\n", coap_socket_strerror()); } if (getpeername(sock->fd, &remote_addr->addr.sa, &remote_addr->size) == COAP_SOCKET_ERROR) { - coap_log(LOG_WARNING, "coap_new_session: getpeername: %s\n", coap_socket_strerror()); + coap_log(LOG_WARNING, "coap_socket_connect_udp: getpeername: %s\n", coap_socket_strerror()); } return 1; @@ -275,8 +544,80 @@ error: } void coap_socket_close(coap_socket_t *sock) { - if (sock->fd != COAP_INVALID_SOCKET) + if (sock->fd != COAP_INVALID_SOCKET) { coap_closesocket(sock->fd); + sock->fd = COAP_INVALID_SOCKET; + } + sock->flags = 0; +} + +ssize_t +coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) { + ssize_t r; + + sock->flags &= ~(COAP_SOCKET_WANT_WRITE | COAP_SOCKET_CAN_WRITE); +#ifdef _WIN32 + r = send(sock->fd, (const char *)data, (int)data_len, 0); +#else + r = send(sock->fd, data, data_len, 0); +#endif + if (r == COAP_SOCKET_ERROR) { +#ifdef _WIN32 + if (WSAGetLastError() == WSAEWOULDBLOCK) { +#else + if (errno==EAGAIN || errno == EWOULDBLOCK) { +#endif + sock->flags |= COAP_SOCKET_WANT_WRITE; + return 0; + } + coap_log(LOG_WARNING, "coap_socket_write: send: %s\n", coap_socket_strerror()); + return -1; + } + if (r < (ssize_t)data_len) + sock->flags |= COAP_SOCKET_WANT_WRITE; + return r; +} + +ssize_t +coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) { + ssize_t r; +#ifdef _WIN32 + int error; +#endif + + if ((sock->flags & COAP_SOCKET_CAN_READ) == 0) + return -1; + +#ifdef _WIN32 + r = recv(sock->fd, (char *)data, (int)data_len, 0); +#else + r = send(sock->fd, data, data_len, 0); +#endif + if (r == 0) { + /* graceful shutdown */ + sock->flags &= ~COAP_SOCKET_CAN_READ; + return -1; + } else if (r == COAP_SOCKET_ERROR) { + sock->flags &= ~COAP_SOCKET_CAN_READ; +#ifdef _WIN32 + error = WSAGetLastError(); + if (error == WSAEWOULDBLOCK || error == WSAECONNRESET) { +#else + if (errno==EAGAIN || errno == EWOULDBLOCK) { +#endif + return 0; + } +#ifdef _WIN32 + if (error != WSAECONNRESET) +#else + if (errno != ECONNRESET) +#endif + coap_log(LOG_WARNING, "coap_socket_read: recv: %s\n", coap_socket_strerror()); + return -1; + } + if (r < (ssize_t)data_len) + sock->flags &= ~COAP_SOCKET_CAN_READ; + return r; } #endif /* WITH_CONTIKI */ @@ -489,11 +830,11 @@ coap_network_read(coap_socket_t *sock, coap_packet_t *packet) { assert(sock); assert(packet); - if ((sock->flags & COAP_SOCKET_HAS_DATA) == 0) { + if ((sock->flags & COAP_SOCKET_CAN_READ) == 0) { return -1; } else { /* clear has-data flag */ - sock->flags &= ~COAP_SOCKET_HAS_DATA; + sock->flags &= ~COAP_SOCKET_CAN_READ; } if (sock->flags & COAP_SOCKET_CONNECTED) { @@ -697,11 +1038,11 @@ coap_write(coap_context_t *ctx, LL_FOREACH(ctx->endpoint, ep) { coap_session_t *tmp; - if (ep->sock.flags & (COAP_SOCKET_WANT_DATA|COAP_SOCKET_WANT_WRITE)) { + if (ep->sock.flags & (COAP_SOCKET_WANT_READ | COAP_SOCKET_WANT_WRITE | COAP_SOCKET_WANT_ACCEPT)) { if (*num_sockets < max_sockets) sockets[(*num_sockets)++] = &ep->sock; } - LL_FOREACH_SAFE(ctx->endpoint->sessions, s, tmp) { + LL_FOREACH_SAFE(ep->sessions, s, tmp) { if (s->type == COAP_SESSION_TYPE_SERVER && s->ref == 0 && s->sendqueue == NULL && (s->last_rx_tx + session_timeout <= now || s->state == COAP_SESSION_STATE_NONE)) { coap_session_free(s); } else { @@ -710,7 +1051,7 @@ coap_write(coap_context_t *ctx, if (timeout == 0 || s_timeout < timeout) timeout = s_timeout; } - if (s->sock.flags & (COAP_SOCKET_WANT_DATA | COAP_SOCKET_WANT_WRITE)) { + if (s->sock.flags & (COAP_SOCKET_WANT_READ | COAP_SOCKET_WANT_WRITE)) { if (*num_sockets < max_sockets) sockets[(*num_sockets)++] = &s->sock; } @@ -718,7 +1059,7 @@ coap_write(coap_context_t *ctx, } } LL_FOREACH(ctx->sessions, s) { - if (s->sock.flags & (COAP_SOCKET_WANT_DATA | COAP_SOCKET_WANT_WRITE)) { + if (s->sock.flags & (COAP_SOCKET_WANT_READ | COAP_SOCKET_WANT_WRITE | COAP_SOCKET_WANT_CONNECT)) { if (*num_sockets < max_sockets) sockets[(*num_sockets)++] = &s->sock; } @@ -782,7 +1123,7 @@ coap_write(coap_context_t *ctx, int coap_run_once(coap_context_t *ctx, unsigned timeout_ms) { - fd_set readfds, writefds; + fd_set readfds, writefds, exceptfds; coap_fd_t nfds = 0; struct timeval tv; coap_tick_t before, now; @@ -798,13 +1139,20 @@ coap_run_once(coap_context_t *ctx, unsigned timeout_ms) { FD_ZERO(&readfds); FD_ZERO(&writefds); + FD_ZERO(&exceptfds); for (i = 0; i < num_sockets; i++) { if (sockets[i]->fd + 1 > nfds) nfds = sockets[i]->fd + 1; - if (sockets[i]->flags & COAP_SOCKET_WANT_DATA) + if (sockets[i]->flags & COAP_SOCKET_WANT_READ) FD_SET(sockets[i]->fd, &readfds); if (sockets[i]->flags & COAP_SOCKET_WANT_WRITE) FD_SET(sockets[i]->fd, &writefds); + if (sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT) + FD_SET(sockets[i]->fd, &readfds); + if (sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) { + FD_SET(sockets[i]->fd, &writefds); + FD_SET(sockets[i]->fd, &exceptfds); + } } if ( timeout > 0 ) { @@ -812,7 +1160,7 @@ coap_run_once(coap_context_t *ctx, unsigned timeout_ms) { tv.tv_sec = (long)(timeout / 1000); } - result = select(nfds, &readfds, &writefds, 0, timeout > 0 ? &tv : NULL); + result = select(nfds, &readfds, &writefds, &exceptfds, timeout > 0 ? &tv : NULL); if (result < 0) { /* error */ #ifdef _WIN32 @@ -827,10 +1175,14 @@ coap_run_once(coap_context_t *ctx, unsigned timeout_ms) { if (result > 0) { for (i = 0; i < num_sockets; i++) { - if ((sockets[i]->flags & COAP_SOCKET_WANT_DATA) && FD_ISSET(sockets[i]->fd, &readfds)) - sockets[i]->flags |= COAP_SOCKET_HAS_DATA; + if ((sockets[i]->flags & COAP_SOCKET_WANT_READ) && FD_ISSET(sockets[i]->fd, &readfds)) + sockets[i]->flags |= COAP_SOCKET_CAN_READ; + if ((sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT) && FD_ISSET(sockets[i]->fd, &readfds)) + sockets[i]->flags |= COAP_SOCKET_CAN_ACCEPT; if ((sockets[i]->flags & COAP_SOCKET_WANT_WRITE) && FD_ISSET(sockets[i]->fd, &writefds)) sockets[i]->flags |= COAP_SOCKET_CAN_WRITE; + if ((sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) && (FD_ISSET(sockets[i]->fd, &writefds) || FD_ISSET(sockets[i]->fd, &exceptfds))) + sockets[i]->flags |= COAP_SOCKET_CAN_CONNECT; } } @@ -858,13 +1210,21 @@ coap_write(coap_context_t *ctx, #endif #ifdef _WIN32 -const char *coap_socket_strerror(void) { +static const char *coap_socket_format_errno(int error) { static char szError[256]; - if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, (DWORD)WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)szError, (DWORD)sizeof(szError), NULL) == 0) + if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, (DWORD)error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)szError, (DWORD)sizeof(szError), NULL) == 0) strcpy(szError, "Unknown error"); return szError; } + +const char *coap_socket_strerror(void) { + return coap_socket_format_errno(WSAGetLastError()); +} #else +static const char *coap_socket_format_errno(int error) { + return strerror(error); +} + const char *coap_socket_strerror(void) { return strerror(errno); } diff --git a/src/coap_io_lwip.c b/src/coap_io_lwip.c index 36bbb370..f3a275ad 100644 --- a/src/coap_io_lwip.c +++ b/src/coap_io_lwip.c @@ -40,7 +40,7 @@ struct pbuf *coap_packet_extract_pbuf(coap_packet_t *packet) /** Callback from lwIP when a package was received. * - * The current implementation deals this to coap_handle_message immediately, but + * The current implementation deals this to coap_handle_dgram immediately, but * other mechanisms (as storing the package in a queue and later fetching it * when coap_read is called) can be envisioned. * @@ -56,7 +56,7 @@ static void coap_recv(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_ packet->srcport = port; /** FIXME derive the context without changing endpoint definition */ - coap_handle_message(ep->context, packet); + coap_handle_dgram(ep->context, packet); coap_free_packet(packet); } diff --git a/src/coap_notls.c b/src/coap_notls.c index c87c7556..cf32d05f 100644 --- a/src/coap_notls.c +++ b/src/coap_notls.c @@ -24,6 +24,11 @@ coap_dtls_is_supported(void) { return 0; } +int +coap_tls_is_supported(void) { + return 0; +} + static int dtls_log_level = 0; void coap_dtls_startup(void) { @@ -105,6 +110,14 @@ unsigned int coap_dtls_get_overhead(coap_session_t *session UNUSED) { return 0; } +int coap_tls_send(coap_session_t *session, + const uint8_t *data, + size_t data_len, + int flush ) +{ + return -1; +} + #undef UNUSED #else /* !HAVE_LIBTINYDTLS && !HAVE_OPENSSL */ diff --git a/src/coap_openssl.c b/src/coap_openssl.c index 0bfd3bca..fbd4fc12 100644 --- a/src/coap_openssl.c +++ b/src/coap_openssl.c @@ -33,6 +33,10 @@ int coap_dtls_is_supported(void) { return 1; } +int coap_tls_is_supported(void) { + return 0; +} + void coap_dtls_startup(void) { SSL_load_error_strings(); SSL_library_init(); @@ -588,7 +592,7 @@ int coap_dtls_receive(coap_session_t *session, dtls_event = -1; r = SSL_read(ssl, pdu, (int)sizeof(pdu)); if (r > 0) { - return coap_handle_message(session->context, session, pdu, (size_t)r); + return coap_handle_dgram(session->context, session, pdu, (size_t)r); } else { int err = SSL_get_error(ssl, r); if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) { @@ -670,6 +674,15 @@ unsigned int coap_dtls_get_overhead(coap_session_t *session) { } return overhead; } + +int coap_tls_send(coap_session_t *session, + const uint8_t *data, + size_t data_len, + int flush ) +{ + return -1; +} + #else /* !HAVE_OPENSSL */ /* make compilers happy that do not like empty modules */ diff --git a/src/coap_session.c b/src/coap_session.c index e20a7da8..0d7c1089 100644 --- a/src/coap_session.c +++ b/src/coap_session.c @@ -51,19 +51,26 @@ coap_session_get_app_data(const coap_session_t *session) { } static coap_session_t * -coap_make_session(coap_proto_t proto, coap_session_type_t type, const coap_address_t *local, const coap_address_t *remote, int ifindex, coap_context_t *context, coap_endpoint_t *endpoint) { +coap_make_session(coap_proto_t proto, coap_session_type_t type, + const coap_address_t *local_if, const coap_address_t *local_addr, + const coap_address_t *remote_addr, int ifindex, coap_context_t *context, + coap_endpoint_t *endpoint) { coap_session_t *session = (coap_session_t*)coap_malloc_type(COAP_SESSION, sizeof(coap_session_t)); if (!session) return NULL; memset(session, 0, sizeof(*session)); session->proto = proto; session->type = type; - if (local) - coap_address_copy(&session->local_addr, local); + if (local_if) + coap_address_copy(&session->local_if, local_if); + else + coap_address_init(&session->local_if); + if (local_addr) + coap_address_copy(&session->local_addr, local_addr); else coap_address_init(&session->local_addr); - if (remote) - coap_address_copy(&session->remote_addr, remote); + if (remote_addr) + coap_address_copy(&session->remote_addr, remote_addr); else coap_address_init(&session->remote_addr); session->ifindex = ifindex; @@ -71,7 +78,7 @@ coap_make_session(coap_proto_t proto, coap_session_type_t type, const coap_addre session->endpoint = endpoint; if (endpoint) session->mtu = endpoint->default_mtu; - else + else if (COAP_PROTO_NOT_RELIABLE(proto)) session->mtu = COAP_DEFAULT_MTU; if (proto == COAP_PROTO_DTLS) { session->tls_overhead = 29; @@ -95,6 +102,8 @@ void coap_session_free(coap_session_t *session) { assert(session->ref == 0); if (session->ref) return; + if (session->partial_pdu) + coap_delete_pdu(session->partial_pdu); if (session->proto == COAP_PROTO_DTLS) coap_dtls_free_session(session); if (session->sock.flags != COAP_SOCKET_EMPTY) @@ -122,8 +131,10 @@ void coap_session_free(coap_session_t *session) { coap_free_type(COAP_SESSION, session); } -unsigned int coap_session_max_pdu_size(coap_session_t *session) { - return session->mtu - session->tls_overhead; +size_t coap_session_max_pdu_size(coap_session_t *session) { + if (session->mtu > 0) + return (size_t)(session->mtu - session->tls_overhead); + return COAP_PDU_SIZE_DYNAMIC; } void coap_session_set_mtu(coap_session_t *session, unsigned mtu) { @@ -170,7 +181,7 @@ coap_session_delay_pdu(coap_session_t *session, coap_pdu_t *pdu, return COAP_INVALID_TID; node->id = pdu->tid; node->pdu = pdu; - if (pdu->type == COAP_MESSAGE_CON && COAP_PROTO_NOT_RELIABLE(session->proto) ) { + if (pdu->type == COAP_MESSAGE_CON && COAP_PROTO_NOT_RELIABLE(session->proto)) { uint8_t r; prng(&r, sizeof(r)); /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */ @@ -186,6 +197,7 @@ void coap_session_connected(coap_session_t *session) { debug("*** %s: session connected\n", coap_session_str(session)); session->state = COAP_SESSION_STATE_ESTABLISHED; + session->partial_write = 0; if ( session->proto==COAP_PROTO_DTLS) { session->tls_overhead = (uint16_t)coap_dtls_get_overhead(session); @@ -206,10 +218,20 @@ void coap_session_connected(coap_session_t *session) { if (coap_wait_ack(session->context, session, q) >= 0) q = NULL; } - if ( q ) - coap_delete_node(q); - if (bytes_written < 0) - break; + if (COAP_PROTO_NOT_RELIABLE(session->proto)) { + if (q) + coap_delete_node(q); + if (bytes_written < 0) + break; + } else { + if (bytes_written <= 0 || (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size) { + q->next = session->sendqueue; + session->sendqueue = q; + if (bytes_written > 0) + session->partial_write = (size_t)bytes_written; + break; + } + } } } @@ -221,18 +243,27 @@ void coap_session_disconnected(coap_session_t *session, coap_nack_reason_t reaso session->tls = NULL; } session->state = COAP_SESSION_STATE_NONE; - while (session->sendqueue) { - coap_queue_t *q = session->sendqueue; - session->sendqueue = q->next; - q->next = NULL; - debug("** %s tid=%d: not transmitted after delay\n", coap_session_str(session), q->id); - if (q->pdu->type==COAP_MESSAGE_CON && COAP_PROTO_NOT_RELIABLE(session->proto)) { - if (coap_wait_ack(session->context, session, q) >= 0) - q = NULL; - } - if (q) - coap_delete_node(q); + if (session->partial_pdu) { + coap_delete_pdu(session->partial_pdu); + session->partial_pdu = NULL; } + session->partial_read = 0; + if (COAP_PROTO_NOT_RELIABLE(session->proto)) { + while (session->sendqueue) { + coap_queue_t *q = session->sendqueue; + session->sendqueue = q->next; + q->next = NULL; + debug("** %s tid=%d: not transmitted after delay\n", coap_session_str(session), q->id); + if (q->pdu->type==COAP_MESSAGE_CON && COAP_PROTO_NOT_RELIABLE(session->proto)) { + if (coap_wait_ack(session->context, session, q) >= 0) + q = NULL; + } + if (q) + coap_delete_node(q); + } + } + if (COAP_PROTO_RELIABLE(session->proto)) + coap_socket_close(&session->sock); } void coap_session_reset(coap_session_t *session) { @@ -246,16 +277,18 @@ void coap_session_reset(coap_session_t *session) { session->tls = NULL; } session->state = COAP_SESSION_STATE_NONE; + if (session->partial_pdu) { + coap_delete_pdu(session->partial_pdu); + session->partial_pdu = NULL; + } + session->partial_read = 0; while (session->sendqueue) { coap_queue_t *q = session->sendqueue; session->sendqueue = q->next; q->next = NULL; debug("** %s tid=%d: not transmitted after delay\n", coap_session_str(session), (int)q->id); - if ( q->pdu->type == COAP_MESSAGE_CON - && COAP_PROTO_NOT_RELIABLE(session->proto) - && session->context->nack_handler ) { + if (q->pdu->type == COAP_MESSAGE_CON && session->context->nack_handler) session->context->nack_handler(session->context, session, q->pdu, COAP_NACK_NOT_DELIVERABLE, q->id); - } coap_delete_node(q); } } @@ -294,7 +327,7 @@ coap_endpoint_get_session(coap_endpoint_t *endpoint, session->ifindex = packet->ifindex; } else { session = coap_make_session(endpoint->proto, COAP_SESSION_TYPE_SERVER, - &packet->dst, &packet->src, packet->ifindex, endpoint->context, + NULL, &packet->dst, &packet->src, packet->ifindex, endpoint->context, endpoint); if (session) { session->last_rx_tx = now; @@ -311,7 +344,9 @@ coap_endpoint_get_session(coap_endpoint_t *endpoint, coap_session_t * coap_endpoint_new_dtls_session(coap_endpoint_t *endpoint, const coap_packet_t *packet, coap_tick_t now) { - coap_session_t *session = coap_make_session(COAP_PROTO_DTLS, COAP_SESSION_TYPE_SERVER, &packet->dst, &packet->src, packet->ifindex, endpoint->context, endpoint); + coap_session_t *session = coap_make_session(COAP_PROTO_DTLS, + COAP_SESSION_TYPE_SERVER, NULL, &packet->dst, &packet->src, + packet->ifindex, endpoint->context, endpoint); if (session) { session->last_rx_tx = now; session->state = COAP_SESSION_STATE_HANDSHAKE; @@ -340,20 +375,27 @@ coap_session_create_client( assert(server); assert(proto != COAP_PROTO_NONE); - session = coap_make_session(proto, COAP_SESSION_TYPE_CLIENT, local_if, server, 0, ctx, NULL); + session = coap_make_session(proto, COAP_SESSION_TYPE_CLIENT, local_if, + local_if, server, 0, ctx, NULL); if (!session) goto error; - if (!coap_socket_connect_udp(&session->sock, local_if, server, - proto == COAP_PROTO_DTLS ? COAPS_DEFAULT_PORT : COAP_DEFAULT_PORT, - &session->local_addr, &session->remote_addr - ) - ) { - goto error; + if (proto == COAP_PROTO_UDP || proto == COAP_PROTO_DTLS) { + if (!coap_socket_connect_udp(&session->sock, &session->local_if, server, + proto == COAP_PROTO_DTLS ? COAPS_DEFAULT_PORT : COAP_DEFAULT_PORT, + &session->local_addr, &session->remote_addr)) { + goto error; + } + } else if (proto == COAP_PROTO_TCP || proto == COAP_PROTO_TLS) { + if (!coap_socket_connect_tcp1(&session->sock, &session->local_if, server, + proto == COAP_PROTO_DTLS ? COAPS_DEFAULT_PORT : COAP_DEFAULT_PORT, + &session->local_addr, &session->remote_addr)) { + goto error; + } } session->ref = 1; - session->sock.flags = COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_CONNECTED | COAP_SOCKET_WANT_DATA; + session->sock.flags |= COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_CONNECTED | COAP_SOCKET_WANT_READ; if (local_if) session->sock.flags |= COAP_SOCKET_BOUND; LL_PREPEND(ctx->sessions, session); @@ -377,6 +419,25 @@ coap_session_connect(coap_session_t *session) { coap_session_free(session); return NULL; } + } else if (session->proto == COAP_PROTO_TCP || session->proto == COAP_PROTO_TLS) { + if (session->sock.flags & COAP_SOCKET_WANT_CONNECT) { + session->state = COAP_SESSION_STATE_CONNECTING; + } else if (session->proto == COAP_PROTO_TLS) { + session->state = COAP_SESSION_STATE_HANDSHAKE; + } else { + session->state = COAP_SESSION_STATE_ESTABLISHED; + } + } + coap_ticks(&session->last_rx_tx); + return session; +} + +static coap_session_t * +coap_session_accept(coap_session_t *session) { + if (session->proto == COAP_PROTO_TCP) { + session->state = COAP_SESSION_STATE_ESTABLISHED; + } else if (session->proto == COAP_PROTO_TLS) { + session->state = COAP_SESSION_STATE_HANDSHAKE; } coap_ticks(&session->last_rx_tx); return session; @@ -435,6 +496,33 @@ coap_session_t *coap_new_client_session_psk( return coap_session_connect(session); } +coap_session_t *coap_new_server_session( + struct coap_context_t *ctx, + coap_endpoint_t *ep +) { + coap_session_t *session; + session = coap_make_session( ep->proto, COAP_SESSION_TYPE_SERVER, + &ep->bind_addr, NULL, NULL, 0, ctx, ep ); + if (!session) + goto error; + if (!coap_socket_accept_tcp(&ep->sock, &session->sock, + &session->local_addr, &session->remote_addr)) + goto error; + session->sock.flags |= COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_CONNECTED + | COAP_SOCKET_WANT_READ; + LL_PREPEND(ep->sessions, session); + if (session) { + debug("*** %s: new incoming session\n", coap_session_str(session)); + session = coap_session_accept(session); + } + return session; + +error: + if (session) + coap_session_free(session); + return NULL; +} + coap_endpoint_t * coap_new_endpoint(coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto) { struct coap_endpoint_t *ep = NULL; @@ -448,6 +536,11 @@ coap_new_endpoint(coap_context_t *context, const coap_address_t *listen_addr, co goto error; } + if (proto == COAP_PROTO_TLS && !coap_tls_is_supported()) { + coap_log(LOG_CRIT, "coap_new_endpoint: TLS not supported\n"); + goto error; + } + ep = coap_malloc_endpoint(); if (!ep) { coap_log(LOG_WARNING, "coap_new_endpoint: malloc"); @@ -458,8 +551,18 @@ coap_new_endpoint(coap_context_t *context, const coap_address_t *listen_addr, co ep->context = context; ep->proto = proto; - if (!coap_socket_bind_udp(&ep->sock, listen_addr, &ep->bind_addr)) + if (proto==COAP_PROTO_TCP || proto==COAP_PROTO_TLS) { + if (!coap_socket_bind_tcp(&ep->sock, listen_addr, &ep->bind_addr)) + goto error; + ep->sock.flags |= COAP_SOCKET_WANT_ACCEPT; + } else if (proto==COAP_PROTO_UDP || proto==COAP_PROTO_DTLS) { + if (!coap_socket_bind_udp(&ep->sock, listen_addr, &ep->bind_addr)) + goto error; + ep->sock.flags |= COAP_SOCKET_WANT_READ; + } else { + coap_log(LOG_CRIT, "coap_new_endpoint: protocol not supported\n"); goto error; + } #ifndef NDEBUG if (LOG_DEBUG <= coap_get_log_level()) { @@ -470,13 +573,15 @@ coap_new_endpoint(coap_context_t *context, const coap_address_t *listen_addr, co if (coap_print_addr(&ep->bind_addr, addr_str, INET6_ADDRSTRLEN + 8)) { debug("created %s endpoint %s\n", - ep->proto == COAP_PROTO_DTLS ? "DTLS " : "UDP", + ep->proto == COAP_PROTO_TLS ? "TLS" + : ep->proto == COAP_PROTO_TCP ? "TCP" + : ep->proto == COAP_PROTO_DTLS ? "DTLS " : "UDP", addr_str); } } #endif /* NDEBUG */ - ep->sock.flags = COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_BOUND | COAP_SOCKET_WANT_DATA; + ep->sock.flags |= COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_BOUND; if (proto == COAP_PROTO_DTLS) { ep->hello.proto = proto; @@ -486,7 +591,8 @@ coap_new_endpoint(coap_context_t *context, const coap_address_t *listen_addr, co ep->hello.endpoint = ep; } - ep->default_mtu = COAP_DEFAULT_MTU; + if (COAP_PROTO_NOT_RELIABLE(proto)) + ep->default_mtu = COAP_DEFAULT_MTU; LL_PREPEND(context->endpoint, ep); return ep; @@ -563,6 +669,12 @@ const char *coap_session_str(const coap_session_t *session) { } else if (session->proto == COAP_PROTO_DTLS) { strcpy(p, " DTLS"); p += 5; + } else if (session->proto == COAP_PROTO_TCP) { + strcpy(p, " TCP"); + p += 4; + } else if (session->proto == COAP_PROTO_TLS) { + strcpy(p, " TLS"); + p += 4; } else { strcpy(p, " NONE"); p += 5; diff --git a/src/coap_tinydtls.c b/src/coap_tinydtls.c index 12d26807..bb55d1c7 100644 --- a/src/coap_tinydtls.c +++ b/src/coap_tinydtls.c @@ -115,7 +115,7 @@ dtls_application_data(struct dtls_context_t *dtls_context, return -1; } - return coap_handle_message(coap_context, coap_session, data, len); + return coap_handle_dgram(coap_context, coap_session, data, len); } static int coap_event_dtls = 0; diff --git a/src/net.c b/src/net.c index 2d997157..81fc7e21 100644 --- a/src/net.c +++ b/src/net.c @@ -629,36 +629,26 @@ coap_send_ack(coap_session_t *session, coap_pdu_t *request) { return result; } -int coap_tls_send(coap_session_t *session, - const uint8_t *data, - size_t data_len, - int flush ) -{ - return -1; -} - ssize_t coap_session_send_pdu(coap_session_t *session, coap_pdu_t *pdu) { ssize_t bytes_written = -1; - size_t header_size = coap_pdu_encode_header(pdu, session->proto); - if (!header_size) - return -1; + assert(pdu->hdr_size > 0); switch(session->proto) { case COAP_PROTO_UDP: - bytes_written = coap_session_send(session, pdu->token - header_size, - pdu->used_size + header_size); + bytes_written = coap_session_send(session, pdu->token - pdu->hdr_size, + pdu->used_size + pdu->hdr_size); break; case COAP_PROTO_DTLS: - bytes_written = coap_dtls_send(session, pdu->token - header_size, - pdu->used_size + header_size); + bytes_written = coap_dtls_send(session, pdu->token - pdu->hdr_size, + pdu->used_size + pdu->hdr_size); break; case COAP_PROTO_TCP: - bytes_written = coap_session_send(session, pdu->token - header_size, - pdu->used_size + header_size); + bytes_written = coap_socket_write(&session->sock, + pdu->token - pdu->hdr_size, pdu->used_size + pdu->hdr_size); break; case COAP_PROTO_TLS: - bytes_written = coap_tls_send(session, pdu->token - header_size, - pdu->used_size + header_size, 1); + bytes_written = coap_tls_send(session, pdu->token - pdu->hdr_size, + pdu->used_size + pdu->hdr_size, 1); break; default: break; @@ -698,13 +688,34 @@ coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node) { session->state = COAP_SESSION_STATE_HANDSHAKE; return coap_session_delay_pdu(session, pdu, node); } + return -1; + } else if(COAP_PROTO_RELIABLE(session->proto)) { + if (!coap_socket_connect_tcp1( + &session->sock, &session->local_if, &session->remote_addr, + session->proto == COAP_PROTO_TLS ? COAPS_DEFAULT_PORT : COAP_DEFAULT_PORT, + &session->local_addr, &session->remote_addr + ) || (session->sock.flags & COAP_SOCKET_WANT_CONNECT) != 0 ) { + if ((session->sock.flags & COAP_SOCKET_WANT_CONNECT) != 0 ) + session->state = COAP_SESSION_STATE_CONNECTING; + return coap_session_delay_pdu(session, pdu, node); + } + if (session->proto == COAP_PROTO_TLS) { + /* ... */ + } else { + coap_session_connected(session); + } + } else { + return -1; } - return -1; } if (session->state != COAP_SESSION_STATE_ESTABLISHED) return coap_session_delay_pdu(session, pdu, node); + if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) && + (session->sock.flags & COAP_SOCKET_WANT_WRITE)) + return coap_session_delay_pdu(session, pdu, node); + bytes_written = coap_session_send_pdu(session, pdu); #endif /* WITH_LWIP */ @@ -835,7 +846,12 @@ coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_tid_t coap_send(coap_session_t *session, coap_pdu_t *pdu) { uint8_t r; - ssize_t bytes_written = coap_send_pdu(session, pdu, NULL); + ssize_t bytes_written; + + if (!coap_pdu_encode_header(pdu, session->proto)) + return COAP_INVALID_TID; + + bytes_written = coap_send_pdu( session, pdu, NULL ); if (bytes_written == COAP_PDU_DELAYED) return pdu->tid; @@ -845,6 +861,17 @@ coap_send(coap_session_t *session, coap_pdu_t *pdu) { return (coap_tid_t)bytes_written; } + if (COAP_PROTO_RELIABLE(session->proto) && + (size_t)bytes_written < pdu->used_size + pdu->hdr_size) { + if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) { + session->partial_write = (size_t)bytes_written; + return pdu->tid; + } else { + coap_delete_pdu(pdu); + return COAP_INVALID_TID; + } + } + if (pdu->type != COAP_MESSAGE_CON || COAP_PROTO_RELIABLE(session->proto)) { coap_tid_t id = pdu->tid; coap_delete_pdu(pdu); @@ -937,8 +964,6 @@ coap_retransmit(coap_context_t *context, coap_queue_t *node) { return COAP_INVALID_TID; } -void coap_dispatch(coap_context_t *context, coap_queue_t *rcvd); - #ifdef WITH_LWIP /* WITH_LWIP, this is handled by coap_recv in a different way */ int @@ -948,7 +973,7 @@ coap_read(coap_context_t *ctx) { #else /* WITH_LWIP */ static int -coap_handle_message_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet) { +coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet) { uint8_t *data; size_t data_len; int result = -1; @@ -961,49 +986,166 @@ coap_handle_message_for_proto(coap_context_t *ctx, coap_session_t *session, coap else if (session->tls) result = coap_dtls_receive(session, data, data_len); } else if (session->proto == COAP_PROTO_UDP) { - result = coap_handle_message(ctx, session, data, data_len); + result = coap_handle_dgram(ctx, session, data, data_len); } - return result; } -static int -coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now) { - ssize_t bytes_read = -1; - int result = -1; /* the value to be returned */ -#ifdef WITH_CONTIKI - coap_packet_t *packet = coap_malloc_packet(); -#else /* WITH_CONTIKI */ - coap_packet_t s_packet; - coap_packet_t *packet = &s_packet; -#endif /* WITH_CONTIKI */ +static void +coap_connect_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now) { + if (coap_socket_connect_tcp2(&session->sock, &session->local_addr, &session->remote_addr)) { + session->last_rx_tx = now; + if (session->proto == COAP_PROTO_TCP) { + coap_session_connected(session); + } else { + /* ... */ + } + } else { + coap_session_reset(session); + } +} + +static void +coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now) { + ssize_t bytes_written = -1; assert(session->sock.flags & COAP_SOCKET_CONNECTED); - if (packet) { - coap_address_copy(&packet->src, &session->remote_addr); - coap_address_copy(&packet->dst, &session->local_addr); - bytes_read = ctx->network_read(&session->sock, packet); + while (session->sendqueue) { + ssize_t bytes_written; + coap_queue_t *q = session->sendqueue; + debug("** %s tid=%d: transmitted after delay\n", coap_session_str(session), (int)q->pdu->tid); + assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size); + switch (session->proto) { + case COAP_PROTO_TCP: + bytes_written = coap_socket_write( + &session->sock, + q->pdu->token - q->pdu->hdr_size - session->partial_write, + q->pdu->used_size + q->pdu->hdr_size - session->partial_write + ); + break; + case COAP_PROTO_TLS: + bytes_written = coap_tls_send( + session, + q->pdu->token - q->pdu->hdr_size - session->partial_write, + q->pdu->used_size + q->pdu->hdr_size - session->partial_write, + 0 + ); + break; + } + if (bytes_written > 0) + session->last_rx_tx = now; + if (bytes_written <= 0 || (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) { + if (bytes_written > 0) + session->partial_write += (size_t)bytes_written; + break; + } + session->sendqueue = q->next; + session->partial_write = 0; + coap_delete_node(q); } +} - if (bytes_read < 0) { - if (bytes_read == -2) - coap_session_reset(session); - else - warn("* %s: read error\n", coap_session_str(session)); - } else if (bytes_read > 0) { - debug("* %s: received %zd bytes\n", coap_session_str(session), bytes_read); - session->last_rx_tx = now; - coap_packet_set_addr(packet, &session->remote_addr, &session->local_addr); - result = coap_handle_message_for_proto(ctx, session, packet); - } +static void +coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now) { + ssize_t bytes_read = -1; + assert(session->sock.flags & COAP_SOCKET_CONNECTED); + + if (COAP_PROTO_NOT_RELIABLE(session->proto)) { #ifdef WITH_CONTIKI - if ( packet ) - coap_free_packet(packet); -#endif + coap_packet_t *packet = coap_malloc_packet(); +#else /* WITH_CONTIKI */ + coap_packet_t s_packet; + coap_packet_t *packet = &s_packet; +#endif /* WITH_CONTIKI */ - return result; + if (packet) { + coap_address_copy(&packet->src, &session->remote_addr); + coap_address_copy(&packet->dst, &session->local_addr); + bytes_read = ctx->network_read(&session->sock, packet); + } + + if (bytes_read < 0) { + if (bytes_read == -2) + coap_session_reset(session); + else + warn("* %s: read error\n", coap_session_str(session)); + } else if (bytes_read > 0) { + debug("* %s: received %zd bytes\n", coap_session_str(session), bytes_read); + session->last_rx_tx = now; + coap_packet_set_addr(packet, &session->remote_addr, &session->local_addr); + coap_handle_dgram_for_proto(ctx, session, packet); + } + + #ifdef WITH_CONTIKI + if ( packet ) + coap_free_packet(packet); + #endif + } else { + while (1) { + if (session->partial_pdu) { + size_t len = session->partial_pdu->used_size + + session->partial_pdu->hdr_size + - session->partial_read; + size_t offset = session->partial_read - session->partial_pdu->hdr_size; + if ( len > 0 ) + bytes_read = coap_socket_read(&session->sock, session->partial_pdu->token + offset, len); + else + bytes_read = 0; + if (bytes_read == (ssize_t)len) { + if (coap_pdu_parse_header(session->partial_pdu, session->proto) + && coap_pdu_parse_opt(session->partial_pdu, session->proto)) { + coap_dispatch(ctx, session, session->partial_pdu); + } + coap_delete_pdu(session->partial_pdu); + session->partial_pdu = NULL; + session->partial_read = 0; + } else { + if (bytes_read > 0) + session->partial_read += bytes_read; + break; + } + } else if (session->partial_read > 0) { + size_t hdr_size = coap_pdu_parse_header_size(session->proto, + session->read_header); + size_t len = hdr_size - session->partial_read; + bytes_read = coap_socket_read(&session->sock, session->read_header + + session->partial_read, len); + if (bytes_read == (ssize_t)len ) { + size_t size = coap_pdu_parse_size(session->proto, session->read_header, + hdr_size); + session->partial_pdu = coap_pdu_init(0, 0, 0, size); + if (session->partial_pdu == NULL) { + coap_session_disconnected(session, COAP_NACK_NOT_DELIVERABLE); + break; + } + session->partial_pdu->hdr_size = (uint8_t)hdr_size; + session->partial_pdu->used_size = size; + memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size); + session->partial_read = hdr_size; + } else { + if (bytes_read > 0) + session->partial_read += bytes_read; + break; + } + } else { + bytes_read = coap_socket_read(&session->sock, session->read_header, 1); + if (bytes_read > 0) { + if (!coap_pdu_parse_header_size(session->proto, + session->read_header)) { + coap_session_disconnected(session, COAP_NACK_NOT_DELIVERABLE); + break; + } + session->partial_read = 1; + } else { + break; + } + } + } + if (bytes_read < 0) + coap_session_disconnected(session, COAP_NACK_NOT_DELIVERABLE); + } } static int @@ -1017,7 +1159,8 @@ coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t n coap_packet_t *packet = &s_packet; #endif /* WITH_CONTIKI */ - assert(endpoint->sock.flags&COAP_SOCKET_BOUND); + assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto)); + assert(endpoint->sock.flags & COAP_SOCKET_BOUND); if (packet) { coap_address_init(&packet->src); @@ -1031,7 +1174,7 @@ coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t n coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now); if (session) { debug("* %s: received %zd bytes\n", coap_session_str(session), bytes_read); - result = coap_handle_message_for_proto(ctx, session, packet); + result = coap_handle_dgram_for_proto(ctx, session, packet); if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1) coap_endpoint_new_dtls_session(endpoint, packet, now); } @@ -1045,97 +1188,85 @@ coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t n return result; } +static int +coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) { + return 0; +} + +static int +coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, + coap_tick_t now) { + coap_session_t *session = coap_new_server_session(ctx, endpoint); + return session != NULL; +} + void coap_read(coap_context_t *ctx, coap_tick_t now) { coap_endpoint_t *ep, *tmp; coap_session_t *s, *tmp_s; LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) { - if ((ep->sock.flags & COAP_SOCKET_HAS_DATA) != 0) + if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0) coap_read_endpoint(ctx, ep, now); + if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) + coap_write_endpoint(ctx, ep, now); + if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0) + coap_accept_endpoint(ctx, ep, now); + LL_FOREACH_SAFE(ep->sessions, s, tmp_s) { + if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) { + /* Make sure the session object is not deleted in one of the callbacks */ + coap_session_reference(s); + coap_read_session(ctx, s, now); + coap_session_release(s); + } + if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) + coap_write_session(ctx, s, now); + } } LL_FOREACH_SAFE(ctx->sessions, s, tmp_s) { - if ((s->sock.flags & COAP_SOCKET_HAS_DATA) != 0) { + if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) { /* Make sure the session object is not deleted in one of the callbacks */ coap_session_reference(s); coap_read_session(ctx, s, now); - coap_session_release(s); - } + coap_session_release(s); + } + if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) + coap_write_session(ctx, s, now); + if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) + coap_connect_session(ctx, s, now); } - } #endif /* not WITH_LWIP */ int -coap_handle_message(coap_context_t *ctx, coap_session_t *session, +coap_handle_dgram(coap_context_t *ctx, coap_session_t *session, uint8_t *msg, size_t msg_len) { - coap_queue_t *node; - /* the negated result code */ - enum result_t { RESULT_OK, RESULT_ERR_EARLY, RESULT_ERR }; - int result = RESULT_ERR_EARLY; + coap_pdu_t *pdu = NULL; - if ( COAP_PROTO_RELIABLE(session->proto) ) { - warn( "tcp not implemented\n" ); - goto error_early; - } - - node = coap_new_node(); - if (!node) { - goto error_early; - } - - /* from this point, the result code indicates that */ - result = RESULT_ERR; + assert(COAP_PROTO_NOT_RELIABLE(session->proto)); #ifdef WITH_LWIP - node->pdu = coap_pdu_from_pbuf(coap_packet_extract_pbuf(packet)); + pdu = coap_pdu_from_pbuf(coap_packet_extract_pbuf(packet)); #else - node->pdu = coap_pdu_init(0, 0, 0, msg_len - 4); + pdu = coap_pdu_init(0, 0, 0, msg_len - 4); #endif - if (!node->pdu) { + if (!pdu) goto error; - } - if (!coap_pdu_parse(session->proto, msg, msg_len, node->pdu)) { + if (!coap_pdu_parse(session->proto, msg, msg_len, pdu)) { warn("discard malformed PDU\n"); goto error; } - coap_ticks(&node->t); - - /* and add new node to receive queue */ - node->session = coap_session_reference(session); - node->id = node->pdu->tid; - -#ifndef NDEBUG - if (LOG_DEBUG <= coap_get_log_level()) { -#ifndef INET6_ADDRSTRLEN -#define INET6_ADDRSTRLEN 40 -#endif - /** @FIXME get debug to work again ** - unsigned char addr[INET6_ADDRSTRLEN+8], localaddr[INET6_ADDRSTRLEN+8]; - if (coap_print_addr(remote, addr, INET6_ADDRSTRLEN+8) && - coap_print_addr(&packet->dst, localaddr, INET6_ADDRSTRLEN+8) ) - debug("** received %d bytes from %s on interface %s:\n", - (int)msg_len, addr, localaddr); - - */ - coap_show_pdu(node->pdu); - } -#endif - - coap_dispatch(ctx, node); - return -RESULT_OK; + coap_dispatch(ctx, session, pdu); + return 0; error: /* FIXME: send back RST? */ - coap_delete_node(node); - return -result; - -error_early: - return -result; + coap_delete_pdu(pdu); + return -1; } int @@ -1398,12 +1529,13 @@ coap_wellknown_response(coap_context_t *context, coap_session_t *session, coap_pdu_t *resp; coap_opt_iterator_t opt_iter; size_t len, wkc_len; - unsigned char buf[2]; + uint8_t buf[2]; int result = 0; int need_block2 = 0; /* set to 1 if Block2 option is required */ coap_block_t block; coap_opt_t *query_filter; size_t offset = 0; + uint8_t *data; resp = coap_pdu_init(request->type == COAP_MESSAGE_CON ? COAP_MESSAGE_ACK @@ -1451,7 +1583,7 @@ coap_wellknown_response(coap_context_t *context, coap_session_t *session, * and data. We do this before adding the Content-Format option to * avoid sending error responses with that option but no actual * content. */ - if (resp->max_size <= resp->used_size + 3) { + if (resp->max_size && resp->max_size <= resp->used_size + 3) { debug("coap_wellknown_response: insufficient storage space\n"); goto error; } @@ -1465,14 +1597,14 @@ coap_wellknown_response(coap_context_t *context, coap_session_t *session, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf); /* check if Block2 option is required even if not requested */ - if (!need_block2 && ((size_t)resp->max_size - resp->used_size < wkc_len)) { + if (!need_block2 && resp->max_size && resp->max_size - resp->used_size < wkc_len + 1) { assert(resp->used_size <= resp->max_size); const size_t payloadlen = resp->max_size - resp->used_size; /* yes, need block-wise transfer */ block.num = 0; block.m = 0; /* the M bit is set by coap_write_block_opt() */ block.szx = COAP_MAX_BLOCK_SZX; - while (payloadlen < SZX_TO_BYTES(block.szx)) { + while (payloadlen < SZX_TO_BYTES(block.szx) + 6) { if (block.szx == 0) { debug("coap_wellknown_response: message to small even for szx == 0\n"); goto error; @@ -1492,20 +1624,19 @@ coap_wellknown_response(coap_context_t *context, coap_session_t *session, } } - /* Manually set payload of response to let print_wellknown() write, - * into our buffer without copying data. */ + len = need_block2 ? SZX_TO_BYTES( block.szx ) : resp->max_size ? resp->max_size - resp->used_size : wkc_len; + data = coap_add_data_after(resp, len); + if (!data) { + debug( "coap_wellknown_response: coap_add_data failed\n" ); + goto error; + } - resp->token[resp->used_size++] = COAP_PAYLOAD_START; - resp->data = resp->token + resp->used_size; - len = need_block2 ? SZX_TO_BYTES(block.szx) : resp->max_size - resp->used_size; - - result = coap_print_wellknown(context, resp->data, &len, offset, query_filter); + result = coap_print_wellknown(context, data, &len, offset, query_filter); if ((result & COAP_PRINT_STATUS_ERROR) != 0) { debug("coap_print_wellknown failed\n"); goto error; } - resp->used_size = resp->used_size + COAP_PRINT_OUTPUT_LENGTH(result); return resp; error: @@ -1620,7 +1751,7 @@ no_response(coap_pdu_t *request, coap_pdu_t *response) { (((Pdu)->code == COAP_REQUEST_GET) && is_wkc(Key)) static void -handle_request(coap_context_t *context, coap_queue_t *node) { +handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu) { coap_method_handler_t h = NULL; coap_pdu_t *response = NULL; coap_opt_filter_t opt_filter; @@ -1635,7 +1766,7 @@ handle_request(coap_context_t *context, coap_queue_t *node) { coap_option_filter_clear(opt_filter); /* try to find the resource from the request URI */ - coap_hash_request_uri(node->pdu, key); + coap_hash_request_uri(pdu, key); resource = coap_get_resource_from_key(context, key); if (!resource) { @@ -1644,12 +1775,12 @@ handle_request(coap_context_t *context, coap_queue_t *node) { * response, otherwise, we return 4.04 */ if (is_wkc(key)) { /* request for .well-known/core */ - if (node->pdu->code == COAP_REQUEST_GET) { /* GET */ + if (pdu->code == COAP_REQUEST_GET) { /* GET */ info("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN); - response = coap_wellknown_response(context, node->session, node->pdu); + response = coap_wellknown_response(context, session, pdu); } else { debug("method not allowed for .well-known/core\n"); - response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405), + response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405), opt_filter); } } else { /* request for any another resource, return 4.04 */ @@ -1657,13 +1788,13 @@ handle_request(coap_context_t *context, coap_queue_t *node) { debug("request for unknown resource 0x%02x%02x%02x%02x, return 4.04\n", key[0], key[1], key[2], key[3]); response = - coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(404), + coap_new_error_response(pdu, COAP_RESPONSE_CODE(404), opt_filter); } - if (response && (no_response(node->pdu, response) != RESPONSE_DROP)) { - if (coap_send(node->session, response) == COAP_INVALID_TID) - warn("cannot send response for transaction %u\n", node->id); + if (response && (no_response(pdu, response) != RESPONSE_DROP)) { + if (coap_send(session, response) == COAP_INVALID_TID) + warn("cannot send response for transaction %u\n", pdu->tid); } else { coap_delete_pdu(response); } @@ -1674,32 +1805,31 @@ handle_request(coap_context_t *context, coap_queue_t *node) { } /* the resource was found, check if there is a registered handler */ - if ((size_t)node->pdu->code - 1 < + if ((size_t)pdu->code - 1 < sizeof(resource->handler) / sizeof(coap_method_handler_t)) - h = resource->handler[node->pdu->code - 1]; + h = resource->handler[pdu->code - 1]; if (h) { - str *query = coap_get_query(node->pdu); + str *query = coap_get_query(pdu); int owns_query = 1; debug("call custom handler for resource 0x%02x%02x%02x%02x\n", key[0], key[1], key[2], key[3]); - response = coap_pdu_init(node->pdu->type == COAP_MESSAGE_CON + response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON, - 0, node->pdu->tid, coap_session_max_pdu_size(node->session)); + 0, pdu->tid, coap_session_max_pdu_size(session)); /* Implementation detail: coap_add_token() immediately returns 0 if response == NULL */ - if (coap_add_token(response, node->pdu->token_length, - node->pdu->token)) { - str token = { node->pdu->token_length, node->pdu->token }; + if (coap_add_token(response, pdu->token_length, pdu->token)) { + str token = { pdu->token_length, pdu->token }; coap_opt_iterator_t opt_iter; coap_opt_t *observe = NULL; int observe_action = COAP_OBSERVE_CANCEL; /* check for Observe option */ if (resource->observable) { - observe = coap_check_option(node->pdu, COAP_OPTION_OBSERVE, &opt_iter); + observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter); if (observe) { observe_action = coap_decode_var_bytes(coap_opt_value(observe), @@ -1709,28 +1839,28 @@ handle_request(coap_context_t *context, coap_queue_t *node) { coap_subscription_t *subscription; coap_log(LOG_DEBUG, "create new subscription\n"); - subscription = coap_add_observer(resource, node->session, &token, query); + subscription = coap_add_observer(resource, session, &token, query); owns_query = 0; if (subscription) { - coap_touch_observer(context, node->session, &token); + coap_touch_observer(context, session, &token); } } else { coap_log(LOG_DEBUG, "removed observer\n"); - coap_delete_observer(resource, node->session, &token); + coap_delete_observer(resource, session, &token); } } } - h(context, resource, node->session, node->pdu, &token, query, response); + h(context, resource, session, pdu, &token, query, response); if (query && owns_query) coap_delete_string(query); - respond = no_response(node->pdu, response); + respond = no_response(pdu, response); if (respond != RESPONSE_DROP) { if (observe && (COAP_RESPONSE_CLASS(response->code) > 2)) { coap_log(LOG_DEBUG, "removed observer\n"); - coap_delete_observer(resource, node->session, &token); + coap_delete_observer(resource, session, &token); } /* If original request contained a token, and the registered @@ -1750,8 +1880,8 @@ handle_request(coap_context_t *context, coap_queue_t *node) { (response->code >= 64 && !coap_mcast_interface(&node->local_if)))) { - if (coap_send(node->session, response) == COAP_INVALID_TID) - debug("cannot send response for message %d\n", node->pdu->tid); + if (coap_send(session, response) == COAP_INVALID_TID) + debug("cannot send response for message %d\n", pdu->tid); } else { coap_delete_pdu(response); } @@ -1763,17 +1893,17 @@ handle_request(coap_context_t *context, coap_queue_t *node) { warn("cannot generate response\r\n"); } } else { - if (WANT_WKC(node->pdu, key)) { + if (WANT_WKC(pdu, key)) { debug("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN); - response = coap_wellknown_response(context, node->session, node->pdu); + response = coap_wellknown_response(context, session, pdu); debug("have wellknown response %p\n", (void *)response); } else - response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405), + response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405), opt_filter); - if (response && (no_response(node->pdu, response) != RESPONSE_DROP)) { - if (coap_send(node->session, response) == COAP_INVALID_TID) - debug("cannot send response for transaction %d\n", node->id); + if (response && (no_response(pdu, response) != RESPONSE_DROP)) { + if (coap_send(session, response) == COAP_INVALID_TID) + debug("cannot send response for transaction %d\n", pdu->tid); } else { coap_delete_pdu(response); } @@ -1783,51 +1913,56 @@ handle_request(coap_context_t *context, coap_queue_t *node) { assert(response == NULL); } -COAP_STATIC_INLINE void -handle_response(coap_context_t *context, - coap_queue_t *sent, coap_queue_t *rcvd) { +static void +handle_response(coap_context_t *context, coap_session_t *session, + coap_pdu_t *sent, coap_pdu_t *rcvd) { - coap_send_ack(rcvd->session, rcvd->pdu); + coap_send_ack(session, rcvd); /* In a lossy context, the ACK of a separate response may have * been lost, so we need to stop retransmitting requests with the * same token. */ - coap_cancel_all_messages(context, rcvd->session, - rcvd->pdu->token, - rcvd->pdu->token_length); + coap_cancel_all_messages(context, session, rcvd->token, rcvd->token_length); /* Call application-specific response handler when available. */ if (context->response_handler) { - context->response_handler(context, rcvd->session, sent ? sent->pdu : NULL, - rcvd->pdu, rcvd->id); + context->response_handler(context, session, sent, rcvd, rcvd->tid); } } void -coap_dispatch(coap_context_t *context, coap_queue_t *rcvd) { +coap_dispatch(coap_context_t *context, coap_session_t *session, + coap_pdu_t *pdu) { coap_queue_t *sent = NULL; coap_pdu_t *response; coap_opt_filter_t opt_filter; - if (!context) - return; +#ifndef NDEBUG + if (LOG_DEBUG <= coap_get_log_level()) { +#ifndef INET6_ADDRSTRLEN +#define INET6_ADDRSTRLEN 40 +#endif + /** @FIXME get debug to work again ** + unsigned char addr[INET6_ADDRSTRLEN+8], localaddr[INET6_ADDRSTRLEN+8]; + if (coap_print_addr(remote, addr, INET6_ADDRSTRLEN+8) && + coap_print_addr(&packet->dst, localaddr, INET6_ADDRSTRLEN+8) ) + debug("** received %d bytes from %s on interface %s:\n", + (int)msg_len, addr, localaddr); + + */ + coap_show_pdu(pdu); + } +#endif memset(opt_filter, 0, sizeof(coap_opt_filter_t)); - { - /* version has been checked in coap_handle_message() */ - /* if ( rcvd->pdu->hdr->version != COAP_DEFAULT_VERSION ) { */ - /* debug("dropped packet with unknown version %u\n", rcvd->pdu->hdr->version); */ - /* goto cleanup; */ - /* } */ - - switch (rcvd->pdu->type) { + switch (pdu->type) { case COAP_MESSAGE_ACK: /* find transaction in sendqueue to stop retransmission */ - coap_remove_from_queue(&context->sendqueue, rcvd->session, rcvd->id, &sent); + coap_remove_from_queue(&context->sendqueue, session, pdu->tid, &sent); - if (rcvd->pdu->code == 0) + if (pdu->code == 0) goto cleanup; /* if sent code was >= 64 the message might have been a @@ -1845,14 +1980,10 @@ coap_dispatch(coap_context_t *context, coap_queue_t *rcvd) { * not only the transaction but also the subscriptions we might * have. */ -#ifndef WITH_CONTIKI - coap_log(LOG_ALERT, "got RST for message %d\n", rcvd->pdu->tid); -#else /* WITH_CONTIKI */ - coap_log(LOG_ALERT, "got RST for message %d\n", rcvd->pdu->tid)); -#endif /* WITH_CONTIKI */ + coap_log(LOG_ALERT, "got RST for message %d\n", pdu->tid); /* find transaction in sendqueue to stop retransmission */ - coap_remove_from_queue(&context->sendqueue, rcvd->session, rcvd->id, &sent); + coap_remove_from_queue(&context->sendqueue, session, pdu->tid, &sent); if (sent) coap_cancel(context, sent); @@ -1863,51 +1994,48 @@ coap_dispatch(coap_context_t *context, coap_queue_t *rcvd) { goto cleanup; case COAP_MESSAGE_NON: /* check for unknown critical options */ - if (coap_option_check_critical(context, rcvd->pdu, opt_filter) == 0) + if (coap_option_check_critical(context, pdu, opt_filter) == 0) goto cleanup; break; case COAP_MESSAGE_CON: /* check for unknown critical options */ - if (coap_option_check_critical(context, rcvd->pdu, opt_filter) == 0) { + if (coap_option_check_critical(context, pdu, opt_filter) == 0) { /* FIXME: send response only if we have received a request. Otherwise, * send RST. */ response = - coap_new_error_response(rcvd->pdu, COAP_RESPONSE_CODE(402), opt_filter); + coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), opt_filter); if (!response) { warn("coap_dispatch: cannot create error response\n"); } else { - if (coap_send(rcvd->session, response) == COAP_INVALID_TID) + if (coap_send(session, response) == COAP_INVALID_TID) warn("coap_dispatch: error sending response\n"); } goto cleanup; } default: break; - } - - /* Pass message to upper layer if a specific handler was - * registered for a request that should be handled locally. */ - if (COAP_PDU_IS_REQUEST(rcvd->pdu)) - handle_request(context, rcvd); - else if (COAP_PDU_IS_RESPONSE(rcvd->pdu)) - handle_response(context, sent, rcvd); - else { - debug("dropped message with invalid code (%d.%02d)\n", - COAP_RESPONSE_CLASS(rcvd->pdu->code), - rcvd->pdu->code & 0x1f); - - if (!coap_is_mcast(&rcvd->session->local_addr)) { - coap_send_message_type(rcvd->session, - rcvd->pdu, COAP_MESSAGE_RST); - } - } - - cleanup: - coap_delete_node(sent); - coap_delete_node(rcvd); } + + /* Pass message to upper layer if a specific handler was + * registered for a request that should be handled locally. */ + if (COAP_PDU_IS_REQUEST(pdu)) + handle_request(context, session, pdu); + else if (COAP_PDU_IS_RESPONSE(pdu)) + handle_response(context, session, sent ? sent->pdu : NULL, pdu); + else { + debug("dropped message with invalid code (%d.%02d)\n", + COAP_RESPONSE_CLASS(pdu->code), + pdu->code & 0x1f); + + if (!coap_is_mcast(&session->local_addr)) { + coap_send_message_type(session, pdu, COAP_MESSAGE_RST); + } + } + +cleanup: + coap_delete_node(sent); } int diff --git a/src/pdu.c b/src/pdu.c index 6eb05340..a37c0592 100644 --- a/src/pdu.c +++ b/src/pdu.c @@ -39,8 +39,11 @@ coap_pdu_clear(coap_pdu_t *pdu, size_t size) { assert(pdu); assert(pdu->token); assert(pdu->max_hdr_size >= COAP_PDU_MAX_UDP_HEADER_SIZE); + if (pdu->alloc_size > size) + pdu->alloc_size = size; pdu->type = 0; pdu->code = 0; + pdu->hdr_size = 0; pdu->token_length = 0; pdu->tid = 0; pdu->max_delta = 0; @@ -69,7 +72,8 @@ coap_pdu_from_pbuf( struct pbuf *pbuf ) pdu->max_hdr_size = COAP_PDU_MAX_UDP_HEADER_SIZE; pdu->pbuf = pbuf; pdu->token = pbuf->payload + pdu->max_hdr_size; - coap_pdu_clear(pdu, pbuf->tot_len - pdu->max_hdr_size); + pdu->alloc_size = pbuf->tot_len - pdu->max_hdr_size; + coap_pdu_clear(pdu, pdu->alloc_size); return pdu; } @@ -81,14 +85,11 @@ coap_pdu_init(uint8_t type, uint8_t code, uint16_t tid, size_t size) { uint8_t *buf; #ifdef WITH_CONTIKI - if (size == 0) + if (size == COAP_PDU_SIZE_DYNAMIC) size = COAP_RXBUFFER_SIZE - COAP_PDU_MAX_UDP_HEADER_SIZE; assert(size <= COAP_RXBUFFER_SIZE - COAP_PDU_MAX_UDP_HEADER_SIZE); if (size > COAP_RXBUFFER_SIZE - COAP_PDU_MAX_UDP_HEADER_SIZE) return NULL; -#else - if (size == 0) - size = 256; #endif pdu = coap_malloc_type(COAP_PDU, sizeof(coap_pdu_t)); @@ -107,9 +108,17 @@ coap_pdu_init(uint8_t type, uint8_t code, uint16_t tid, size_t size) { pdu = NULL; } pdu->token = pdu->pbuf->payload + pdu->max_hdr_size; - size = pbuf->tot_len - pdu->max_hdr_size; + if (size == COAP_PDU_SIZE_DYNAMIC) + size = pbuf->tot_len - pdu->max_hdr_size; + assert(size <= pbuf->tot_len - pdu->max_hdr_size); + if (size > pbuf->tot_len - pdu->max_hdr_size) + return NULL; #else /* WITH_LWIP */ - buf = coap_malloc_type(COAP_PDU_BUF, size + pdu->max_hdr_size); + if (size != COAP_PDU_SIZE_DYNAMIC) + pdu->alloc_size = size; + else + pdu->alloc_size = 256; + buf = coap_malloc_type(COAP_PDU_BUF, pdu->alloc_size + pdu->max_hdr_size); if (buf == NULL) { coap_free_type(COAP_PDU, pdu); pdu = NULL; @@ -124,8 +133,8 @@ coap_pdu_init(uint8_t type, uint8_t code, uint16_t tid, size_t size) { } coap_pdu_t * -coap_new_pdu() { - coap_pdu_t *pdu = coap_pdu_init(0, 0, 0, 0); +coap_new_pdu(struct coap_session_t *session) { + coap_pdu_t *pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_size(session)); #ifndef NDEBUG if (!pdu) coap_log(LOG_CRIT, "coap_new_pdu: cannot allocate memory for new PDU\n"); @@ -147,23 +156,19 @@ coap_delete_pdu(coap_pdu_t *pdu) { } static int coap_pdu_resize(coap_pdu_t *pdu, size_t new_size) { - if (new_size > pdu->max_size) { -#if defined(WITH_LWIP) - if (new_size > pbuf->tot_len - pdu->max_hdr_size) { - warn( "coap_pdu_resize: pdu too big\n" ); - return NULL; - } -#elif defined(WITH_CONTIKI) - if (new_size > COAP_RXBUFFER_SIZE - COAP_PDU_MAX_UDP_HEADER_SIZE) { - warn( "coap_pdu_resize: pdu too big\n" ); - return NULL; - } -#else + if (new_size > pdu->alloc_size) { uint8_t *new_hdr; - size_t offset = 0; + size_t offset; + if (pdu->max_size && new_size > pdu->max_size) { + warn( "coap_pdu_resize: pdu too big\n" ); + return 0; + } +#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI) if (pdu->data != NULL) { assert(pdu->data > pdu->token); offset = pdu->data - pdu->token; + } else { + offset = 0; } new_hdr = (uint8_t*)realloc(pdu->token - pdu->max_hdr_size, new_size + pdu->max_hdr_size); if (new_hdr == NULL) { @@ -177,18 +182,14 @@ static int coap_pdu_resize(coap_pdu_t *pdu, size_t new_size) { pdu->data = NULL; #endif } - pdu->max_size = new_size; + pdu->alloc_size = new_size; return 1; } static int coap_pdu_check_resize(coap_pdu_t *pdu, size_t size) { - if (size > pdu->max_size) { -#if defined(WITH_LWIP) || defined(WITH_CONTIKI) - warn("coap_pdu_check_resize: cannot resize\n"); - return 0; -#endif - size_t new_size = pdu->max_size * 2; + if (size > pdu->alloc_size) { + size_t new_size = max(256, pdu->alloc_size * 2); while (size > new_size) new_size *= 2; if (!coap_pdu_resize(pdu, new_size)) @@ -229,13 +230,15 @@ coap_add_option(coap_pdu_t *pdu, uint16_t type, size_t len, const uint8_t *data) return 0; } +#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI) if (!coap_pdu_check_resize(pdu, pdu->used_size + len + 5)) return 0; +#endif opt = pdu->token + pdu->used_size; /* encode option and check length */ - optsize = coap_opt_encode(opt, pdu->max_size - pdu->used_size, + optsize = coap_opt_encode(opt, pdu->alloc_size - pdu->used_size, type - pdu->max_delta, data, len); if (!optsize) { @@ -264,13 +267,15 @@ coap_add_option_later(coap_pdu_t *pdu, uint16_t type, size_t len) { return NULL; } +#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI) if (!coap_pdu_check_resize(pdu, pdu->used_size + len + 5)) return 0; +#endif opt = pdu->token + pdu->used_size; /* encode option and check length */ - optsize = coap_opt_encode(opt, pdu->max_size - pdu->used_size, + optsize = coap_opt_encode(opt, pdu->alloc_size - pdu->used_size, type - pdu->max_delta, NULL, len); if (!optsize) { @@ -432,7 +437,7 @@ coap_pdu_parse_size(coap_proto_t proto, if ((proto == COAP_PROTO_TCP || proto==COAP_PROTO_TLS) && length >= 1) { uint8_t len = *data >> 4; if (len < 13) { - size = len - 2; + size = len; } else if (length >= 2) { if (len==13) { size = (size_t)data[1] + 13; @@ -444,99 +449,50 @@ coap_pdu_parse_size(coap_proto_t proto, } } } + size += data[0] & 0x0f; } return size; } int -coap_pdu_parse_opt(coap_proto_t proto, - const uint8_t *data, - size_t length, - coap_pdu_t *pdu, - size_t *offset) -{ - const coap_opt_t *opt; - const uint8_t *token; - - assert(data); - assert(pdu); - - *offset = 0; - -#ifdef WITH_LWIP - /* this verifies that with the classical copy-at-parse-time and lwip's - * zerocopy-into-place approaches, both share the same idea of destination - * addresses */ - LWIP_ASSERT("coap_pdu_parse with unexpected addresses", data == pdu->token - 4); - LWIP_ASSERT("coap_pdu_parse with unexpected length", length == pdu->used_size + 4); -#endif - +coap_pdu_parse_header(coap_pdu_t *pdu, coap_proto_t proto) { + uint8_t *hdr = pdu->token - pdu->hdr_size; if (proto == COAP_PROTO_UDP || proto == COAP_PROTO_DTLS) { - if (length < 4) { - debug( "coap_pdu_parse: UDP header too short\n" ); - return 0; - } - uint8_t version = data[0] >> 6; - if (version != COAP_DEFAULT_VERSION) { + assert(pdu->hdr_size == 4); + if ((hdr[0] >> 6) != COAP_DEFAULT_VERSION) { debug( "coap_pdu_parse: UDP version not supported\n" ); return 0; } - pdu->type = (data[0] >> 4) & 0x03; - pdu->token_length = data[0] & 0x0f; - pdu->code = data[1]; - pdu->tid = (uint16_t)data[2] << 8 | data[3]; - token = data + 4; - } else if (proto == COAP_PROTO_UDP || proto == COAP_PROTO_DTLS) { - uint8_t len; - if (length < 2) { - debug( "coap_pdu_parse: TCP header too short\n" ); - return 0; - } - len = data[0] >> 4; - if (len < 13) { - pdu->code = data[1]; - token = data + 2; - } else if (len == 13) { - if (length < 3) { - debug( "coap_pdu_parse: TCP8 header too short\n" ); - return 0; - } - pdu->code = data[2]; - token = data + 3; - } else if (len == 14) { - if (length < 4) { - debug( "coap_pdu_parse: TCP16 header too short\n" ); - return 0; - } - pdu->code = data[3]; - token = data + 4; - } else { - if (length < 6) { - debug( "coap_pdu_parse: TCP32 header too short\n" ); - return 0; - } - pdu->code = data[5]; - token = data + 6; - } + pdu->type = (hdr[0] >> 4) & 0x03; + pdu->token_length = hdr[0] & 0x0f; + pdu->code = hdr[1]; + pdu->tid = (uint16_t)hdr[2] << 8 | hdr[3]; + } else if (proto == COAP_PROTO_TCP || proto == COAP_PROTO_TLS) { + assert(pdu->hdr_size >= 2 && pdu->hdr_size <= 6); pdu->type = COAP_MESSAGE_CON; - pdu->token_length = data[0] & 0x0f; + pdu->token_length = hdr[0] & 0x0f; + pdu->code = hdr[pdu->hdr_size-1]; pdu->tid = 0; } else { debug( "coap_pdu_parse: unsupported protocol\n" ); return 0; } + return 1; +} + +int +coap_pdu_parse_opt(coap_pdu_t *pdu, coap_proto_t proto) { /* sanity checks */ if (pdu->code == 0) { - if (length != token - data || pdu->token_length) { + if (pdu->used_size != 0 || pdu->token_length) { debug("coap_pdu_parse: empty message is not empty\n"); return 0; } } - if (token + pdu->token_length > data + length - || pdu->token_length > 8) { + if (pdu->token_length > pdu->used_size || pdu->token_length > 8) { debug("coap_pdu_parse: invalid Token\n"); return 0; } @@ -544,10 +500,11 @@ coap_pdu_parse_opt(coap_proto_t proto, if (pdu->code == 0) { /* empty packet */ pdu->used_size = 0; + pdu->data = NULL; } else { /* skip header + token */ - opt = token + pdu->token_length; - length = data + length - opt; + coap_opt_t *opt = pdu->token + pdu->token_length; + size_t length = pdu->used_size - pdu->token_length; while (length > 0 && *opt != COAP_PAYLOAD_START) { if ( !next_option_safe( &opt, (size_t *)&length ) ) { @@ -565,17 +522,10 @@ coap_pdu_parse_opt(coap_proto_t proto, return 0; } } - - if (opt > token) { - if (!coap_pdu_check_resize(pdu, opt - token)) - return 0; - - /* Append options (including the token) to pdu structure, if any. */ - memcpy(pdu->token, token, opt - token); - pdu->used_size = opt - token; - - *offset = opt - data; - } + if (length > 0) + pdu->data = opt; + else + pdu->data = NULL; } return 1; @@ -587,18 +537,21 @@ coap_pdu_parse(coap_proto_t proto, size_t length, coap_pdu_t *pdu) { - size_t offset; - if (coap_pdu_parse_opt(proto, data, length, pdu, &offset) == 0) + size_t hdr_size; + + if (length == 0) return 0; - length -= offset; - if (offset == 0 || length == 0) - return 1; - if (!coap_pdu_resize(pdu, pdu->used_size + length)) + hdr_size = coap_pdu_parse_header_size(proto, data); + if (!hdr_size || hdr_size > length) return 0; - pdu->data = pdu->token + pdu->used_size; - memcpy(pdu->data, data + offset, length); - pdu->used_size += length; - return 1; + if (hdr_size > pdu->max_hdr_size) + return 0; + if (!coap_pdu_resize(pdu, length - hdr_size)) + return 0; + memcpy(pdu->token - hdr_size, data, length); + pdu->hdr_size = (uint8_t)hdr_size; + pdu->used_size = length - hdr_size; + return coap_pdu_parse_header(pdu, proto) && coap_pdu_parse_opt(pdu, proto); } size_t @@ -615,7 +568,7 @@ coap_pdu_encode_header(coap_pdu_t *pdu, coap_proto_t proto) { pdu->token[-3] = pdu->code; pdu->token[-2] = (uint8_t)(pdu->tid >> 8); pdu->token[-1] = (uint8_t)(pdu->tid); - return 4; + pdu->hdr_size = 4; } else if (proto == COAP_PROTO_TCP || proto == COAP_PROTO_TLS) { size_t len; assert(pdu->used_size >= pdu->token_length); @@ -633,7 +586,7 @@ coap_pdu_encode_header(coap_pdu_t *pdu, coap_proto_t proto) { pdu->token[-2] = (uint8_t)len << 4 | pdu->token_length; pdu->token[-1] = pdu->code; - return 2; + pdu->hdr_size = 2; } else if (len < 269) { assert(pdu->max_hdr_size >= 3); if (pdu->max_hdr_size < 3) { @@ -643,7 +596,7 @@ coap_pdu_encode_header(coap_pdu_t *pdu, coap_proto_t proto) { pdu->token[-3] = 13 << 4 | pdu->token_length; pdu->token[-2] = (uint8_t)(len - 13); pdu->token[-1] = pdu->code; - return 3; + pdu->hdr_size = 3; } else if (len < 65805) { assert(pdu->max_hdr_size >= 4); if (pdu->max_hdr_size < 4) { @@ -654,7 +607,7 @@ coap_pdu_encode_header(coap_pdu_t *pdu, coap_proto_t proto) { pdu->token[-3] = (uint8_t)((len - 269) >> 8); pdu->token[-2] = (uint8_t)(len - 269); pdu->token[-1] = pdu->code; - return 4; + pdu->hdr_size = 4; } else { assert(pdu->max_hdr_size >= 6); if (pdu->max_hdr_size < 6) { @@ -667,9 +620,10 @@ coap_pdu_encode_header(coap_pdu_t *pdu, coap_proto_t proto) { pdu->token[-3] = (uint8_t)((len - 65805) >> 8); pdu->token[-2] = (uint8_t)(len - 65805); pdu->token[-1] = pdu->code; - return 6; + pdu->hdr_size = 6; } + } else { + warn("coap_pdu_encode_header: unsupported protocol"); } - warn("coap_pdu_encode_header: unsupported protocol"); - return 0; + return pdu->hdr_size; } diff --git a/tests/test_error_response.c b/tests/test_error_response.c index 17cbf6e3..b21f0be3 100644 --- a/tests/test_error_response.c +++ b/tests/test_error_response.c @@ -321,7 +321,7 @@ t_error_response8(void) { static int t_error_response_tests_create(void) { - pdu = coap_pdu_init(0, 0, 0, 0); + pdu = coap_pdu_init(0, 0, 0, COAP_PDU_SIZE_DYNAMIC); return pdu == NULL; } diff --git a/tests/test_pdu.c b/tests/test_pdu.c index 65cc7d7d..b887e6e4 100644 --- a/tests/test_pdu.c +++ b/tests/test_pdu.c @@ -268,7 +268,7 @@ t_encode_pdu2(void) { size_t old_max = pdu->max_size; int result; - coap_pdu_clear(pdu, 7); /* set very small PDU size */ + coap_pdu_clear(pdu, 3); /* set very small PDU size */ pdu->type = COAP_MESSAGE_CON; pdu->code = COAP_REQUEST_GET; @@ -276,7 +276,7 @@ t_encode_pdu2(void) { result = coap_add_token(pdu, 5, (unsigned char *)"token"); - CU_ASSERT(result == 1); + CU_ASSERT(result == 0); coap_pdu_clear(pdu, old_max); /* restore PDU size */ } @@ -609,16 +609,16 @@ t_encode_pdu11(void) { result = coap_add_data(pdu, 10, (unsigned char *)"0123456789"); coap_set_log_level(level); - CU_ASSERT(result == 1); - CU_ASSERT(pdu->data != NULL); - CU_ASSERT(pdu->used_size == 11); + CU_ASSERT(result == 0); + CU_ASSERT(pdu->data == NULL); + CU_ASSERT(pdu->used_size == 0); pdu->max_size = old_max; } static int t_pdu_tests_create(void) { - pdu = coap_pdu_init(0, 0, 0, 0); + pdu = coap_pdu_init(0, 0, 0, COAP_PDU_SIZE_DYNAMIC); return pdu == NULL; }