LWS_VISIBLE void lws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi) { lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ); context->fds[context->fds_count++].revents = 0; }
int remove_wsi_socket_from_fds(struct libwebsocket_context *context, struct libwebsocket *wsi) { int m; struct libwebsocket_pollargs pa = { wsi->sock, 0, 0 }; lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE); if (!--context->fds_count) { context->protocols[0].callback(context, wsi, LWS_CALLBACK_LOCK_POLL, wsi->user_space, (void *) &pa, 0); goto do_ext; } if (wsi->sock > context->max_fds) { lwsl_err("Socket fd %d too high (%d)\n", wsi->sock, context->max_fds); return 1; } lwsl_info("%s: wsi=%p, sock=%d, fds pos=%d\n", __func__, wsi, wsi->sock, wsi->position_in_fds_table); context->protocols[0].callback(context, wsi, LWS_CALLBACK_LOCK_POLL, wsi->user_space, (void *)&pa, 0); m = wsi->position_in_fds_table; /* replace the contents for this */ /* have the last guy take up the vacant slot */ context->fds[m] = context->fds[context->fds_count]; lws_plat_delete_socket_from_fds(context, wsi, m); /* * end guy's fds_lookup entry remains unchanged * (still same fd pointing to same wsi) */ /* end guy's "position in fds table" changed */ context->lws_lookup[context->fds[context->fds_count].fd]-> position_in_fds_table = m; /* deletion guy's lws_lookup entry needs nuking */ context->lws_lookup[wsi->sock] = NULL; /* removed wsi has no position any more */ wsi->position_in_fds_table = -1; do_ext: /* remove also from external POLL support via protocol 0 */ if (wsi->sock) { context->protocols[0].callback(context, wsi, LWS_CALLBACK_DEL_POLL_FD, wsi->user_space, (void *) &pa, 0); } context->protocols[0].callback(context, wsi, LWS_CALLBACK_UNLOCK_POLL, wsi->user_space, (void *) &pa, 0); return 0; }
int remove_wsi_socket_from_fds(struct lws *wsi) { int m; struct lws *end_wsi; struct lws_pollargs pa = { wsi->sock, 0, 0 }; struct lws_context *context = wsi->context; struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE); --pt->fds_count; #if !defined(_WIN32) && !defined(MBED_OPERATORS) if (wsi->sock > context->max_fds) { lwsl_err("Socket fd %d too high (%d)\n", wsi->sock, context->max_fds); return 1; } #endif lwsl_info("%s: wsi=%p, sock=%d, fds pos=%d\n", __func__, wsi, wsi->sock, wsi->position_in_fds_table); if (context->protocols[0].callback(wsi, LWS_CALLBACK_LOCK_POLL, wsi->user_space, (void *)&pa, 1)) return -1; m = wsi->position_in_fds_table; /* replace the contents for this */ /* have the last guy take up the vacant slot */ pt->fds[m] = pt->fds[pt->fds_count]; lws_plat_delete_socket_from_fds(context, wsi, m); /* * end guy's fds_lookup entry remains unchanged * (still same fd pointing to same wsi) */ /* end guy's "position in fds table" changed */ end_wsi = wsi_from_fd(context, pt->fds[pt->fds_count].fd); end_wsi->position_in_fds_table = m; /* deletion guy's lws_lookup entry needs nuking */ delete_from_fd(context, wsi->sock); /* removed wsi has no position any more */ wsi->position_in_fds_table = -1; /* remove also from external POLL support via protocol 0 */ if (lws_socket_is_valid(wsi->sock)) { if (context->protocols[0].callback(wsi, LWS_CALLBACK_DEL_POLL_FD, wsi->user_space, (void *) &pa, 0)) return -1; } if (context->protocols[0].callback(wsi, LWS_CALLBACK_UNLOCK_POLL, wsi->user_space, (void *) &pa, 1)) return -1; return 0; }
extern "C" LWS_VISIBLE void lws_plat_insert_socket_into_fds(struct libwebsocket_context *context, struct libwebsocket *wsi) { (void)wsi; lws_libev_io(context, wsi, LWS_EV_START | LWS_EV_READ); context->fds[context->fds_count++].revents = 0; }
LWS_VISIBLE void lws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi) { struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ); lws_libuv_io(wsi, LWS_EV_START | LWS_EV_READ); pt->fds[pt->fds_count++].revents = 0; }
LWS_VISIBLE void lws_plat_delete_socket_from_fds(struct lws_context *context, struct lws *wsi, int m) { struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE); lws_libuv_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE); pt->fds_count--; }
int lws_client_socket_service(struct lws_context *context, struct lws *wsi, struct lws_pollfd *pollfd) { struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; char *p = (char *)&pt->serv_buf[0]; char *sb = p; unsigned char c; int n, len; switch (wsi->mode) { case LWSCM_WSCL_WAITING_CONNECT: /* * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE * timeout protection set in client-handshake.c */ if (!lws_client_connect_2(wsi)) { /* closed */ lwsl_client("closed\n"); return -1; } /* either still pending connection, or changed mode */ return 0; case LWSCM_WSCL_WAITING_PROXY_REPLY: /* handle proxy hung up on us */ if (pollfd->revents & LWS_POLLHUP) { lwsl_warn("Proxy connection %p (fd=%d) dead\n", (void *)wsi, pollfd->fd); lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); return 0; } n = recv(wsi->sock, sb, LWS_MAX_SOCKET_IO_BUF, 0); if (n < 0) { if (LWS_ERRNO == LWS_EAGAIN) { lwsl_debug("Proxy read returned EAGAIN... retrying\n"); return 0; } lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); lwsl_err("ERROR reading from proxy socket\n"); return 0; } pt->serv_buf[13] = '\0'; if (strcmp(sb, "HTTP/1.0 200 ") && strcmp(sb, "HTTP/1.1 200 ")) { lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); lwsl_err("ERROR proxy: %s\n", sb); return 0; } /* clear his proxy connection timeout */ lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); /* fallthru */ case LWSCM_WSCL_ISSUE_HANDSHAKE: /* * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE * timeout protection set in client-handshake.c * * take care of our lws_callback_on_writable * happening at a time when there's no real connection yet */ if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) return -1; lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_WRITE); #ifdef LWS_OPENSSL_SUPPORT /* we can retry this... just cook the SSL BIO the first time */ if (wsi->use_ssl && !wsi->ssl) { #if defined(CYASSL_SNI_HOST_NAME) || defined(WOLFSSL_SNI_HOST_NAME) || defined(SSL_CTRL_SET_TLSEXT_HOSTNAME) const char *hostname = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST); #endif wsi->ssl = SSL_new(context->ssl_client_ctx); #ifndef USE_WOLFSSL SSL_set_mode(wsi->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); #endif /* * use server name indication (SNI), if supported, * when establishing connection */ #ifdef USE_WOLFSSL #ifdef USE_OLD_CYASSL #ifdef CYASSL_SNI_HOST_NAME CyaSSL_UseSNI(wsi->ssl, CYASSL_SNI_HOST_NAME, hostname, strlen(hostname)); #endif #else #ifdef WOLFSSL_SNI_HOST_NAME wolfSSL_UseSNI(wsi->ssl, WOLFSSL_SNI_HOST_NAME, hostname, strlen(hostname)); #endif #endif #else #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME SSL_set_tlsext_host_name(wsi->ssl, hostname); #endif #endif #ifdef USE_WOLFSSL /* * wolfSSL/CyaSSL does certificate verification differently * from OpenSSL. * If we should ignore the certificate, we need to set * this before SSL_new and SSL_connect is called. * Otherwise the connect will simply fail with error * code -155 */ #ifdef USE_OLD_CYASSL if (wsi->use_ssl == 2) CyaSSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, NULL); #else if (wsi->use_ssl == 2) wolfSSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, NULL); #endif #endif /* USE_WOLFSSL */ wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE); SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio); #ifdef USE_WOLFSSL #ifdef USE_OLD_CYASSL CyaSSL_set_using_nonblock(wsi->ssl, 1); #else wolfSSL_set_using_nonblock(wsi->ssl, 1); #endif #else BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */ #endif SSL_set_ex_data(wsi->ssl, openssl_websocket_private_data_index, context); } if (wsi->use_ssl) { lws_latency_pre(context, wsi); n = SSL_connect(wsi->ssl); lws_latency(context, wsi, "SSL_connect LWSCM_WSCL_ISSUE_HANDSHAKE", n, n > 0); if (n < 0) { n = SSL_get_error(wsi->ssl, n); if (n == SSL_ERROR_WANT_READ) goto some_wait; if (n == SSL_ERROR_WANT_WRITE) { /* * wants us to retry connect due to * state of the underlying ssl layer... * but since it may be stalled on * blocked write, no incoming data may * arrive to trigger the retry. * Force (possibly many times if the SSL * state persists in returning the * condition code, but other sockets * are getting serviced inbetweentimes) * us to get called back when writable. */ lwsl_info("%s: WANT_WRITE... retrying\n", __func__); lws_callback_on_writable(wsi); some_wait: wsi->mode = LWSCM_WSCL_WAITING_SSL; return 0; /* no error */ } n = -1; } if (n <= 0) { /* * retry if new data comes until we * run into the connection timeout or win */ n = ERR_get_error(); if (n != SSL_ERROR_NONE) { lwsl_err("SSL connect error %lu: %s\n", n, ERR_error_string(n, sb)); return 0; } } } else wsi->ssl = NULL; /* fallthru */ case LWSCM_WSCL_WAITING_SSL: if (wsi->use_ssl) { if (wsi->mode == LWSCM_WSCL_WAITING_SSL) { lws_latency_pre(context, wsi); n = SSL_connect(wsi->ssl); lws_latency(context, wsi, "SSL_connect LWSCM_WSCL_WAITING_SSL", n, n > 0); if (n < 0) { n = SSL_get_error(wsi->ssl, n); if (n == SSL_ERROR_WANT_READ) goto some_wait; if (n == SSL_ERROR_WANT_WRITE) { /* * wants us to retry connect due to * state of the underlying ssl layer... * but since it may be stalled on * blocked write, no incoming data may * arrive to trigger the retry. * Force (possibly many times if the SSL * state persists in returning the * condition code, but other sockets * are getting serviced inbetweentimes) * us to get called back when writable. */ lwsl_info("SSL_connect WANT_WRITE... retrying\n"); lws_callback_on_writable(wsi); goto some_wait; } n = -1; } if (n <= 0) { /* * retry if new data comes until we * run into the connection timeout or win */ n = ERR_get_error(); if (n != SSL_ERROR_NONE) { lwsl_err("SSL connect error %lu: %s\n", n, ERR_error_string(n, sb)); return 0; } } } #ifndef USE_WOLFSSL /* * See comment above about wolfSSL certificate * verification */ lws_latency_pre(context, wsi); n = SSL_get_verify_result(wsi->ssl); lws_latency(context, wsi, "SSL_get_verify_result LWS_CONNMODE..HANDSHAKE", n, n > 0); if (n != X509_V_OK) { if ((n == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT || n == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) && wsi->use_ssl == 2) { lwsl_notice("accepting self-signed certificate\n"); } else { lwsl_err("server's cert didn't look good, X509_V_ERR = %d: %s\n", n, ERR_error_string(n, sb)); lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); return 0; } } #endif /* USE_WOLFSSL */ } else wsi->ssl = NULL; #endif wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE2; lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND, AWAITING_TIMEOUT); /* fallthru */ case LWSCM_WSCL_ISSUE_HANDSHAKE2: p = lws_generate_client_handshake(wsi, p); if (p == NULL) { lwsl_err("Failed to generate handshake for client\n"); lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); return 0; } /* send our request to the server */ lws_latency_pre(context, wsi); n = lws_ssl_capable_write(wsi, (unsigned char *)sb, p - sb); lws_latency(context, wsi, "send lws_issue_raw", n, n == p - sb); switch (n) { case LWS_SSL_CAPABLE_ERROR: lwsl_debug("ERROR writing to client socket\n"); lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); return 0; case LWS_SSL_CAPABLE_MORE_SERVICE: lws_callback_on_writable(wsi); break; } wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART; wsi->u.hdr.lextable_pos = 0; wsi->mode = LWSCM_WSCL_WAITING_SERVER_REPLY; lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, AWAITING_TIMEOUT); break; case LWSCM_WSCL_WAITING_SERVER_REPLY: /* handle server hung up on us */ if (pollfd->revents & LWS_POLLHUP) { lwsl_debug("Server connection %p (fd=%d) dead\n", (void *)wsi, pollfd->fd); goto bail3; } if (!(pollfd->revents & LWS_POLLIN)) break; /* interpret the server response */ /* * HTTP/1.1 101 Switching Protocols * Upgrade: websocket * Connection: Upgrade * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo= * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC== * Sec-WebSocket-Protocol: chat */ /* * we have to take some care here to only take from the * socket bytewise. The browser may (and has been seen to * in the case that onopen() performs websocket traffic) * coalesce both handshake response and websocket traffic * in one packet, since at that point the connection is * definitively ready from browser pov. */ len = 1; while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE && len > 0) { n = lws_ssl_capable_read(wsi, &c, 1); lws_latency(context, wsi, "send lws_issue_raw", n, n == 1); switch (n) { case 0: case LWS_SSL_CAPABLE_ERROR: goto bail3; case LWS_SSL_CAPABLE_MORE_SERVICE: return 0; } if (lws_parse(wsi, c)) { lwsl_warn("problems parsing header\n"); goto bail3; } } /* * hs may also be coming in multiple packets, there is a 5-sec * libwebsocket timeout still active here too, so if parsing did * not complete just wait for next packet coming in this state */ if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE) break; /* * otherwise deal with the handshake. If there's any * packet traffic already arrived we'll trigger poll() again * right away and deal with it that way */ return lws_client_interpret_server_handshake(wsi); bail3: lwsl_info("closing conn at LWS_CONNMODE...SERVER_REPLY\n"); lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); return -1; case LWSCM_WSCL_WAITING_EXTENSION_CONNECT: lwsl_ext("LWSCM_WSCL_WAITING_EXTENSION_CONNECT\n"); break; case LWSCM_WSCL_PENDING_CANDIDATE_CHILD: lwsl_ext("LWSCM_WSCL_PENDING_CANDIDATE_CHILD\n"); break; default: break; } return 0; }
LWS_VISIBLE int lws_server_socket_service(struct lws_context *context, struct lws *wsi, struct lws_pollfd *pollfd) { lws_sockfd_type accept_fd = LWS_SOCK_INVALID; #if LWS_POSIX struct sockaddr_in cli_addr; socklen_t clilen; #endif struct lws *new_wsi = NULL; int n, len; switch (wsi->mode) { case LWSCM_HTTP_SERVING: case LWSCM_HTTP_SERVING_ACCEPTED: case LWSCM_HTTP2_SERVING: /* handle http headers coming in */ /* pending truncated sends have uber priority */ if (wsi->trunc_len) { if (!(pollfd->revents & LWS_POLLOUT)) break; if (lws_issue_raw(wsi, wsi->trunc_alloc + wsi->trunc_offset, wsi->trunc_len) < 0) goto fail; /* * we can't afford to allow input processing send * something new, so spin around he event loop until * he doesn't have any partials */ break; } /* any incoming data ready? */ if (!(pollfd->revents & pollfd->events && LWS_POLLIN)) goto try_pollout; len = lws_ssl_capable_read(wsi, context->serv_buf, sizeof(context->serv_buf)); lwsl_debug("%s: read %d\r\n", __func__, len); switch (len) { case 0: lwsl_info("lws_server_skt_srv: read 0 len\n"); /* lwsl_info(" state=%d\n", wsi->state); */ if (!wsi->hdr_parsing_completed) lws_free_header_table(wsi); /* fallthru */ case LWS_SSL_CAPABLE_ERROR: goto fail; case LWS_SSL_CAPABLE_MORE_SERVICE: goto try_pollout; } /* just ignore incoming if waiting for close */ if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) { /* * hm this may want to send * (via HTTP callback for example) */ n = lws_read(wsi, context->serv_buf, len); if (n < 0) /* we closed wsi */ return 1; /* hum he may have used up the * writability above */ break; } try_pollout: /* this handles POLLOUT for http serving fragments */ if (!(pollfd->revents & LWS_POLLOUT)) break; /* one shot */ if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) goto fail; lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_WRITE); if (wsi->state != LWSS_HTTP_ISSUING_FILE) { n = user_callback_handle_rxflow( wsi->protocol->callback, wsi, LWS_CALLBACK_HTTP_WRITEABLE, wsi->user_space, NULL, 0); if (n < 0) goto fail; break; } /* >0 == completion, <0 == error */ n = lws_serve_http_file_fragment(wsi); if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) goto fail; break; case LWSCM_SERVER_LISTENER: #if LWS_POSIX /* pollin means a client has connected to us then */ if (!(pollfd->revents & LWS_POLLIN)) break; /* listen socket got an unencrypted connection... */ clilen = sizeof(cli_addr); lws_latency_pre(context, wsi); accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr, &clilen); lws_latency(context, wsi, "unencrypted accept LWSCM_SERVER_LISTENER", accept_fd, accept_fd >= 0); if (accept_fd < 0) { if (LWS_ERRNO == LWS_EAGAIN || LWS_ERRNO == LWS_EWOULDBLOCK) { lwsl_debug("accept asks to try again\n"); break; } lwsl_warn("ERROR on accept: %s\n", strerror(LWS_ERRNO)); break; } lws_plat_set_socket_options(context, accept_fd); #else /* not very beautiful... */ accept_fd = (lws_sockfd_type)pollfd; #endif /* * look at who we connected to and give user code a chance * to reject based on client IP. There's no protocol selected * yet so we issue this to protocols[0] */ if ((context->protocols[0].callback)(wsi, LWS_CALLBACK_FILTER_NETWORK_CONNECTION, NULL, (void *)(long)accept_fd, 0)) { lwsl_debug("Callback denied network connection\n"); compatible_close(accept_fd); break; } new_wsi = lws_create_new_server_wsi(context); if (new_wsi == NULL) { compatible_close(accept_fd); break; } new_wsi->sock = accept_fd; /* the transport is accepted... give him time to negotiate */ lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER, AWAITING_TIMEOUT); #if LWS_POSIX == 0 mbed3_tcp_stream_accept(accept_fd, new_wsi); #endif /* * A new connection was accepted. Give the user a chance to * set properties of the newly created wsi. There's no protocol * selected yet so we issue this to protocols[0] */ (context->protocols[0].callback)(new_wsi, LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0); lws_libev_accept(new_wsi, accept_fd); if (!LWS_SSL_ENABLED(context)) { #if LWS_POSIX lwsl_debug("accepted new conn port %u on fd=%d\n", ntohs(cli_addr.sin_port), accept_fd); #endif if (insert_wsi_socket_into_fds(context, new_wsi)) goto fail; } break; default: break; } if (!lws_server_socket_service_ssl(&wsi, new_wsi, accept_fd, pollfd)) return 0; fail: lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); return 1; }
int lws_handle_POLLOUT_event(struct lws *wsi, struct lws_pollfd *pollfd) { int write_type = LWS_WRITE_PONG; struct lws_tokens eff_buf; #ifdef LWS_USE_HTTP2 struct lws *wsi2; #endif int ret, m, n; /* * user callback is lowest priority to get these notifications * actually, since other pending things cannot be disordered */ /* Priority 1: pending truncated sends are incomplete ws fragments * If anything else sent first the protocol would be * corrupted. */ if (wsi->trunc_len) { if (lws_issue_raw(wsi, wsi->trunc_alloc + wsi->trunc_offset, wsi->trunc_len) < 0) { lwsl_info("%s signalling to close\n", __func__); return -1; } /* leave POLLOUT active either way */ return 0; } else if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) return -1; /* retry closing now */ #ifdef LWS_USE_HTTP2 /* Priority 2: protocol packets */ if (wsi->pps) { lwsl_info("servicing pps %d\n", wsi->pps); switch (wsi->pps) { case LWS_PPS_HTTP2_MY_SETTINGS: case LWS_PPS_HTTP2_ACK_SETTINGS: lws_http2_do_pps_send(lws_get_context(wsi), wsi); break; default: break; } wsi->pps = LWS_PPS_NONE; lws_rx_flow_control(wsi, 1); return 0; /* leave POLLOUT active */ } #endif /* Priority 3: pending control packets (pong or close) */ if ((wsi->state == LWSS_ESTABLISHED && wsi->u.ws.ping_pending_flag) || (wsi->state == LWSS_RETURNED_CLOSE_ALREADY && wsi->u.ws.payload_is_close)) { if (wsi->u.ws.payload_is_close) write_type = LWS_WRITE_CLOSE; n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE], wsi->u.ws.ping_payload_len, write_type); if (n < 0) return -1; /* well he is sent, mark him done */ wsi->u.ws.ping_pending_flag = 0; if (wsi->u.ws.payload_is_close) /* oh... a close frame was it... then we are done */ return -1; /* otherwise for PING, leave POLLOUT active either way */ return 0; } /* Priority 4: if we are closing, not allowed to send more data frags * which means user callback or tx ext flush banned now */ if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY) goto user_service; /* Priority 5: Tx path extension with more to send * * These are handled as new fragments each time around * So while we must block new writeable callback to enforce * payload ordering, but since they are always complete * fragments control packets can interleave OK. */ if (wsi->state == LWSS_ESTABLISHED && wsi->u.ws.tx_draining_ext) { lwsl_ext("SERVICING TX EXT DRAINING\n"); if (lws_write(wsi, NULL, 0, LWS_WRITE_CONTINUATION) < 0) return -1; /* leave POLLOUT active */ return 0; } /* Priority 6: user can get the callback */ m = lws_ext_cb_active(wsi, LWS_EXT_CB_IS_WRITEABLE, NULL, 0); #ifndef LWS_NO_EXTENSIONS if (!wsi->extension_data_pending) goto user_service; #endif /* * check in on the active extensions, see if they * had pending stuff to spill... they need to get the * first look-in otherwise sequence will be disordered * * NULL, zero-length eff_buf means just spill pending */ ret = 1; while (ret == 1) { /* default to nobody has more to spill */ ret = 0; eff_buf.token = NULL; eff_buf.token_len = 0; /* give every extension a chance to spill */ m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_TX_PRESEND, &eff_buf, 0); if (m < 0) { lwsl_err("ext reports fatal error\n"); return -1; } if (m) /* * at least one extension told us he has more * to spill, so we will go around again after */ ret = 1; /* assuming they gave us something to send, send it */ if (eff_buf.token_len) { n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token, eff_buf.token_len); if (n < 0) { lwsl_info("closing from POLLOUT spill\n"); return -1; } /* * Keep amount spilled small to minimize chance of this */ if (n != eff_buf.token_len) { lwsl_err("Unable to spill ext %d vs %s\n", eff_buf.token_len, n); return -1; } } else continue; /* no extension has more to spill */ if (!ret) continue; /* * There's more to spill from an extension, but we just sent * something... did that leave the pipe choked? */ if (!lws_send_pipe_choked(wsi)) /* no we could add more */ continue; lwsl_info("choked in POLLOUT service\n"); /* * Yes, he's choked. Leave the POLLOUT masked on so we will * come back here when he is unchoked. Don't call the user * callback to enforce ordering of spilling, he'll get called * when we come back here and there's nothing more to spill. */ return 0; } #ifndef LWS_NO_EXTENSIONS wsi->extension_data_pending = 0; #endif user_service: /* one shot */ if (pollfd) { if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { lwsl_info("failed at set pollfd\n"); return 1; } lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_WRITE); } #ifdef LWS_USE_HTTP2 /* * we are the 'network wsi' for potentially many muxed child wsi with * no network connection of their own, who have to use us for all their * network actions. So we use a round-robin scheme to share out the * POLLOUT notifications to our children. * * But because any child could exhaust the socket's ability to take * writes, we can only let one child get notified each time. * * In addition children may be closed / deleted / added between POLLOUT * notifications, so we can't hold pointers */ if (wsi->mode != LWSCM_HTTP2_SERVING) { lwsl_info("%s: non http2\n", __func__); goto notify; } wsi->u.http2.requested_POLLOUT = 0; if (!wsi->u.http2.initialized) { lwsl_info("pollout on uninitialized http2 conn\n"); return 0; } lwsl_info("%s: doing children\n", __func__); wsi2 = wsi; do { wsi2 = wsi2->u.http2.next_child_wsi; lwsl_info("%s: child %p\n", __func__, wsi2); if (!wsi2) continue; if (!wsi2->u.http2.requested_POLLOUT) continue; wsi2->u.http2.requested_POLLOUT = 0; if (lws_calllback_as_writeable(wsi2)) { lwsl_debug("Closing POLLOUT child\n"); lws_close_free_wsi(wsi2, LWS_CLOSE_STATUS_NOSTATUS); } wsi2 = wsi; } while (wsi2 != NULL && !lws_send_pipe_choked(wsi)); lwsl_info("%s: completed\n", __func__); return 0; notify: #endif return lws_calllback_as_writeable(wsi); }
struct lws * lws_client_connect_2(struct lws *wsi) { #ifdef LWS_USE_IPV6 struct sockaddr_in6 server_addr6; struct sockaddr_in6 client_addr6; struct addrinfo hints, *result; #endif struct lws_context *context = wsi->context; struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; struct sockaddr_in server_addr4; struct sockaddr_in client_addr4; struct lws_pollfd pfd; struct sockaddr *v; int n, plen = 0; const char *ads; lwsl_client("%s\n", __func__); /* proxy? */ if (context->http_proxy_port) { plen = sprintf((char *)pt->serv_buf, "CONNECT %s:%u HTTP/1.0\x0d\x0a" "User-agent: libwebsockets\x0d\x0a", lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS), wsi->u.hdr.ah->c_port); if (context->proxy_basic_auth_token[0]) plen += sprintf((char *)pt->serv_buf + plen, "Proxy-authorization: basic %s\x0d\x0a", context->proxy_basic_auth_token); plen += sprintf((char *)pt->serv_buf + plen, "\x0d\x0a"); ads = context->http_proxy_address; #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) { memset(&server_addr6, 0, sizeof(struct sockaddr_in6)); server_addr6.sin6_port = htons(context->http_proxy_port); } else #endif server_addr4.sin_port = htons(context->http_proxy_port); } else { ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS); #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) { memset(&server_addr6, 0, sizeof(struct sockaddr_in6)); server_addr6.sin6_port = htons(wsi->u.hdr.ah->c_port); } else #endif server_addr4.sin_port = htons(wsi->u.hdr.ah->c_port); } /* * prepare the actual connection (to the proxy, if any) */ lwsl_client("%s: address %s\n", __func__, ads); #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) { memset(&hints, 0, sizeof(struct addrinfo)); #if !defined(__ANDROID__) hints.ai_family = AF_INET6; hints.ai_flags = AI_V4MAPPED; #endif n = getaddrinfo(ads, NULL, &hints, &result); if (n) { #ifdef _WIN32 lwsl_err("getaddrinfo: %ls\n", gai_strerrorW(n)); #else lwsl_err("getaddrinfo: %s\n", gai_strerror(n)); #endif goto oom4; } server_addr6.sin6_family = AF_INET6; switch (result->ai_family) { #if defined(__ANDROID__) case AF_INET: /* map IPv4 to IPv6 */ bzero((char *)&server_addr6.sin6_addr, sizeof(struct in6_addr)); server_addr6.sin6_addr.s6_addr[10] = 0xff; server_addr6.sin6_addr.s6_addr[11] = 0xff; memcpy(&server_addr6.sin6_addr.s6_addr[12], &((struct sockaddr_in *)result->ai_addr)->sin_addr, sizeof(struct in_addr)); break; #endif case AF_INET6: memcpy(&server_addr6.sin6_addr, &((struct sockaddr_in6 *)result->ai_addr)->sin6_addr, sizeof(struct in6_addr)); break; default: lwsl_err("Unknown address family\n"); freeaddrinfo(result); goto oom4; } freeaddrinfo(result); } else #endif { struct addrinfo ai, *res, *result; void *p = NULL; memset (&ai, 0, sizeof ai); ai.ai_family = PF_UNSPEC; ai.ai_socktype = SOCK_STREAM; ai.ai_flags = AI_CANONNAME; if (getaddrinfo(ads, NULL, &ai, &result)) goto oom4; res = result; while (!p && res) { switch (res->ai_family) { case AF_INET: p = &((struct sockaddr_in *)res->ai_addr)->sin_addr; break; } res = res->ai_next; } if (!p) { freeaddrinfo(result); goto oom4; } server_addr4.sin_family = AF_INET; server_addr4.sin_addr = *((struct in_addr *)p); bzero(&server_addr4.sin_zero, 8); freeaddrinfo(result); } if (!lws_socket_is_valid(wsi->sock)) { #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) wsi->sock = socket(AF_INET6, SOCK_STREAM, 0); else #endif wsi->sock = socket(AF_INET, SOCK_STREAM, 0); if (!lws_socket_is_valid(wsi->sock)) { lwsl_warn("Unable to open socket\n"); goto oom4; } if (lws_plat_set_socket_options(context, wsi->sock)) { lwsl_err("Failed to set wsi socket options\n"); compatible_close(wsi->sock); goto oom4; } wsi->mode = LWSCM_WSCL_WAITING_CONNECT; lws_libev_accept(wsi, wsi->sock); if (insert_wsi_socket_into_fds(context, wsi)) { compatible_close(wsi->sock); goto oom4; } /* * past here, we can't simply free the structs as error * handling as oom4 does. We have to run the whole close flow. */ lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE, AWAITING_TIMEOUT); #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) { v = (struct sockaddr *)&client_addr6; n = sizeof(client_addr6); bzero((char *)v, n); client_addr6.sin6_family = AF_INET6; } else #endif { v = (struct sockaddr *)&client_addr4; n = sizeof(client_addr4); bzero((char *)v, n); client_addr4.sin_family = AF_INET; } if (context->iface) { if (interface_to_sa(context, context->iface, (struct sockaddr_in *)v, n) < 0) { lwsl_err("Unable to find interface %s\n", context->iface); goto failed; } if (bind(wsi->sock, v, n) < 0) { lwsl_err("Error binding to interface %s", context->iface); goto failed; } } } #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) { v = (struct sockaddr *)&server_addr6; n = sizeof(struct sockaddr_in6); } else #endif { v = (struct sockaddr *)&server_addr4; n = sizeof(struct sockaddr); } if (connect(wsi->sock, v, n) == -1 || LWS_ERRNO == LWS_EISCONN) { if (LWS_ERRNO == LWS_EALREADY || LWS_ERRNO == LWS_EINPROGRESS || LWS_ERRNO == LWS_EWOULDBLOCK #ifdef _WIN32 || LWS_ERRNO == WSAEINVAL #endif ) { lwsl_client("nonblocking connect retry\n"); /* * must do specifically a POLLOUT poll to hear * about the connect completion */ if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) goto failed; lws_libev_io(wsi, LWS_EV_START | LWS_EV_WRITE); return wsi; } if (LWS_ERRNO != LWS_EISCONN) { lwsl_debug("Connect failed errno=%d\n", LWS_ERRNO); goto failed; } } lwsl_client("connected\n"); /* we are connected to server, or proxy */ if (context->http_proxy_port) { /* * OK from now on we talk via the proxy, so connect to that * * (will overwrite existing pointer, * leaving old string/frag there but unreferenced) */ if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS, context->http_proxy_address)) goto failed; wsi->u.hdr.ah->c_port = context->http_proxy_port; n = send(wsi->sock, (char *)pt->serv_buf, plen, MSG_NOSIGNAL); if (n < 0) { lwsl_debug("ERROR writing to proxy socket\n"); goto failed; } lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE, AWAITING_TIMEOUT); wsi->mode = LWSCM_WSCL_WAITING_PROXY_REPLY; return wsi; } /* * provoke service to issue the handshake directly * we need to do it this way because in the proxy case, this is the * next state and executed only if and when we get a good proxy * response inside the state machine... but notice in SSL case this * may not have sent anything yet with 0 return, and won't until some * many retries from main loop. To stop that becoming endless, * cover with a timeout. */ lws_set_timeout(wsi, PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE, AWAITING_TIMEOUT); wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE; pfd.fd = wsi->sock; pfd.revents = LWS_POLLIN; n = lws_service_fd(context, &pfd); if (n < 0) goto failed; if (n) /* returns 1 on failure after closing wsi */ return NULL; return wsi; oom4: lws_free_header_table(wsi); lws_free(wsi); return NULL; failed: lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); return NULL; }
LWS_VISIBLE int libwebsocket_callback_on_writable(struct libwebsocket_context *context, struct libwebsocket *wsi) { #ifdef LWS_USE_HTTP2 struct libwebsocket *network_wsi, *wsi2; int already; lwsl_info("%s: %p\n", __func__, wsi); if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING) goto network_sock; if (wsi->u.http2.requested_POLLOUT) { lwsl_info("already pending writable\n"); return 1; } if (wsi->u.http2.tx_credit <= 0) { /* * other side is not able to cope with us sending * anything so no matter if we have POLLOUT on our side. * * Delay waiting for our POLLOUT until peer indicates he has * space for more using tx window command in http2 layer */ lwsl_info("%s: %p: waiting_tx_credit (%d)\n", __func__, wsi, wsi->u.http2.tx_credit); wsi->u.http2.waiting_tx_credit = 1; return 0; } network_wsi = lws_http2_get_network_wsi(wsi); already = network_wsi->u.http2.requested_POLLOUT; /* mark everybody above him as requesting pollout */ wsi2 = wsi; while (wsi2) { wsi2->u.http2.requested_POLLOUT = 1; lwsl_info("mark %p pending writable\n", wsi2); wsi2 = wsi2->u.http2.parent_wsi; } /* for network action, act only on the network wsi */ wsi = network_wsi; if (already) return 1; network_sock: #endif (void)context; if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE, NULL, 0)) return 1; if (wsi->position_in_fds_table < 0) { lwsl_err("%s: failed to find socket %d\n", __func__, wsi->sock); return -1; } if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) return -1; lws_libev_io(context, wsi, LWS_EV_START | LWS_EV_WRITE); return 1; }
int lws_context_init_server(struct lws_context_creation_info *info, struct lws_context *context) { #ifdef LWS_USE_IPV6 struct sockaddr_in6 serv_addr6; #endif #if LWS_POSIX struct sockaddr_in serv_addr4; socklen_t len = sizeof(struct sockaddr); struct sockaddr_in sin; struct sockaddr *v; int n, opt = 1; #endif lws_sockfd_type sockfd; struct lws *wsi; /* set up our external listening socket we serve on */ if (info->port == CONTEXT_PORT_NO_LISTEN) return 0; #if LWS_POSIX #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) sockfd = socket(AF_INET6, SOCK_STREAM, 0); else #endif sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { #else sockfd = mbed3_create_tcp_stream_socket(); if (!lws_sockfd_valid(sockfd)) { #endif lwsl_err("ERROR opening socket\n"); return 1; } #if LWS_POSIX /* * allow us to restart even if old sockets in TIME_WAIT */ if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(opt)) < 0) { compatible_close(sockfd); return 1; } #endif lws_plat_set_socket_options(context, sockfd); #if LWS_POSIX #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) { v = (struct sockaddr *)&serv_addr6; n = sizeof(struct sockaddr_in6); bzero((char *) &serv_addr6, sizeof(serv_addr6)); serv_addr6.sin6_addr = in6addr_any; serv_addr6.sin6_family = AF_INET6; serv_addr6.sin6_port = htons(info->port); } else #endif { v = (struct sockaddr *)&serv_addr4; n = sizeof(serv_addr4); bzero((char *) &serv_addr4, sizeof(serv_addr4)); serv_addr4.sin_addr.s_addr = INADDR_ANY; serv_addr4.sin_family = AF_INET; if (info->iface) { if (interface_to_sa(context, info->iface, (struct sockaddr_in *)v, n) < 0) { lwsl_err("Unable to find interface %s\n", info->iface); compatible_close(sockfd); return 1; } } serv_addr4.sin_port = htons(info->port); } /* ipv4 */ n = bind(sockfd, v, n); if (n < 0) { lwsl_err("ERROR on binding to port %d (%d %d)\n", info->port, n, LWS_ERRNO); compatible_close(sockfd); return 1; } if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1) lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO)); else info->port = ntohs(sin.sin_port); #endif context->listen_port = info->port; wsi = lws_zalloc(sizeof(struct lws)); if (wsi == NULL) { lwsl_err("Out of mem\n"); compatible_close(sockfd); return 1; } wsi->sock = sockfd; wsi->mode = LWS_CONNMODE_SERVER_LISTENER; wsi->protocol = context->protocols; if (insert_wsi_socket_into_fds(context, wsi)) { compatible_close(sockfd); return 1; } context->listen_service_modulo = LWS_LISTEN_SERVICE_MODULO; context->listen_service_count = 0; context->listen_service_fd = sockfd; #if LWS_POSIX listen(sockfd, LWS_SOMAXCONN); #else mbed3_tcp_stream_bind(sockfd, info->port, wsi); #endif lwsl_notice(" Listening on port %d\n", info->port); return 0; } int _lws_rx_flow_control(struct lws *wsi) { struct lws_context *context = wsi->protocol->owning_server; /* there is no pending change */ if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) return 0; /* stuff is still buffered, not ready to really accept new input */ if (wsi->rxflow_buffer) { /* get ourselves called back to deal with stashed buffer */ lws_callback_on_writable(context, wsi); return 0; } /* pending is cleared, we can change rxflow state */ wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE; lwsl_info("rxflow: wsi %p change_to %d\n", wsi, wsi->rxflow_change_to & LWS_RXFLOW_ALLOW); /* adjust the pollfd for this wsi */ if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) { if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) { lwsl_info("%s: fail\n", __func__); return -1; } } else if (lws_change_pollfd(wsi, LWS_POLLIN, 0)) return -1; return 0; } int lws_http_action(struct lws_context *context, struct lws *wsi) { enum http_connection_type connection_type = HTTP_CONNECTION_KEEP_ALIVE; enum http_version request_version; char content_length_str[32]; unsigned int n, count = 0; char http_version_str[10]; char http_conn_str[20]; int http_version_len; char *uri_ptr = NULL; int uri_len = 0; static const unsigned char methods[] = { WSI_TOKEN_GET_URI, WSI_TOKEN_POST_URI, WSI_TOKEN_OPTIONS_URI, WSI_TOKEN_PUT_URI, WSI_TOKEN_PATCH_URI, WSI_TOKEN_DELETE_URI, #ifdef LWS_USE_HTTP2 WSI_TOKEN_HTTP_COLON_PATH, #endif }; #ifdef _DEBUG static const char * const method_names[] = { "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE", #ifdef LWS_USE_HTTP2 ":path", #endif }; #endif /* it's not websocket.... shall we accept it as http? */ for (n = 0; n < ARRAY_SIZE(methods); n++) if (lws_hdr_total_length(wsi, methods[n])) count++; if (!count) { lwsl_warn("Missing URI in HTTP request\n"); goto bail_nuke_ah; } if (count != 1) { lwsl_warn("multiple methods?\n"); goto bail_nuke_ah; } if (lws_ensure_user_space(wsi)) goto bail_nuke_ah; for (n = 0; n < ARRAY_SIZE(methods); n++) if (lws_hdr_total_length(wsi, methods[n])) { uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]); uri_len = lws_hdr_total_length(wsi, methods[n]); lwsl_info("Method: %s request for '%s'\n", method_names[n], uri_ptr); break; } /* HTTP header had a content length? */ wsi->u.http.content_length = 0; if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) || lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) || lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI)) wsi->u.http.content_length = 100 * 1024 * 1024; if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) { lws_hdr_copy(wsi, content_length_str, sizeof(content_length_str) - 1, WSI_TOKEN_HTTP_CONTENT_LENGTH); wsi->u.http.content_length = atoi(content_length_str); } /* http_version? Default to 1.0, override with token: */ request_version = HTTP_VERSION_1_0; /* Works for single digit HTTP versions. : */ http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP); if (http_version_len > 7) { lws_hdr_copy(wsi, http_version_str, sizeof(http_version_str) - 1, WSI_TOKEN_HTTP); if (http_version_str[5] == '1' && http_version_str[7] == '1') request_version = HTTP_VERSION_1_1; } wsi->u.http.request_version = request_version; /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */ if (request_version == HTTP_VERSION_1_1) connection_type = HTTP_CONNECTION_KEEP_ALIVE; else connection_type = HTTP_CONNECTION_CLOSE; /* Override default if http "Connection:" header: */ if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) { lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1, WSI_TOKEN_CONNECTION); http_conn_str[sizeof(http_conn_str) - 1] = '\0'; if (!strcasecmp(http_conn_str, "keep-alive")) connection_type = HTTP_CONNECTION_KEEP_ALIVE; else if (!strcasecmp(http_conn_str, "close")) connection_type = HTTP_CONNECTION_CLOSE; } wsi->u.http.connection_type = connection_type; n = wsi->protocol->callback(context, wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION, wsi->user_space, uri_ptr, uri_len); if (!n) { /* * if there is content supposed to be coming, * put a timeout on it having arrived */ lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, AWAITING_TIMEOUT); n = wsi->protocol->callback(context, wsi, LWS_CALLBACK_HTTP, wsi->user_space, uri_ptr, uri_len); } /* now drop the header info we kept a pointer to */ lws_free2(wsi->u.http.ah); if (n) { lwsl_info("LWS_CALLBACK_HTTP closing\n"); return 1; /* struct ah ptr already nuked */ } /* * If we're not issuing a file, check for content_length or * HTTP keep-alive. No keep-alive header allocation for * ISSUING_FILE, as this uses HTTP/1.0. * * In any case, return 0 and let lws_read decide how to * proceed based on state */ if (wsi->state != WSI_STATE_HTTP_ISSUING_FILE) /* Prepare to read body if we have a content length: */ if (wsi->u.http.content_length > 0) wsi->state = WSI_STATE_HTTP_BODY; return 0; bail_nuke_ah: /* drop the header info */ lws_free2(wsi->u.hdr.ah); return 1; } int lws_handshake_server(struct lws_context *context, struct lws *wsi, unsigned char **buf, size_t len) { struct allocated_headers *ah; int protocol_len, n, hit; char protocol_list[128]; char protocol_name[32]; char *p; /* LWS_CONNMODE_WS_SERVING */ while (len--) { if (lws_parse(context, wsi, *(*buf)++)) { lwsl_info("lws_parse failed\n"); goto bail_nuke_ah; } if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE) continue; lwsl_parser("lws_parse sees parsing complete\n"); wsi->mode = LWS_CONNMODE_PRE_WS_SERVING_ACCEPT; lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); /* is this websocket protocol or normal http 1.0? */ if (!lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE) || !lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) { ah = wsi->u.hdr.ah; lws_union_transition(wsi, LWS_CONNMODE_HTTP_SERVING_ACCEPTED); wsi->state = WSI_STATE_HTTP; wsi->u.http.fd = LWS_INVALID_FILE; /* expose it at the same offset as u.hdr */ wsi->u.http.ah = ah; n = lws_http_action(context, wsi); return n; } if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE), "websocket")) goto upgrade_ws; #ifdef LWS_USE_HTTP2 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE), "h2c-14")) goto upgrade_h2c; #endif /* dunno what he wanted to upgrade to */ goto bail_nuke_ah; #ifdef LWS_USE_HTTP2 upgrade_h2c: if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) { lwsl_err("missing http2_settings\n"); goto bail_nuke_ah; } lwsl_err("h2c upgrade...\n"); p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS); /* convert the peer's HTTP-Settings */ n = lws_b64_decode_string(p, protocol_list, sizeof(protocol_list)); if (n < 0) { lwsl_parser("HTTP2_SETTINGS too long\n"); return 1; } /* adopt the header info */ ah = wsi->u.hdr.ah; lws_union_transition(wsi, LWS_CONNMODE_HTTP2_SERVING); /* http2 union member has http union struct at start */ wsi->u.http.ah = ah; lws_http2_init(&wsi->u.http2.peer_settings); lws_http2_init(&wsi->u.http2.my_settings); /* HTTP2 union */ lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings, (unsigned char *)protocol_list, n); strcpy(protocol_list, "HTTP/1.1 101 Switching Protocols\x0d\x0a" "Connection: Upgrade\x0d\x0a" "Upgrade: h2c\x0d\x0a\x0d\x0a"); n = lws_issue_raw(wsi, (unsigned char *)protocol_list, strlen(protocol_list)); if (n != strlen(protocol_list)) { lwsl_debug("http2 switch: ERROR writing to socket\n"); return 1; } wsi->state = WSI_STATE_HTTP2_AWAIT_CLIENT_PREFACE; return 0; #endif upgrade_ws: if (!wsi->protocol) lwsl_err("NULL protocol at lws_read\n"); /* * It's websocket * * Select the first protocol we support from the list * the client sent us. * * Copy it to remove header fragmentation */ if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1, WSI_TOKEN_PROTOCOL) < 0) { lwsl_err("protocol list too long"); goto bail_nuke_ah; } protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL); protocol_list[protocol_len] = '\0'; p = protocol_list; hit = 0; while (*p && !hit) { unsigned int n = 0; while (n < sizeof(protocol_name) - 1 && *p && *p !=',') protocol_name[n++] = *p++; protocol_name[n] = '\0'; if (*p) p++; lwsl_info("checking %s\n", protocol_name); n = 0; while (wsi->protocol && context->protocols[n].callback) { if (!wsi->protocol->name) { n++; continue; } if (!strcmp(context->protocols[n].name, protocol_name)) { lwsl_info("prot match %d\n", n); wsi->protocol = &context->protocols[n]; hit = 1; break; } n++; } } /* we didn't find a protocol he wanted? */ if (!hit) { if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL) == NULL) { /* * some clients only have one protocol and * do not sent the protocol list header... * allow it and match to protocol 0 */ lwsl_info("defaulting to prot 0 handler\n"); wsi->protocol = &context->protocols[0]; } else { lwsl_err("No protocol from list \"%s\" supported\n", protocol_list); goto bail_nuke_ah; } } /* allocate wsi->user storage */ if (lws_ensure_user_space(wsi)) goto bail_nuke_ah; /* * Give the user code a chance to study the request and * have the opportunity to deny it */ if ((wsi->protocol->callback)(wsi->protocol->owning_server, wsi, LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION, wsi->user_space, lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) { lwsl_warn("User code denied connection\n"); goto bail_nuke_ah; } /* * Perform the handshake according to the protocol version the * client announced */ switch (wsi->ietf_spec_revision) { case 13: lwsl_parser("lws_parse calling handshake_04\n"); if (handshake_0405(context, wsi)) { lwsl_info("hs0405 has failed the connection\n"); goto bail_nuke_ah; } break; default: lwsl_warn("Unknown client spec version %d\n", wsi->ietf_spec_revision); goto bail_nuke_ah; } /* drop the header info -- no bail_nuke_ah after this */ lws_free_header_table(wsi); lws_union_transition(wsi, LWS_CONNMODE_WS_SERVING); /* * create the frame buffer for this connection according to the * size mentioned in the protocol definition. If 0 there, use * a big default for compatibility */ n = wsi->protocol->rx_buffer_size; if (!n) n = LWS_MAX_SOCKET_IO_BUF; n += LWS_SEND_BUFFER_PRE_PADDING + LWS_SEND_BUFFER_POST_PADDING; wsi->u.ws.rx_user_buffer = lws_malloc(n); if (!wsi->u.ws.rx_user_buffer) { lwsl_err("Out of Mem allocating rx buffer %d\n", n); return 1; } lwsl_info("Allocating RX buffer %d\n", n); #if LWS_POSIX if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF, (const char *)&n, sizeof n)) { lwsl_warn("Failed to set SNDBUF to %d", n); return 1; } #endif lwsl_parser("accepted v%02d connection\n", wsi->ietf_spec_revision); } /* while all chars are handled */ return 0; bail_nuke_ah: /* drop the header info */ lws_free_header_table(wsi); return 1; } struct lws * lws_create_new_server_wsi(struct lws_context *context) { struct lws *new_wsi; new_wsi = lws_zalloc(sizeof(struct lws)); if (new_wsi == NULL) { lwsl_err("Out of memory for new connection\n"); return NULL; } new_wsi->pending_timeout = NO_PENDING_TIMEOUT; new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW; /* intialize the instance struct */ new_wsi->state = WSI_STATE_HTTP; new_wsi->mode = LWS_CONNMODE_HTTP_SERVING; new_wsi->hdr_parsing_completed = 0; #ifdef LWS_OPENSSL_SUPPORT new_wsi->use_ssl = LWS_SSL_ENABLED(context); #endif if (lws_allocate_header_table(new_wsi)) { lws_free(new_wsi); return NULL; } /* * these can only be set once the protocol is known * we set an unestablished connection's protocol pointer * to the start of the supported list, so it can look * for matching ones during the handshake */ new_wsi->protocol = context->protocols; new_wsi->user_space = NULL; new_wsi->ietf_spec_revision = 0; new_wsi->sock = LWS_SOCK_INVALID; /* * outermost create notification for wsi * no user_space because no protocol selection */ context->protocols[0].callback(context, new_wsi, LWS_CALLBACK_WSI_CREATE, NULL, NULL, 0); return new_wsi; } /** * lws_http_transaction_completed() - wait for new http transaction or close * @wsi: websocket connection * * Returns 1 if the HTTP connection must close now * Returns 0 and resets connection to wait for new HTTP header / * transaction if possible */ LWS_VISIBLE int lws_http_transaction_completed(struct lws *wsi) { /* if we can't go back to accept new headers, drop the connection */ if (wsi->u.http.connection_type == HTTP_CONNECTION_CLOSE) { lwsl_info("%s: close connection\n", __func__); return 1; } /* otherwise set ourselves up ready to go again */ wsi->state = WSI_STATE_HTTP; wsi->mode = LWS_CONNMODE_HTTP_SERVING; wsi->u.http.content_length = 0; /* He asked for it to stay alive indefinitely */ lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); if (lws_allocate_header_table(wsi)) return 1; /* If we're (re)starting on headers, need other implied init */ wsi->u.hdr.ues = URIES_IDLE; lwsl_info("%s: keep-alive await new transaction\n", __func__); return 0; } LWS_VISIBLE int lws_server_socket_service(struct lws_context *context, struct lws *wsi, struct lws_pollfd *pollfd) { lws_sockfd_type accept_fd = LWS_SOCK_INVALID; #if LWS_POSIX struct sockaddr_in cli_addr; socklen_t clilen; #endif struct lws *new_wsi = NULL; int n, len; switch (wsi->mode) { case LWS_CONNMODE_HTTP_SERVING: case LWS_CONNMODE_HTTP_SERVING_ACCEPTED: case LWS_CONNMODE_HTTP2_SERVING: /* handle http headers coming in */ /* pending truncated sends have uber priority */ if (wsi->truncated_send_len) { if (pollfd->revents & LWS_POLLOUT) if (lws_issue_raw(wsi, wsi->truncated_send_malloc + wsi->truncated_send_offset, wsi->truncated_send_len) < 0) { goto fail; } /* * we can't afford to allow input processing send * something new, so spin around he event loop until * he doesn't have any partials */ break; } /* any incoming data ready? */ if (pollfd->revents & LWS_POLLIN) { len = lws_ssl_capable_read(context, wsi, context->service_buffer, sizeof(context->service_buffer)); lwsl_debug("%s: read %d\r\n", __func__, len); switch (len) { case 0: lwsl_info("lws_server_skt_srv: read 0 len\n"); /* lwsl_info(" state=%d\n", wsi->state); */ if (!wsi->hdr_parsing_completed) lws_free_header_table(wsi); /* fallthru */ case LWS_SSL_CAPABLE_ERROR: goto fail; case LWS_SSL_CAPABLE_MORE_SERVICE: goto try_pollout; } /* just ignore incoming if waiting for close */ if (wsi->state != WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) { /* * hm this may want to send * (via HTTP callback for example) */ n = lws_read(context, wsi, context->service_buffer, len); if (n < 0) /* we closed wsi */ return 1; /* hum he may have used up the * writability above */ break; } } try_pollout: /* this handles POLLOUT for http serving fragments */ if (!(pollfd->revents & LWS_POLLOUT)) break; /* one shot */ if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) goto fail; lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE); if (wsi->state != WSI_STATE_HTTP_ISSUING_FILE) { n = user_callback_handle_rxflow( wsi->protocol->callback, wsi->protocol->owning_server, wsi, LWS_CALLBACK_HTTP_WRITEABLE, wsi->user_space, NULL, 0); if (n < 0) goto fail; break; } /* >0 == completion, <0 == error */ n = lws_serve_http_file_fragment(context, wsi); if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) goto fail; break; case LWS_CONNMODE_SERVER_LISTENER: #if LWS_POSIX /* pollin means a client has connected to us then */ if (!(pollfd->revents & LWS_POLLIN)) break; /* listen socket got an unencrypted connection... */ clilen = sizeof(cli_addr); lws_latency_pre(context, wsi); accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr, &clilen); lws_latency(context, wsi, "unencrypted accept LWS_CONNMODE_SERVER_LISTENER", accept_fd, accept_fd >= 0); if (accept_fd < 0) { if (LWS_ERRNO == LWS_EAGAIN || LWS_ERRNO == LWS_EWOULDBLOCK) { lwsl_debug("accept asks to try again\n"); break; } lwsl_warn("ERROR on accept: %s\n", strerror(LWS_ERRNO)); break; } lws_plat_set_socket_options(context, accept_fd); #else /* not very beautiful... */ accept_fd = (lws_sockfd_type)pollfd; #endif /* * look at who we connected to and give user code a chance * to reject based on client IP. There's no protocol selected * yet so we issue this to protocols[0] */ if ((context->protocols[0].callback)(context, wsi, LWS_CALLBACK_FILTER_NETWORK_CONNECTION, NULL, (void *)(long)accept_fd, 0)) { lwsl_debug("Callback denied network connection\n"); compatible_close(accept_fd); break; } new_wsi = lws_create_new_server_wsi(context); if (new_wsi == NULL) { compatible_close(accept_fd); break; } new_wsi->sock = accept_fd; /* the transport is accepted... give him time to negotiate */ lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER, AWAITING_TIMEOUT); #if LWS_POSIX == 0 mbed3_tcp_stream_accept(accept_fd, new_wsi); #endif /* * A new connection was accepted. Give the user a chance to * set properties of the newly created wsi. There's no protocol * selected yet so we issue this to protocols[0] */ (context->protocols[0].callback)(context, new_wsi, LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0); lws_libev_accept(context, new_wsi, accept_fd); if (!LWS_SSL_ENABLED(context)) { #if LWS_POSIX lwsl_debug("accepted new conn port %u on fd=%d\n", ntohs(cli_addr.sin_port), accept_fd); #endif if (insert_wsi_socket_into_fds(context, new_wsi)) goto fail; } break; default: break; } if (!lws_server_socket_service_ssl(context, &wsi, new_wsi, accept_fd, pollfd)) return 0; fail: lws_close_and_free_session(context, wsi, LWS_CLOSE_STATUS_NOSTATUS); return 1; }
int remove_wsi_socket_from_fds(struct lws *wsi) { struct lws_pollargs pa = { wsi->sock, 0, 0 }; #ifndef LWS_NO_SERVER struct lws_pollargs pa1; #endif struct lws_context *context = wsi->context; struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; struct lws *end_wsi; int m, ret = 0; #if !defined(_WIN32) && !defined(MBED_OPERATORS) if (wsi->sock > context->max_fds) { lwsl_err("fd %d too high (%d)\n", wsi->sock, context->max_fds); return 1; } #endif if (context->protocols[0].callback(wsi, LWS_CALLBACK_LOCK_POLL, wsi->user_space, (void *)&pa, 1)) return -1; lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE); lws_pt_lock(pt); lwsl_info("%s: wsi=%p, sock=%d, fds pos=%d, end guy pos=%d, endfd=%d\n", __func__, wsi, wsi->sock, wsi->position_in_fds_table, pt->fds_count, pt->fds[pt->fds_count].fd); /* the guy who is to be deleted's slot index in pt->fds */ m = wsi->position_in_fds_table; /* have the last guy take up the now vacant slot */ pt->fds[m] = pt->fds[pt->fds_count - 1]; lws_plat_delete_socket_from_fds(context, wsi, m); /* end guy's "position in fds table" is now the deletion guy's old one */ end_wsi = wsi_from_fd(context, pt->fds[pt->fds_count].fd); assert(end_wsi); end_wsi->position_in_fds_table = m; /* deletion guy's lws_lookup entry needs nuking */ delete_from_fd(context, wsi->sock); /* removed wsi has no position any more */ wsi->position_in_fds_table = -1; /* remove also from external POLL support via protocol 0 */ if (lws_socket_is_valid(wsi->sock)) if (context->protocols[0].callback(wsi, LWS_CALLBACK_DEL_POLL_FD, wsi->user_space, (void *) &pa, 0)) ret = -1; #ifndef LWS_NO_SERVER /* if this made some room, accept connects on this thread */ if ((unsigned int)pt->fds_count < context->fd_limit_per_thread - 1) _lws_change_pollfd(pt->wsi_listening, 0, LWS_POLLIN, &pa1); #endif lws_pt_unlock(pt); if (context->protocols[0].callback(wsi, LWS_CALLBACK_UNLOCK_POLL, wsi->user_space, (void *) &pa, 1)) ret = -1; return ret; }
int lws_handle_POLLOUT_event(struct libwebsocket_context *context, struct libwebsocket *wsi, struct libwebsocket_pollfd *pollfd) { int n; struct lws_tokens eff_buf; #ifdef LWS_USE_HTTP2 struct libwebsocket *wsi2; #endif int ret; int m; int handled = 0; /* pending truncated sends have uber priority */ if (wsi->truncated_send_len) { if (lws_issue_raw(wsi, wsi->truncated_send_malloc + wsi->truncated_send_offset, wsi->truncated_send_len) < 0) { lwsl_info("lws_handle_POLLOUT_event signalling to close\n"); return -1; } /* leave POLLOUT active either way */ return 0; } else if (wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) { lwsl_info("***** %x signalling to close in POLLOUT handler\n", wsi); return -1; /* retry closing now */ } #ifdef LWS_USE_HTTP2 /* protocol packets are next */ if (wsi->pps) { lwsl_info("servicing pps %d\n", wsi->pps); switch (wsi->pps) { case LWS_PPS_HTTP2_MY_SETTINGS: case LWS_PPS_HTTP2_ACK_SETTINGS: lws_http2_do_pps_send(context, wsi); break; default: break; } wsi->pps = LWS_PPS_NONE; libwebsocket_rx_flow_control(wsi, 1); return 0; /* leave POLLOUT active */ } #endif /* pending control packets have next priority */ if (wsi->state == WSI_STATE_ESTABLISHED && wsi->u.ws.ping_payload_len) { n = libwebsocket_write(wsi, &wsi->u.ws.ping_payload_buf[ LWS_SEND_BUFFER_PRE_PADDING], wsi->u.ws.ping_payload_len, LWS_WRITE_PONG); if (n < 0) return -1; /* well he is sent, mark him done */ wsi->u.ws.ping_payload_len = 0; /* leave POLLOUT active either way */ return 0; } /* if nothing critical, user can get the callback */ m = lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_IS_WRITEABLE, NULL, 0); #ifndef LWS_NO_EXTENSIONS if (!wsi->extension_data_pending || handled == 2) goto user_service; #endif /* * check in on the active extensions, see if they * had pending stuff to spill... they need to get the * first look-in otherwise sequence will be disordered * * NULL, zero-length eff_buf means just spill pending */ ret = 1; while (ret == 1) { /* default to nobody has more to spill */ ret = 0; eff_buf.token = NULL; eff_buf.token_len = 0; /* give every extension a chance to spill */ m = lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_PACKET_TX_PRESEND, &eff_buf, 0); if (m < 0) { lwsl_err("ext reports fatal error\n"); return -1; } if (m) /* * at least one extension told us he has more * to spill, so we will go around again after */ ret = 1; /* assuming they gave us something to send, send it */ if (eff_buf.token_len) { n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token, eff_buf.token_len); if (n < 0) { lwsl_info("closing from POLLOUT spill\n"); return -1; } /* * Keep amount spilled small to minimize chance of this */ if (n != eff_buf.token_len) { lwsl_err("Unable to spill ext %d vs %s\n", eff_buf.token_len, n); return -1; } } else continue; /* no extension has more to spill */ if (!ret) continue; /* * There's more to spill from an extension, but we just sent * something... did that leave the pipe choked? */ if (!lws_send_pipe_choked(wsi)) /* no we could add more */ continue; lwsl_info("choked in POLLOUT service\n"); /* * Yes, he's choked. Leave the POLLOUT masked on so we will * come back here when he is unchoked. Don't call the user * callback to enforce ordering of spilling, he'll get called * when we come back here and there's nothing more to spill. */ return 0; } #ifndef LWS_NO_EXTENSIONS wsi->extension_data_pending = 0; user_service: #endif /* one shot */ if (pollfd) { if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { lwsl_info("failled at set pollfd\n"); return 1; } lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE); } #ifdef LWS_USE_HTTP2 /* * we are the 'network wsi' for potentially many muxed child wsi with * no network connection of their own, who have to use us for all their * network actions. So we use a round-robin scheme to share out the * POLLOUT notifications to our children. * * But because any child could exhaust the socket's ability to take * writes, we can only let one child get notified each time. * * In addition children may be closed / deleted / added between POLLOUT * notifications, so we can't hold pointers */ if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING) { lwsl_info("%s: non http2\n", __func__); goto notify; } wsi->u.http2.requested_POLLOUT = 0; if (!wsi->u.http2.initialized) { lwsl_info("pollout on uninitialized http2 conn\n"); return 0; } lwsl_info("%s: doing children\n", __func__); wsi2 = wsi; do { wsi2 = wsi2->u.http2.next_child_wsi; lwsl_info("%s: child %p\n", __func__, wsi2); if (!wsi2) continue; if (!wsi2->u.http2.requested_POLLOUT) continue; wsi2->u.http2.requested_POLLOUT = 0; if (lws_calllback_as_writeable(context, wsi2)) { lwsl_debug("Closing POLLOUT child\n"); libwebsocket_close_and_free_session(context, wsi2, LWS_CLOSE_STATUS_NOSTATUS); } wsi2 = wsi; } while (wsi2 != NULL && !lws_send_pipe_choked(wsi)); lwsl_info("%s: completed\n", __func__); return 0; notify: #endif return lws_calllback_as_writeable(context, wsi); }
LWS_VISIBLE int lws_server_socket_service_ssl(struct libwebsocket_context *context, struct libwebsocket **pwsi, struct libwebsocket *new_wsi, int accept_fd, struct libwebsocket_pollfd *pollfd) { int n, m; struct libwebsocket *wsi = *pwsi; #ifndef USE_CYASSL BIO *bio; #endif if (!LWS_SSL_ENABLED(context)) return 0; switch (wsi->mode) { case LWS_CONNMODE_SERVER_LISTENER: if (!new_wsi) { lwsl_err("no new_wsi\n"); return 0; } new_wsi->ssl = SSL_new(context->ssl_ctx); if (new_wsi->ssl == NULL) { lwsl_err("SSL_new failed: %s\n", ERR_error_string(SSL_get_error( new_wsi->ssl, 0), NULL)); libwebsockets_decode_ssl_error(); lws_free(new_wsi); compatible_close(accept_fd); break; } SSL_set_ex_data(new_wsi->ssl, openssl_websocket_private_data_index, context); SSL_set_fd(new_wsi->ssl, accept_fd); #ifdef USE_CYASSL CyaSSL_set_using_nonblock(new_wsi->ssl, 1); #else SSL_set_mode(new_wsi->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); bio = SSL_get_rbio(new_wsi->ssl); if (bio) BIO_set_nbio(bio, 1); /* nonblocking */ else lwsl_notice("NULL rbio\n"); bio = SSL_get_wbio(new_wsi->ssl); if (bio) BIO_set_nbio(bio, 1); /* nonblocking */ else lwsl_notice("NULL rbio\n"); #endif /* * we are not accepted yet, but we need to enter ourselves * as a live connection. That way we can retry when more * pieces come if we're not sorted yet */ *pwsi = new_wsi; wsi = *pwsi; wsi->mode = LWS_CONNMODE_SSL_ACK_PENDING; insert_wsi_socket_into_fds(context, wsi); libwebsocket_set_timeout(wsi, PENDING_TIMEOUT_SSL_ACCEPT, AWAITING_TIMEOUT); lwsl_info("inserted SSL accept into fds, trying SSL_accept\n"); /* fallthru */ case LWS_CONNMODE_SSL_ACK_PENDING: if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) goto fail; lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE); lws_latency_pre(context, wsi); n = recv(wsi->sock, context->service_buffer, sizeof(context->service_buffer), MSG_PEEK); /* * optionally allow non-SSL connect on SSL listening socket * This is disabled by default, if enabled it goes around any * SSL-level access control (eg, client-side certs) so leave * it disabled unless you know it's not a problem for you */ if (context->allow_non_ssl_on_ssl_port && n >= 1 && context->service_buffer[0] >= ' ') { /* * TLS content-type for Handshake is 0x16 * TLS content-type for ChangeCipherSpec Record is 0x14 * * A non-ssl session will start with the HTTP method in * ASCII. If we see it's not a legit SSL handshake * kill the SSL for this connection and try to handle * as a HTTP connection upgrade directly. */ wsi->use_ssl = 0; SSL_shutdown(wsi->ssl); SSL_free(wsi->ssl); wsi->ssl = NULL; goto accepted; } /* normal SSL connection processing path */ n = SSL_accept(wsi->ssl); lws_latency(context, wsi, "SSL_accept LWS_CONNMODE_SSL_ACK_PENDING\n", n, n == 1); if (n == 1) goto accepted; m = SSL_get_error(wsi->ssl, n); lwsl_debug("SSL_accept failed %d / %s\n", m, ERR_error_string(m, NULL)); if (m == SSL_ERROR_WANT_READ) { if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) goto fail; lws_libev_io(context, wsi, LWS_EV_START | LWS_EV_READ); lwsl_info("SSL_ERROR_WANT_READ\n"); break; } if (m == SSL_ERROR_WANT_WRITE) { if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) goto fail; lws_libev_io(context, wsi, LWS_EV_START | LWS_EV_WRITE); break; } lwsl_debug("SSL_accept failed skt %u: %s\n", pollfd->fd, ERR_error_string(m, NULL)); goto fail; accepted: /* OK, we are accepted... give him some time to negotiate */ libwebsocket_set_timeout(wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER, AWAITING_TIMEOUT); wsi->mode = LWS_CONNMODE_HTTP_SERVING; lws_http2_configure_if_upgraded(wsi); lwsl_debug("accepted new SSL conn\n"); break; } return 0; fail: return 1; }
LWS_VISIBLE int lws_server_socket_service_ssl(struct lws *wsi, lws_sockfd_type accept_fd) { struct lws_context *context = wsi->context; struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; int n, m; #ifndef USE_WOLFSSL BIO *bio; #endif if (!LWS_SSL_ENABLED(context)) return 0; lwsl_err("%s: mode %d, state %d\n", __func__, wsi->mode, wsi->state); switch (wsi->mode) { case LWSCM_SSL_INIT: if (!wsi) return 0; wsi->ssl = SSL_new(context->ssl_ctx); if (wsi->ssl == NULL) { lwsl_err("SSL_new failed: %s\n", ERR_error_string(SSL_get_error(wsi->ssl, 0), NULL)); lws_decode_ssl_error(); compatible_close(accept_fd); goto fail; } SSL_set_ex_data(wsi->ssl, openssl_websocket_private_data_index, context); SSL_set_fd(wsi->ssl, accept_fd); #ifdef USE_WOLFSSL #ifdef USE_OLD_CYASSL CyaSSL_set_using_nonblock(wsi->ssl, 1); #else wolfSSL_set_using_nonblock(wsi->ssl, 1); #endif #else SSL_set_mode(wsi->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); bio = SSL_get_rbio(wsi->ssl); if (bio) BIO_set_nbio(bio, 1); /* nonblocking */ else lwsl_notice("NULL rbio\n"); bio = SSL_get_wbio(wsi->ssl); if (bio) BIO_set_nbio(bio, 1); /* nonblocking */ else lwsl_notice("NULL rbio\n"); #endif /* * we are not accepted yet, but we need to enter ourselves * as a live connection. That way we can retry when more * pieces come if we're not sorted yet */ wsi->mode = LWSCM_SSL_ACK_PENDING; if (insert_wsi_socket_into_fds(context, wsi)) goto fail; lws_set_timeout(wsi, PENDING_TIMEOUT_SSL_ACCEPT, AWAITING_TIMEOUT); lwsl_info("inserted SSL accept into fds, trying SSL_accept\n"); /* fallthru */ case LWSCM_SSL_ACK_PENDING: if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) goto fail; lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_WRITE); lws_latency_pre(context, wsi); n = recv(wsi->sock, (char *)pt->serv_buf, LWS_MAX_SOCKET_IO_BUF, MSG_PEEK); /* * optionally allow non-SSL connect on SSL listening socket * This is disabled by default, if enabled it goes around any * SSL-level access control (eg, client-side certs) so leave * it disabled unless you know it's not a problem for you */ if (context->allow_non_ssl_on_ssl_port) { if (n >= 1 && pt->serv_buf[0] >= ' ') { /* * TLS content-type for Handshake is 0x16, and * for ChangeCipherSpec Record, it's 0x14 * * A non-ssl session will start with the HTTP * method in ASCII. If we see it's not a legit * SSL handshake kill the SSL for this * connection and try to handle as a HTTP * connection upgrade directly. */ wsi->use_ssl = 0; SSL_shutdown(wsi->ssl); SSL_free(wsi->ssl); wsi->ssl = NULL; goto accepted; } if (!n) /* * connection is gone, or nothing to read * if it's gone, we will timeout on * PENDING_TIMEOUT_SSL_ACCEPT */ break; if (n < 0 && (LWS_ERRNO == LWS_EAGAIN || LWS_ERRNO == LWS_EWOULDBLOCK)) { /* * well, we get no way to know ssl or not * so go around again waiting for something * to come and give us a hint, or timeout the * connection. */ m = SSL_ERROR_WANT_READ; goto go_again; } } /* normal SSL connection processing path */ n = SSL_accept(wsi->ssl); lws_latency(context, wsi, "SSL_accept LWSCM_SSL_ACK_PENDING\n", n, n == 1); if (n == 1) goto accepted; m = SSL_get_error(wsi->ssl, n); lwsl_debug("SSL_accept failed %d / %s\n", m, ERR_error_string(m, NULL)); go_again: if (m == SSL_ERROR_WANT_READ) { if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) goto fail; lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ); lwsl_info("SSL_ERROR_WANT_READ\n"); break; } if (m == SSL_ERROR_WANT_WRITE) { if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) goto fail; lws_libev_io(wsi, LWS_EV_START | LWS_EV_WRITE); break; } lwsl_debug("SSL_accept failed skt %u: %s\n", wsi->sock, ERR_error_string(m, NULL)); goto fail; accepted: /* OK, we are accepted... give him some time to negotiate */ lws_set_timeout(wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER, AWAITING_TIMEOUT); wsi->mode = LWSCM_HTTP_SERVING; lws_http2_configure_if_upgraded(wsi); lwsl_debug("accepted new SSL conn\n"); break; } return 0; fail: return 1; }