static void lws_libuv_closewsi(uv_handle_t* handle) { struct lws *n = NULL, *wsi = (struct lws *)(((char *)handle) - (char *)(&n->w_read.uv_watcher)); struct lws_context *context = lws_get_context(wsi); int lspd = 0; if (wsi->mode == LWSCM_SERVER_LISTENER && wsi->context->deprecated) { lspd = 1; context->deprecation_pending_listen_close_count--; if (!context->deprecation_pending_listen_close_count) lspd = 2; } lws_close_free_wsi_final(wsi); if (lspd == 2 && context->deprecation_cb) { lwsl_notice("calling deprecation callback\n"); context->deprecation_cb(); } if (context->requested_kill && context->count_wsi_allocated == 0) lws_libuv_kill(context); }
static void esp8266_cb_sent(void *arg) { struct espconn *conn = arg; struct lws *wsi = conn->reverse; struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; // lwsl_err("%s: wsi %p (psc %d) wsi->position_in_fds_table=%d\n", __func__, wsi, wsi->pending_send_completion, wsi->position_in_fds_table); wsi->pending_send_completion--; if (wsi->close_is_pending_send_completion && !wsi->pending_send_completion && !lws_partial_buffered(wsi)) { lwsl_notice("doing delayed close\n"); lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); } if (pt->fds[wsi->position_in_fds_table].events & LWS_POLLOUT) { struct lws_pollfd pollfd; pollfd.fd = arg; pollfd.events = LWS_POLLOUT; pollfd.revents = LWS_POLLOUT; // lwsl_notice("informing POLLOUT\n"); lws_service_fd(lws_get_context(wsi), &pollfd); } }
int lws_change_pollfd(struct lws *wsi, int _and, int _or) { struct lws_context_per_thread *pt; struct lws_context *context; struct lws_pollargs pa; int ret = 0; if (!wsi || !wsi->protocol || wsi->position_in_fds_table < 0) return 1; context = lws_get_context(wsi); if (!context) return 1; if (context->protocols[0].callback(wsi, LWS_CALLBACK_LOCK_POLL, wsi->user_space, (void *) &pa, 0)) return -1; pt = &context->pt[(int)wsi->tsi]; lws_pt_lock(pt); ret = _lws_change_pollfd(wsi, _and, _or, &pa); lws_pt_unlock(pt); if (context->protocols[0].callback(wsi, LWS_CALLBACK_UNLOCK_POLL, wsi->user_space, (void *) &pa, 0)) ret = -1; return ret; }
LWS_VISIBLE void lws_libev_io(struct lws *wsi, int flags) { struct lws_context *context = lws_get_context(wsi); if (!LWS_LIBEV_ENABLED(context)) return; if (!context->io_loop) return; assert((flags & (LWS_EV_START | LWS_EV_STOP)) && (flags & (LWS_EV_READ | LWS_EV_WRITE))); if (flags & LWS_EV_START) { if (flags & LWS_EV_WRITE) ev_io_start(context->io_loop, &wsi->w_write.watcher); if (flags & LWS_EV_READ) ev_io_start(context->io_loop, &wsi->w_read.watcher); } else { if (flags & LWS_EV_WRITE) ev_io_stop(context->io_loop, &wsi->w_write.watcher); if (flags & LWS_EV_READ) ev_io_stop(context->io_loop, &wsi->w_read.watcher); } }
LWS_VISIBLE void lws_libev_io(struct lws *wsi, int flags) { struct lws_context *context = lws_get_context(wsi); struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; if (!LWS_LIBEV_ENABLED(context)) return; if (!pt->io_loop_ev || context->being_destroyed) return; assert((flags & (LWS_EV_START | LWS_EV_STOP)) && (flags & (LWS_EV_READ | LWS_EV_WRITE))); if (flags & LWS_EV_START) { if (flags & LWS_EV_WRITE) ev_io_start(pt->io_loop_ev, &wsi->w_write.ev_watcher); if (flags & LWS_EV_READ) ev_io_start(pt->io_loop_ev, &wsi->w_read.ev_watcher); } else { if (flags & LWS_EV_WRITE) ev_io_stop(pt->io_loop_ev, &wsi->w_write.ev_watcher); if (flags & LWS_EV_READ) ev_io_stop(pt->io_loop_ev, &wsi->w_read.ev_watcher); } }
static int unreal_networking_server ( struct lws *Wsi, enum lws_callback_reasons Reason, void *User, void *In, size_t Len ) { struct lws_context *Context = lws_get_context(Wsi); PerSessionDataServer* BufferInfo = (PerSessionDataServer*)User; FWebSocketServer* Server = (FWebSocketServer*)lws_context_user(Context); if (!Server->IsAlive) { return 0; } switch (Reason) { case LWS_CALLBACK_ESTABLISHED: { BufferInfo->Socket = new FWebSocket(Context, Wsi); Server->ConnectedCallBack.ExecuteIfBound(BufferInfo->Socket); lws_set_timeout(Wsi, NO_PENDING_TIMEOUT, 0); } break; case LWS_CALLBACK_RECEIVE: { BufferInfo->Socket->OnRawRecieve(In, Len); lws_set_timeout(Wsi, NO_PENDING_TIMEOUT, 0); } break; case LWS_CALLBACK_SERVER_WRITEABLE: { BufferInfo->Socket->OnRawWebSocketWritable(Wsi); lws_set_timeout(Wsi, NO_PENDING_TIMEOUT, 0); } break; case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: { BufferInfo->Socket->ErrorCallBack.ExecuteIfBound(); } break; case LWS_CALLBACK_WSI_DESTROY: case LWS_CALLBACK_PROTOCOL_DESTROY: case LWS_CALLBACK_CLOSED: case LWS_CALLBACK_CLOSED_HTTP: { Server->IsAlive = false; } break; } return 0; }
LWS_VISIBLE int lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type, const char *other_headers, int other_headers_len) { struct lws_context *context = lws_get_context(wsi); struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; unsigned char *response = pt->serv_buf + LWS_PRE; unsigned char *p = response; unsigned char *end = p + LWS_MAX_SOCKET_IO_BUF - LWS_PRE; int ret = 0; wsi->u.http.fd = lws_plat_file_open(wsi, file, &wsi->u.http.filelen, O_RDONLY); if (wsi->u.http.fd == LWS_INVALID_FILE) { lwsl_err("Unable to open '%s'\n", file); lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL); return -1; } if (lws_add_http_header_status(wsi, 200, &p, end)) return -1; if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER, (unsigned char *)"libwebsockets", 13, &p, end)) return -1; if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE, (unsigned char *)content_type, strlen(content_type), &p, end)) return -1; if (lws_add_http_header_content_length(wsi, wsi->u.http.filelen, &p, end)) return -1; if (other_headers) { if ((end - p) < other_headers_len) return -1; memcpy(p, other_headers, other_headers_len); p += other_headers_len; } if (lws_finalize_http_header(wsi, &p, end)) return -1; ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS); if (ret != (p - response)) { lwsl_err("_write returned %d from %d\n", ret, (p - response)); return -1; } wsi->u.http.filepos = 0; wsi->state = LWSS_HTTP_ISSUING_FILE; return lws_serve_http_file_fragment(wsi); }
void lws_libuv_closehandle(struct lws *wsi) { struct lws_context *context = lws_get_context(wsi); /* required to defer actual deletion until libuv has processed it */ uv_close((uv_handle_t*)&wsi->w_read.uv_watcher, lws_libuv_closewsi); if (context->requested_kill && context->count_wsi_allocated == 0) lws_libuv_kill(context); }
void lws_libuv_io(struct lws *wsi, int flags) { struct lws_context *context = lws_get_context(wsi); struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; #if defined(WIN32) || defined(_WIN32) int current_events = wsi->w_read.uv_watcher.events & (UV_READABLE | UV_WRITABLE); #else int current_events = wsi->w_read.uv_watcher.io_watcher.pevents & (UV_READABLE | UV_WRITABLE); #endif struct lws_io_watcher *w = &wsi->w_read; if (!LWS_LIBUV_ENABLED(context)) return; // lwsl_notice("%s: wsi: %p, flags:0x%x\n", __func__, wsi, flags); // w->context is set after the loop is initialized if (!pt->io_loop_uv || !w->context) { lwsl_info("%s: no io loop yet\n", __func__); return; } if (!((flags & (LWS_EV_START | LWS_EV_STOP)) && (flags & (LWS_EV_READ | LWS_EV_WRITE)))) { lwsl_err("%s: assert: flags %d", __func__, flags); assert(0); } if (flags & LWS_EV_START) { if (flags & LWS_EV_WRITE) current_events |= UV_WRITABLE; if (flags & LWS_EV_READ) current_events |= UV_READABLE; uv_poll_start(&w->uv_watcher, current_events, lws_io_cb); } else { if (flags & LWS_EV_WRITE) current_events &= ~UV_WRITABLE; if (flags & LWS_EV_READ) current_events &= ~UV_READABLE; if (!(current_events & (UV_READABLE | UV_WRITABLE))) uv_poll_stop(&w->uv_watcher); else uv_poll_start(&w->uv_watcher, current_events, lws_io_cb); } }
bool FJavascriptWebSocketServer::Init(uint32 Port, FJavascriptWebSocketClientConnectedCallBack CallBack) { // setup log level. #if !UE_BUILD_SHIPPING lws_set_log_level(LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_DEBUG | LLL_INFO, lws_debugLog_JS); #endif Protocols = new lws_protocols[3]; FMemory::Memzero(Protocols, sizeof(lws_protocols) * 3); Protocols[0].name = "binary"; Protocols[0].callback = [](lws *Wsi, lws_callback_reasons Reason, void *User, void *In, size_t Len) { auto context = lws_get_context(Wsi); return reinterpret_cast<FJavascriptWebSocketServer*>(lws_context_user(context))->unreal_networking_server(Wsi, Reason, User, In, Len); }; Protocols[0].per_session_data_size = sizeof(PerSessionDataServer); Protocols[0].rx_buffer_size = 10 * 1024 * 1024; Protocols[1].name = nullptr; Protocols[1].callback = nullptr; Protocols[1].per_session_data_size = 0; struct lws_context_creation_info Info; memset(&Info, 0, sizeof(lws_context_creation_info)); // look up libwebsockets.h for details. Info.port = Port; ServerPort = Port; // we listen on all available interfaces. Info.iface = NULL; Info.protocols = &Protocols[0]; // no extensions Info.extensions = NULL; Info.gid = -1; Info.uid = -1; Info.options = 0; // tack on this object. Info.user = this; Info.port = Port; Context = lws_create_context(&Info); if (Context == NULL) { ServerPort = 0; delete Protocols; Protocols = NULL; IsAlive = false; return false; // couldn't create a server. } ConnectedCallBack = CallBack; IsAlive = true; return true; }
static void lws_libuv_closewsi(uv_handle_t* handle) { struct lws *n = NULL, *wsi = (struct lws *)(((char *)handle) - (char *)(&n->w_read.uv_watcher)); struct lws_context *context = lws_get_context(wsi); lws_close_free_wsi_final(wsi); if (context->requested_kill && context->count_wsi_allocated == 0) lws_libuv_kill(context); }
static void update_status(struct lws *wsi, struct per_session_data__lws_status *pss) { struct per_session_data__lws_status **pp = &list; int subsequent = 0; char *p = cache + LWS_PRE, *start = p; char date[128]; time_t t; struct tm *ptm; #ifndef WIN32 struct tm tm; #endif p += snprintf(p, 512, " { %s, \"wsi\":\"%d\", \"conns\":[", server_info, live_wsi); /* render the list */ while (*pp) { t = (*pp)->tv_established.tv_sec; #ifdef WIN32 ptm = localtime(&t); if (!ptm) #else ptm = &tm; if (!localtime_r(&t, &tm)) #endif strcpy(date, "unknown"); else strftime(date, sizeof(date), "%F %H:%M %Z", ptm); if ((p - start) > (sizeof(cache) - 512)) break; if (subsequent) *p++ = ','; subsequent = 1; p += snprintf(p, sizeof(cache) - (p - start) - 1, "{\"peer\":\"%s\",\"time\":\"%s\"," "\"ua\":\"%s\"}", (*pp)->ip, date, (*pp)->user_agent); pp = &((*pp)->list); } p += sprintf(p, "]}"); cache_len = p - start; lwsl_err("cache_len %d\n", cache_len); *p = '\0'; /* since we changed the list, increment the 'version' */ current++; /* update everyone */ lws_callback_on_writable_all_protocol(lws_get_context(wsi), lws_get_protocol(wsi)); }
static int unreal_networking_client( struct lws *Wsi, enum lws_callback_reasons Reason, void *User, void *In, size_t Len) { struct lws_context *Context = lws_get_context(Wsi); FWebSocket* Socket = (FWebSocket*)lws_context_user(Context); switch (Reason) { case LWS_CALLBACK_CLIENT_ESTABLISHED: { Socket->ConnectedCallBack.Broadcast(); lws_set_timeout(Wsi, NO_PENDING_TIMEOUT, 0); check(Socket->Wsi == Wsi); } break; case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: { Socket->ErrorCallBack.Broadcast(); return -1; } break; case LWS_CALLBACK_CLIENT_RECEIVE: { // push it on the socket. Socket->OnRawRecieve(In, (uint32)Len, !!lws_frame_is_binary(Wsi)); check(Socket->Wsi == Wsi); lws_set_timeout(Wsi, NO_PENDING_TIMEOUT, 0); break; } case LWS_CALLBACK_CLIENT_WRITEABLE: { check(Socket->Wsi == Wsi); Socket->OnRawWebSocketWritable(Wsi); lws_callback_on_writable(Wsi); lws_set_timeout(Wsi, NO_PENDING_TIMEOUT, 0); break; } case LWS_CALLBACK_CLOSED: { Socket->ErrorCallBack.Broadcast(); return -1; } } return 0; }
static void esp8266_cb_rx(void *arg, char *data, unsigned short len) { struct espconn *conn = arg; struct lws *wsi = conn->reverse; struct lws_context_per_thread *pt = &wsi->context->pt[0]; struct lws_pollfd pollfd; int n = 0; /* * if we're doing HTTP headers, and we have no ah, check if there is * a free ah, if not, have to buffer it */ if (!wsi->hdr_parsing_completed && !wsi->ah) { for (n = 0; n < wsi->context->max_http_header_pool; n++) if (!pt->ah_pool[n].in_use) break; n = n == wsi->context->max_http_header_pool; } if (!(pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN) || n) { wsi->premature_rx = realloc(wsi->premature_rx, wsi->prem_rx_size + len); if (!wsi->premature_rx) return; os_memcpy((char *)wsi->premature_rx + wsi->prem_rx_size, data, len); wsi->prem_rx_size += len; // lwsl_notice("%s: wsi %p: len %d BUFFERING\n", __func__, wsi, len); if (n) /* we know it will fail, but we will get on the wait list */ n = lws_header_table_attach(wsi, 0); (void)n; return; } //lwsl_err("%s: wsi %p. len %d\n", __func__, wsi, len); pollfd.fd = arg; pollfd.events = LWS_POLLIN; pollfd.revents = LWS_POLLIN; wsi->context->rxd = data; wsi->context->rxd_len = len; lws_service_fd(lws_get_context(wsi), &pollfd); }
void lws_libuv_accept(struct lws *wsi, lws_sockfd_type accept_fd) { struct lws_context *context = lws_get_context(wsi); struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; if (!LWS_LIBUV_ENABLED(context)) return; lwsl_debug("%s: new wsi %p\n", __func__, wsi); wsi->w_read.context = context; uv_poll_init_socket(pt->io_loop_uv, &wsi->w_read.uv_watcher, accept_fd); }
LWS_VISIBLE void lws_libev_accept(struct lws *new_wsi, int accept_fd) { struct lws_context *context = lws_get_context(new_wsi); struct ev_io *r = &new_wsi->w_read.watcher; struct ev_io *w = &new_wsi->w_write.watcher; if (!LWS_LIBEV_ENABLED(context)) return; new_wsi->w_read.context = context; new_wsi->w_write.context = context; ev_io_init(r, lws_accept_cb, accept_fd, EV_READ); ev_io_init(w, lws_accept_cb, accept_fd, EV_WRITE); }
// callback. int FJavascriptWebSocketServer::unreal_networking_server(lws *InWsi, lws_callback_reasons Reason, void* User, void *In, size_t Len) { struct lws_context *LwsContext = lws_get_context(InWsi); PerSessionDataServer* BufferInfo = (PerSessionDataServer*)User; FJavascriptWebSocketServer* Server = (FJavascriptWebSocketServer*)lws_context_user(LwsContext); if (!Server->IsAlive) { return 0; } switch (Reason) { case LWS_CALLBACK_ESTABLISHED: { BufferInfo->Socket = new FJavascriptWebSocket(LwsContext, InWsi); ConnectedCallBack.ExecuteIfBound(BufferInfo->Socket); lws_set_timeout(InWsi, NO_PENDING_TIMEOUT, 0); } break; case LWS_CALLBACK_RECEIVE: { BufferInfo->Socket->OnRawRecieve(In, Len); lws_set_timeout(InWsi, NO_PENDING_TIMEOUT, 0); } break; case LWS_CALLBACK_SERVER_WRITEABLE: if (BufferInfo->Socket->Context == LwsContext) // UE-68340 -- bandaid until this file is removed in favor of using LwsWebSocketsManager.cpp & LwsWebSocket.cpp { BufferInfo->Socket->OnRawWebSocketWritable(InWsi); } lws_set_timeout(InWsi, NO_PENDING_TIMEOUT, 0); break; case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: { BufferInfo->Socket->ErrorCallBack.ExecuteIfBound(); } break; case LWS_CALLBACK_WSI_DESTROY: case LWS_CALLBACK_PROTOCOL_DESTROY: case LWS_CALLBACK_CLOSED: case LWS_CALLBACK_CLOSED_HTTP: break; } return 0; }
void lws_libuv_accept(struct lws *wsi, lws_sock_file_fd_type desc) { struct lws_context *context = lws_get_context(wsi); struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; if (!LWS_LIBUV_ENABLED(context)) return; wsi->w_read.context = context; if (wsi->mode == LWSCM_RAW_FILEDESC || wsi->event_pipe) uv_poll_init(pt->io_loop_uv, &wsi->w_read.uv_watcher, (int)(long long)desc.filefd); else uv_poll_init_socket(pt->io_loop_uv, &wsi->w_read.uv_watcher, desc.sockfd); }
void lws_libuv_io(struct lws *wsi, int flags) { struct lws_context *context = lws_get_context(wsi); struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; int current_events = wsi->w_read.uv_watcher.io_watcher.pevents & (UV_READABLE | UV_WRITABLE); struct lws_io_watcher *w = &wsi->w_read; if (!LWS_LIBUV_ENABLED(context)) return; lwsl_debug("%s: wsi: %p, flags:%d\n", __func__, wsi, flags); if (!pt->io_loop_uv) { lwsl_info("%s: no io loop yet\n", __func__); return; } assert((flags & (LWS_EV_START | LWS_EV_STOP)) && (flags & (LWS_EV_READ | LWS_EV_WRITE))); if (flags & LWS_EV_START) { if (flags & LWS_EV_WRITE) current_events |= UV_WRITABLE; if (flags & LWS_EV_READ) current_events |= UV_READABLE; uv_poll_start(&w->uv_watcher, current_events, lws_accept_cb); } else { if (flags & LWS_EV_WRITE) current_events &= ~UV_WRITABLE; if (flags & LWS_EV_READ) current_events &= ~UV_READABLE; if (!(current_events & (UV_READABLE | UV_WRITABLE))) uv_poll_stop(&w->uv_watcher); else uv_poll_start(&w->uv_watcher, current_events, lws_accept_cb); } }
int lws_ext_cb_active(struct lws *wsi, int reason, void *arg, int len) { int n, m, handled = 0; for (n = 0; n < wsi->count_act_ext; n++) { m = wsi->active_extensions[n]->callback(lws_get_context(wsi), wsi->active_extensions[n], wsi, reason, wsi->act_ext_user[n], arg, len); if (m < 0) { lwsl_ext("Ext '%s' failed to handle callback %d!\n", wsi->active_extensions[n]->name, reason); return -1; } if (m > handled) handled = m; } return handled; }
/** * lws_return_http_status() - Return simple http status * @wsi: Websocket instance (available from user callback) * @code: Status index, eg, 404 * @html_body: User-readable HTML description < 1KB, or NULL * * Helper to report HTTP errors back to the client cleanly and * consistently */ LWS_VISIBLE int lws_return_http_status(struct lws *wsi, unsigned int code, const char *html_body) { struct lws_context *context = lws_get_context(wsi); struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; unsigned char *p = pt->serv_buf + LWS_PRE; unsigned char *start = p, *body = p + 512; unsigned char *end = p + LWS_MAX_SOCKET_IO_BUF - LWS_PRE; int n, m, len; char slen[20]; if (!html_body) html_body = ""; len = sprintf((char *)body, "<html><body><h1>%u</h1>%s</body></html>", code, html_body); if (lws_add_http_header_status(wsi, code, &p, end)) return 1; if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE, (unsigned char *)"text/html", 9, &p, end)) return 1; n = sprintf(slen, "%d", len); if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH, (unsigned char *)slen, n, &p, end)) return 1; if (lws_finalize_http_header(wsi, &p, end)) return 1; m = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS); if (m != (int)(p - start)) return 1; m = lws_write(wsi, body, len, LWS_WRITE_HTTP); return m != n; }
LWS_VISIBLE int lws_plat_change_pollfd(struct lws_context *context, struct lws *wsi, struct lws_pollfd *pfd) { void *p; //lwsl_notice("%s: %p: wsi->pift=%d, events %d\n", // __func__, wsi, wsi->position_in_fds_table, pfd->events); if (pfd->events & LWS_POLLIN) { if (wsi->premature_rx) { lwsl_notice("replaying buffered rx: wsi %p\n", wsi); p = wsi->premature_rx; wsi->premature_rx = NULL; esp8266_cb_rx(wsi->desc.sockfd, (char *)p + wsi->prem_rx_pos, wsi->prem_rx_size - wsi->prem_rx_pos); wsi->prem_rx_size = 0; wsi->prem_rx_pos = 0; lws_free(p); } if (espconn_recv_unhold(wsi->desc.sockfd) < 0) return -1; } else if (espconn_recv_hold(wsi->desc.sockfd) < 0) return -1; if (!(pfd->events & LWS_POLLOUT)) return 0; if (!wsi->pending_send_completion) { pfd->revents |= LWS_POLLOUT; // lwsl_notice("doing POLLOUT\n"); lws_service_fd(lws_get_context(wsi), pfd); } //else //lwsl_notice("pending sc\n"); return 0; }
/** * lws_return_http_status() - Return simple http status * @wsi: Websocket instance (available from user callback) * @code: Status index, eg, 404 * @html_body: User-readable HTML description < 1KB, or NULL * * Helper to report HTTP errors back to the client cleanly and * consistently */ LWS_VISIBLE int lws_return_http_status(struct lws *wsi, unsigned int code, const char *html_body) { int n, m; struct lws_context *context = lws_get_context(wsi); unsigned char *p = context->serv_buf + LWS_SEND_BUFFER_PRE_PADDING; unsigned char *start = p; unsigned char *end = p + sizeof(context->serv_buf) - LWS_SEND_BUFFER_PRE_PADDING; if (!html_body) html_body = ""; if (lws_add_http_header_status(wsi, code, &p, end)) return 1; if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER, (unsigned char *)"libwebsockets", 13, &p, end)) return 1; if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE, (unsigned char *)"text/html", 9, &p, end)) return 1; if (lws_finalize_http_header(wsi, &p, end)) return 1; m = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS); if (m != (int)(p - start)) return 1; n = sprintf((char *)start, "<html><body><h1>%u</h1>%s</body></html>", code, html_body); m = lws_write(wsi, start, n, LWS_WRITE_HTTP); return m != n; }
int lws_client_interpret_server_handshake(struct lws *wsi) { int n, len, okay = 0, isErrorCodeReceived = 0, port = 0, ssl = 0; struct lws_context *context = wsi->context; int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR; const char *pc, *prot, *ads = NULL, *path; char *p; #ifndef LWS_NO_EXTENSIONS struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; char *sb = (char *)&pt->serv_buf[0]; const struct lws_ext_options *opts; const struct lws_extension *ext; char ext_name[128]; const char *c, *a; char ignore; int more = 1; void *v; #endif /* * well, what the server sent looked reasonable for syntax. * Now let's confirm it sent all the necessary headers */ p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP); if (!p) { lwsl_info("no URI\n"); goto bail3; } n = atoi(p); if (n == 301 || n == 302 || n == 303 || n == 307 || n == 308) { p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_LOCATION); if (!p) goto bail3; if (lws_parse_uri(p, &prot, &ads, &port, &path)) goto bail3; if (!strcmp(prot, "wss://") || !strcmp(prot, "https://")) ssl = 1; if (lws_client_reset(wsi, ssl, ads, port, path, ads)) { lwsl_err("Redirect failed\n"); goto bail3; } return 0; } if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) { lwsl_info("no ACCEPT\n"); isErrorCodeReceived = 1; goto bail3; } if (p && strncmp(p, "101", 3)) { lwsl_warn( "lws_client_handshake: got bad HTTP response '%s'\n", p); goto bail3; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE); if (!p) { lwsl_info("no UPGRADE\n"); goto bail3; } strtolower(p); if (strcmp(p, "websocket")) { lwsl_warn( "lws_client_handshake: got bad Upgrade header '%s'\n", p); goto bail3; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION); if (!p) { lwsl_info("no Connection hdr\n"); goto bail3; } strtolower(p); if (strcmp(p, "upgrade")) { lwsl_warn("lws_client_int_s_hs: bad header %s\n", p); goto bail3; } pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS); if (!pc) { lwsl_parser("lws_client_int_s_hs: no protocol list\n"); } else lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc); /* * confirm the protocol the server wants to talk was in the list * of protocols we offered */ len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL); if (!len) { lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n"); /* * no protocol name to work from, * default to first protocol */ wsi->protocol = &context->protocols[0]; goto check_extensions; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL); len = strlen(p); while (pc && *pc && !okay) { if (!strncmp(pc, p, len) && (pc[len] == ',' || pc[len] == '\0')) { okay = 1; continue; } while (*pc && *pc++ != ',') ; while (*pc && *pc == ' ') pc++; } if (!okay) { lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p); goto bail2; } /* * identify the selected protocol struct and set it */ n = 0; wsi->protocol = NULL; while (context->protocols[n].callback && !wsi->protocol) { if (strcmp(p, context->protocols[n].name) == 0) { wsi->protocol = &context->protocols[n]; break; } n++; } if (wsi->protocol == NULL) { lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p); goto bail2; } check_extensions: #ifndef LWS_NO_EXTENSIONS /* instantiate the accepted extensions */ if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) { lwsl_ext("no client extenstions allowed by server\n"); goto check_accept; } /* * break down the list of server accepted extensions * and go through matching them or identifying bogons */ if (lws_hdr_copy(wsi, sb, LWS_MAX_SOCKET_IO_BUF, WSI_TOKEN_EXTENSIONS) < 0) { lwsl_warn("ext list from server failed to copy\n"); goto bail2; } c = sb; n = 0; ignore = 0; a = NULL; while (more) { if (*c && (*c != ',' && *c != '\t')) { if (*c == ';') { ignore = 1; if (!a) a = c + 1; } if (ignore || *c == ' ') { c++; continue; } ext_name[n] = *c++; if (n < sizeof(ext_name) - 1) n++; continue; } ext_name[n] = '\0'; ignore = 0; if (!*c) more = 0; else { c++; if (!n) continue; } /* check we actually support it */ lwsl_notice("checking client ext %s\n", ext_name); n = 0; ext = lws_get_context(wsi)->extensions; while (ext && ext->callback) { if (strcmp(ext_name, ext->name)) { ext++; continue; } n = 1; lwsl_notice("instantiating client ext %s\n", ext_name); /* instantiate the extension on this conn */ wsi->active_extensions[wsi->count_act_ext] = ext; /* allow him to construct his ext instance */ ext->callback(lws_get_context(wsi), ext, wsi, LWS_EXT_CB_CLIENT_CONSTRUCT, (void *)&wsi->act_ext_user[wsi->count_act_ext], (void *)&opts, 0); /* * allow the user code to override ext defaults if it * wants to */ ext_name[0] = '\0'; if (user_callback_handle_rxflow(wsi->protocol->callback, wsi, LWS_CALLBACK_WS_EXT_DEFAULTS, (char *)ext->name, ext_name, sizeof(ext_name))) goto bail2; if (ext_name[0] && lws_ext_parse_options(ext, wsi, wsi->act_ext_user[ wsi->count_act_ext], opts, ext_name, strlen(ext_name))) { lwsl_err("%s: unable to parse user defaults '%s'", __func__, ext_name); goto bail2; } /* * give the extension the server options */ if (a && lws_ext_parse_options(ext, wsi, wsi->act_ext_user[wsi->count_act_ext], opts, a, c - a)) { lwsl_err("%s: unable to parse remote def '%s'", __func__, a); goto bail2; } if (ext->callback(lws_get_context(wsi), ext, wsi, LWS_EXT_CB_OPTION_CONFIRM, wsi->act_ext_user[wsi->count_act_ext], NULL, 0)) { lwsl_err("%s: ext %s rejects server options %s", ext->name, a); goto bail2; } wsi->count_act_ext++; ext++; } if (n == 0) { lwsl_warn("Unknown ext '%s'!\n", ext_name); goto bail2; } a = NULL; n = 0; } check_accept: #endif /* * Confirm his accept token is the one we precomputed */ p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT); if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) { lwsl_warn("lws_client_int_s_hs: accept '%s' wrong vs '%s'\n", p, wsi->u.hdr.ah->initial_handshake_hash_base64); goto bail2; } /* allocate the per-connection user memory (if any) */ if (lws_ensure_user_space(wsi)) { lwsl_err("Problem allocating wsi user mem\n"); goto bail2; } /* * we seem to be good to go, give client last chance to check * headers and OK it */ if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH, wsi->user_space, NULL, 0)) goto bail2; /* clear his proxy connection timeout */ lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); /* free up his parsing allocations */ lws_free_header_table(wsi); lws_union_transition(wsi, LWSCM_WS_CLIENT); wsi->state = LWSS_ESTABLISHED; wsi->rxflow_change_to = LWS_RXFLOW_ALLOW; /* * create the frame buffer for this connection according to the * size mentioned in the protocol definition. If 0 there, then * use a big default for compatibility */ n = wsi->protocol->rx_buffer_size; if (!n) n = LWS_MAX_SOCKET_IO_BUF; n += LWS_PRE; wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */); if (!wsi->u.ws.rx_ubuf) { lwsl_err("Out of Mem allocating rx buffer %d\n", n); goto bail2; } wsi->u.ws.rx_ubuf_alloc = n; lwsl_info("Allocating client RX buffer %d\n", n); if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF, (const char *)&n, sizeof n)) { lwsl_warn("Failed to set SNDBUF to %d", n); goto bail3; } lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name); /* call him back to inform him he is up */ if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED, wsi->user_space, NULL, 0)) goto bail3; #ifndef LWS_NO_EXTENSIONS /* * inform all extensions, not just active ones since they * already know */ ext = context->extensions; while (ext && ext->callback) { v = NULL; for (n = 0; n < wsi->count_act_ext; n++) if (wsi->active_extensions[n] == ext) v = wsi->act_ext_user[n]; ext->callback(context, ext, wsi, LWS_EXT_CB_ANY_WSI_ESTABLISHED, v, NULL, 0); ext++; } #endif return 0; bail3: close_reason = LWS_CLOSE_STATUS_NOSTATUS; bail2: if (wsi->protocol && wsi->state == LWSS_ESTABLISHED) { if (isErrorCodeReceived && p) { wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, p, (unsigned int)strlen(p)); } else { wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, NULL, 0); } } lwsl_info("closing connection due to bail2 connection error\n"); /* closing will free up his parsing allocations */ lws_close_free_wsi(wsi, close_reason); return 1; }
int lws_client_interpret_server_handshake(struct lws *wsi) { struct lws_context *context = wsi->context; int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR; int n, len, okay = 0, isErrorCodeReceived = 0; const char *pc; char *p; #ifndef LWS_NO_EXTENSIONS const struct lws_extension *ext; char ext_name[128]; const char *c; int more = 1; void *v; #endif /* * well, what the server sent looked reasonable for syntax. * Now let's confirm it sent all the necessary headers */ if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) { lwsl_info("no ACCEPT\n"); p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP); isErrorCodeReceived = 1; goto bail3; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP); if (!p) { lwsl_info("no URI\n"); goto bail3; } if (p && strncmp(p, "101", 3)) { lwsl_warn( "lws_client_handshake: got bad HTTP response '%s'\n", p); goto bail3; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE); if (!p) { lwsl_info("no UPGRADE\n"); goto bail3; } strtolower(p); if (strcmp(p, "websocket")) { lwsl_warn( "lws_client_handshake: got bad Upgrade header '%s'\n", p); goto bail3; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION); if (!p) { lwsl_info("no Connection hdr\n"); goto bail3; } strtolower(p); if (strcmp(p, "upgrade")) { lwsl_warn("lws_client_int_s_hs: bad header %s\n", p); goto bail3; } pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS); if (!pc) { lwsl_parser("lws_client_int_s_hs: no protocol list\n"); } else lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc); /* * confirm the protocol the server wants to talk was in the list * of protocols we offered */ len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL); if (!len) { lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n"); /* * no protocol name to work from, * default to first protocol */ wsi->protocol = &context->protocols[0]; goto check_extensions; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL); len = strlen(p); while (pc && *pc && !okay) { if (!strncmp(pc, p, len) && (pc[len] == ',' || pc[len] == '\0')) { okay = 1; continue; } while (*pc && *pc++ != ',') ; while (*pc && *pc == ' ') pc++; } if (!okay) { lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p); goto bail2; } /* * identify the selected protocol struct and set it */ n = 0; wsi->protocol = NULL; while (context->protocols[n].callback && !wsi->protocol) { if (strcmp(p, context->protocols[n].name) == 0) { wsi->protocol = &context->protocols[n]; break; } n++; } if (wsi->protocol == NULL) { lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p); goto bail2; } check_extensions: #ifndef LWS_NO_EXTENSIONS /* instantiate the accepted extensions */ if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) { lwsl_ext("no client extenstions allowed by server\n"); goto check_accept; } /* * break down the list of server accepted extensions * and go through matching them or identifying bogons */ if (lws_hdr_copy(wsi, (char *)context->serv_buf, sizeof(context->serv_buf), WSI_TOKEN_EXTENSIONS) < 0) { lwsl_warn("ext list from server failed to copy\n"); goto bail2; } c = (char *)context->serv_buf; n = 0; while (more) { if (*c && (*c != ',' && *c != ' ' && *c != '\t')) { ext_name[n] = *c++; if (n < sizeof(ext_name) - 1) n++; continue; } ext_name[n] = '\0'; if (!*c) more = 0; else { c++; if (!n) continue; } /* check we actually support it */ lwsl_ext("checking client ext %s\n", ext_name); n = 0; ext = lws_get_context(wsi)->extensions; while (ext && ext->callback) { if (strcmp(ext_name, ext->name)) { ext++; continue; } n = 1; lwsl_ext("instantiating client ext %s\n", ext_name); /* instantiate the extension on this conn */ wsi->active_extensions_user[ wsi->count_active_extensions] = lws_zalloc(ext->per_session_data_size); if (wsi->active_extensions_user[ wsi->count_active_extensions] == NULL) { lwsl_err("Out of mem\n"); goto bail2; } wsi->active_extensions[ wsi->count_active_extensions] = ext; /* allow him to construct his context */ ext->callback(lws_get_context(wsi), ext, wsi, LWS_EXT_CALLBACK_CLIENT_CONSTRUCT, wsi->active_extensions_user[ wsi->count_active_extensions], NULL, 0); wsi->count_active_extensions++; ext++; } if (n == 0) { lwsl_warn("Unknown ext '%s'!\n", ext_name); goto bail2; } n = 0; } check_accept: #endif /* * Confirm his accept token is the one we precomputed */ p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT); if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) { lwsl_warn("lws_client_int_s_hs: accept %s wrong vs %s\n", p, wsi->u.hdr.ah->initial_handshake_hash_base64); goto bail2; } /* allocate the per-connection user memory (if any) */ if (lws_ensure_user_space(wsi)) { lwsl_err("Problem allocating wsi user mem\n"); goto bail2; } /* * we seem to be good to go, give client last chance to check * headers and OK it */ if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH, wsi->user_space, NULL, 0)) goto bail2; /* clear his proxy connection timeout */ lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); /* free up his parsing allocations */ lws_free(wsi->u.hdr.ah); lws_union_transition(wsi, LWSCM_WS_CLIENT); wsi->state = LWSS_ESTABLISHED; wsi->rxflow_change_to = LWS_RXFLOW_ALLOW; /* * create the frame buffer for this connection according to the * size mentioned in the protocol definition. If 0 there, then * 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); goto bail2; } lwsl_info("Allocating client RX buffer %d\n", n); if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF, (const char *)&n, sizeof n)) { lwsl_warn("Failed to set SNDBUF to %d", n); goto bail3; } lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name); /* call him back to inform him he is up */ if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED, wsi->user_space, NULL, 0)) goto bail3; #ifndef LWS_NO_EXTENSIONS /* * inform all extensions, not just active ones since they * already know */ ext = context->extensions; while (ext && ext->callback) { v = NULL; for (n = 0; n < wsi->count_active_extensions; n++) if (wsi->active_extensions[n] == ext) v = wsi->active_extensions_user[n]; ext->callback(context, ext, wsi, LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0); ext++; } #endif return 0; bail3: lws_free_set_NULL(wsi->u.ws.rx_user_buffer); close_reason = LWS_CLOSE_STATUS_NOSTATUS; bail2: if (wsi->protocol) { if (isErrorCodeReceived && p) { wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, p, (unsigned int)strlen(p)); } else { wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, NULL, 0); } } lwsl_info("closing connection due to bail2 connection error\n"); /* free up his parsing allocations */ lws_free_set_NULL(wsi->u.hdr.ah); lws_close_free_wsi(wsi, close_reason); 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 && interface_to_sa(context, info->iface, (struct sockaddr_in *)v, n) < 0) { lwsl_err("Unable to find interface %s\n", info->iface); goto bail; } 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); goto bail; } 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"); goto bail; } wsi->context = context; wsi->sock = sockfd; wsi->mode = LWSCM_SERVER_LISTENER; wsi->protocol = context->protocols; context->wsi_listening = wsi; if (insert_wsi_socket_into_fds(context, wsi)) goto bail; context->lserv_mod = LWS_lserv_mod; context->lserv_count = 0; context->lserv_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; bail: compatible_close(sockfd); return 1; } int _lws_server_listen_accept_flow_control(struct lws_context *context, int on) { struct lws *wsi = context->wsi_listening; int n; if (!wsi) return 0; lwsl_debug("%s: wsi %p: state %d\n", __func__, (void *)wsi, on); if (on) n = lws_change_pollfd(wsi, 0, LWS_POLLIN); else n = lws_change_pollfd(wsi, LWS_POLLIN, 0); return n; } int lws_http_action(struct lws *wsi) { enum http_connection_type connection_type; 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(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(wsi, LWS_CALLBACK_HTTP, wsi->user_space, uri_ptr, uri_len); } /* now drop the header info we kept a pointer to */ lws_free_header_table(wsi); 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 != LWSS_HTTP_ISSUING_FILE) /* Prepare to read body if we have a content length: */ if (wsi->u.http.content_length > 0) wsi->state = LWSS_HTTP_BODY; return 0; bail_nuke_ah: lws_free_header_table(wsi); return 1; } int lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len) { struct lws_context *context = lws_get_context(wsi); struct allocated_headers *ah; int protocol_len, n, hit; char protocol_list[128]; char protocol_name[32]; char *p; /* LWSCM_WS_SERVING */ while (len--) { if (lws_parse(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 = LWSCM_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, LWSCM_HTTP_SERVING_ACCEPTED); wsi->state = LWSS_HTTP; wsi->u.http.fd = LWS_INVALID_FILE; /* expose it at the same offset as u.hdr */ wsi->u.http.ah = ah; lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi, (void *)wsi->u.hdr.ah); n = lws_http_action(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, LWSCM_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 = LWSS_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 (context->protocols[n].callback) { if (context->protocols[n].name && !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)) { lwsl_err("No protocol from \"%s\" supported\n", protocol_list); goto bail_nuke_ah; } /* * 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]; } /* 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, 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, LWSCM_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_PRE; wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */); if (!wsi->u.ws.rx_ubuf) { 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->context = context; new_wsi->pending_timeout = NO_PENDING_TIMEOUT; new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW; /* intialize the instance struct */ new_wsi->state = LWSS_HTTP; new_wsi->mode = LWSCM_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(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) { lwsl_debug("%s: wsi %p\n", __func__, wsi); /* if we can't go back to accept new headers, drop the connection */ if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) { lwsl_info("%s: close connection\n", __func__); return 1; } /* otherwise set ourselves up ready to go again */ wsi->state = LWSS_HTTP; wsi->mode = LWSCM_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; }
static int callback_minimal(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { struct per_session_data__minimal *pss = (struct per_session_data__minimal *)user; struct per_vhost_data__minimal *vhd = (struct per_vhost_data__minimal *) lws_protocol_vh_priv_get(lws_get_vhost(wsi), lws_get_protocol(wsi)); const struct lws_protocol_vhost_options *pvo; const struct msg *pmsg; void *retval; int n, m, r = 0; switch (reason) { case LWS_CALLBACK_PROTOCOL_INIT: /* create our per-vhost struct */ vhd = lws_protocol_vh_priv_zalloc(lws_get_vhost(wsi), lws_get_protocol(wsi), sizeof(struct per_vhost_data__minimal)); if (!vhd) return 1; pthread_mutex_init(&vhd->lock_ring, NULL); /* recover the pointer to the globals struct */ pvo = lws_pvo_search( (const struct lws_protocol_vhost_options *)in, "config"); if (!pvo || !pvo->value) { lwsl_err("%s: Can't find \"config\" pvo\n", __func__); return 1; } vhd->config = pvo->value; vhd->context = lws_get_context(wsi); vhd->protocol = lws_get_protocol(wsi); vhd->vhost = lws_get_vhost(wsi); vhd->ring = lws_ring_create(sizeof(struct msg), 8, __minimal_destroy_message); if (!vhd->ring) { lwsl_err("%s: failed to create ring\n", __func__); return 1; } /* start the content-creating threads */ for (n = 0; n < (int)LWS_ARRAY_SIZE(vhd->pthread_spam); n++) if (pthread_create(&vhd->pthread_spam[n], NULL, thread_spam, vhd)) { lwsl_err("thread creation failed\n"); r = 1; goto init_fail; } break; case LWS_CALLBACK_PROTOCOL_DESTROY: init_fail: vhd->finished = 1; for (n = 0; n < (int)LWS_ARRAY_SIZE(vhd->pthread_spam); n++) if (vhd->pthread_spam[n]) pthread_join(vhd->pthread_spam[n], &retval); if (vhd->ring) lws_ring_destroy(vhd->ring); pthread_mutex_destroy(&vhd->lock_ring); break; case LWS_CALLBACK_ESTABLISHED: /* add ourselves to the list of live pss held in the vhd */ lws_ll_fwd_insert(pss, pss_list, vhd->pss_list); pss->tail = lws_ring_get_oldest_tail(vhd->ring); pss->wsi = wsi; break; case LWS_CALLBACK_CLOSED: /* remove our closing pss from the list of live pss */ lws_ll_fwd_remove(struct per_session_data__minimal, pss_list, pss, vhd->pss_list); break; case LWS_CALLBACK_SERVER_WRITEABLE: pthread_mutex_lock(&vhd->lock_ring); /* --------- ring lock { */ pmsg = lws_ring_get_element(vhd->ring, &pss->tail); if (!pmsg) { pthread_mutex_unlock(&vhd->lock_ring); /* } ring lock ------- */ break; } /* notice we allowed for LWS_PRE in the payload already */ m = lws_write(wsi, ((unsigned char *)pmsg->payload) + LWS_PRE, pmsg->len, LWS_WRITE_TEXT); if (m < (int)pmsg->len) { pthread_mutex_unlock(&vhd->lock_ring); /* } ring lock ------- */ lwsl_err("ERROR %d writing to ws socket\n", m); return -1; } lws_ring_consume_and_update_oldest_tail( vhd->ring, /* lws_ring object */ struct per_session_data__minimal, /* type of objects with tails */ &pss->tail, /* tail of guy doing the consuming */ 1, /* number of payload objects being consumed */ vhd->pss_list, /* head of list of objects with tails */ tail, /* member name of tail in objects with tails */ pss_list /* member name of next object in objects with tails */ ); /* more to do? */ if (lws_ring_get_element(vhd->ring, &pss->tail)) /* come back as soon as we can write more */ lws_callback_on_writable(pss->wsi); pthread_mutex_unlock(&vhd->lock_ring); /* } ring lock ------- */ break; case LWS_CALLBACK_RECEIVE: break; case LWS_CALLBACK_EVENT_WAIT_CANCELLED: /* * When the "spam" threads add a message to the ringbuffer, * they create this event in the lws service thread context * using lws_cancel_service(). * * We respond by scheduling a writable callback for all * connected clients. */ lws_start_foreach_llp(struct per_session_data__minimal **, ppss, vhd->pss_list) { lws_callback_on_writable((*ppss)->wsi); } lws_end_foreach_llp(ppss, pss_list); break; default: break; } return r; }
static int callback_acme_client(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { struct per_vhost_data__lws_acme_client *vhd = (struct per_vhost_data__lws_acme_client *) lws_protocol_vh_priv_get(lws_get_vhost(wsi), lws_get_protocol(wsi)); char buf[LWS_PRE + 2536], *start = buf + LWS_PRE, *p = start, *end = buf + sizeof(buf) - 1, digest[32], *failreason = NULL; unsigned char **pp, *pend; const char *content_type; const struct lws_protocol_vhost_options *pvo; struct lws_acme_cert_aging_args *caa; struct acme_connection *ac = NULL; struct lws_genhash_ctx hctx; struct lws *cwsi; int n, m; if (vhd) ac = vhd->ac; switch ((int)reason) { case LWS_CALLBACK_PROTOCOL_INIT: vhd = lws_protocol_vh_priv_zalloc(lws_get_vhost(wsi), lws_get_protocol(wsi), sizeof(struct per_vhost_data__lws_acme_client)); vhd->context = lws_get_context(wsi); vhd->protocol = lws_get_protocol(wsi); vhd->vhost = lws_get_vhost(wsi); /* compute how much we need to hold all the pvo payloads */ m = 0; pvo = (const struct lws_protocol_vhost_options *)in; while (pvo) { m += strlen(pvo->value) + 1; pvo = pvo->next; } p = vhd->pvo_data = malloc(m); if (!p) return -1; pvo = (const struct lws_protocol_vhost_options *)in; while (pvo) { start = p; n = strlen(pvo->value) + 1; memcpy(start, pvo->value, n); p += n; for (m = 0; m < (int)LWS_ARRAY_SIZE(pvo_names); m++) if (!strcmp(pvo->name, pvo_names[m])) vhd->pvop[m] = start; pvo = pvo->next; } n = 0; for (m = 0; m < (int)LWS_ARRAY_SIZE(pvo_names); m++) if (!vhd->pvop[m] && m >= LWS_TLS_REQ_ELEMENT_COMMON_NAME) { lwsl_notice("%s: require pvo '%s'\n", __func__, pvo_names[m]); n |= 1; } else if (vhd->pvop[m]) lwsl_info(" %s: %s\n", pvo_names[m], vhd->pvop[m]); if (n) { free(vhd->pvo_data); vhd->pvo_data = NULL; return -1; } #if !defined(LWS_WITH_ESP32) /* * load (or create) the registration keypair while we * still have root */ if (lws_acme_load_create_auth_keys(vhd, 4096)) return 1; /* * in case we do an update, open the update files while we * still have root */ lws_snprintf(buf, sizeof(buf) - 1, "%s.upd", vhd->pvop[LWS_TLS_SET_CERT_PATH]); vhd->fd_updated_cert = lws_open(buf, LWS_O_WRONLY | LWS_O_CREAT | LWS_O_TRUNC, 0600); if (vhd->fd_updated_cert < 0) { lwsl_err("unable to create update cert file %s\n", buf); return -1; } lws_snprintf(buf, sizeof(buf) - 1, "%s.upd", vhd->pvop[LWS_TLS_SET_KEY_PATH]); vhd->fd_updated_key = lws_open(buf, LWS_O_WRONLY | LWS_O_CREAT | LWS_O_TRUNC, 0600); if (vhd->fd_updated_key < 0) { lwsl_err("unable to create update key file %s\n", buf); return -1; } #endif break; case LWS_CALLBACK_PROTOCOL_DESTROY: if (vhd && vhd->pvo_data) { free(vhd->pvo_data); vhd->pvo_data = NULL; } if (vhd) lws_acme_finished(vhd); break; case LWS_CALLBACK_VHOST_CERT_AGING: if (!vhd) break; caa = (struct lws_acme_cert_aging_args *)in; /* * Somebody is telling us about a cert some vhost is using. * * First see if the cert is getting close enough to expiry that * we *want* to do something about it. */ if ((int)(ssize_t)len > 14) break; /* * ...is this a vhost we were configured on? */ if (vhd->vhost != caa->vh) return 1; for (n = 0; n < (int)LWS_ARRAY_SIZE(vhd->pvop);n++) if (caa->element_overrides[n]) vhd->pvop_active[n] = caa->element_overrides[n]; else vhd->pvop_active[n] = vhd->pvop[n]; lwsl_notice("starting acme acquisition on %s: %s\n", lws_get_vhost_name(caa->vh), vhd->pvop_active[LWS_TLS_SET_DIR_URL]); lws_acme_start_acquisition(vhd, caa->vh); break; /* * Client */ case LWS_CALLBACK_CLIENT_ESTABLISHED: lwsl_notice("%s: CLIENT_ESTABLISHED\n", __func__); break; case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: lwsl_notice("%s: CLIENT_CONNECTION_ERROR: %p\n", __func__, wsi); break; case LWS_CALLBACK_CLOSED_CLIENT_HTTP: lwsl_notice("%s: CLOSED_CLIENT_HTTP: %p\n", __func__, wsi); break; case LWS_CALLBACK_CLOSED: lwsl_notice("%s: CLOSED: %p\n", __func__, wsi); break; case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: lwsl_notice("lws_http_client_http_response %d\n", lws_http_client_http_response(wsi)); if (!ac) break; ac->resp = lws_http_client_http_response(wsi); /* we get a new nonce each time */ if (lws_hdr_total_length(wsi, WSI_TOKEN_REPLAY_NONCE) && lws_hdr_copy(wsi, ac->replay_nonce, sizeof(ac->replay_nonce), WSI_TOKEN_REPLAY_NONCE) < 0) { lwsl_notice("%s: nonce too large\n", __func__); goto failed; } switch (ac->state) { case ACME_STATE_DIRECTORY: lejp_construct(&ac->jctx, cb_dir, vhd, jdir_tok, LWS_ARRAY_SIZE(jdir_tok)); break; case ACME_STATE_NEW_REG: break; case ACME_STATE_NEW_AUTH: lejp_construct(&ac->jctx, cb_authz, ac, jauthz_tok, LWS_ARRAY_SIZE(jauthz_tok)); break; case ACME_STATE_POLLING: case ACME_STATE_ACCEPT_CHALL: lejp_construct(&ac->jctx, cb_chac, ac, jchac_tok, LWS_ARRAY_SIZE(jchac_tok)); break; case ACME_STATE_POLLING_CSR: ac->cpos = 0; if (ac->resp != 201) break; /* * He acknowledges he will create the cert... * get the URL to GET it from in the Location * header. */ if (lws_hdr_copy(wsi, ac->challenge_uri, sizeof(ac->challenge_uri), WSI_TOKEN_HTTP_LOCATION) < 0) { lwsl_notice("%s: missing cert location:\n", __func__); goto failed; } lwsl_notice("told to fetch cert from %s\n", ac->challenge_uri); break; default: break; } break; case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER: if (!ac) break; switch (ac->state) { case ACME_STATE_DIRECTORY: break; case ACME_STATE_NEW_REG: p += lws_snprintf(p, end - p, "{" "\"resource\":\"new-reg\"," "\"contact\":[" "\"mailto:%s\"" "],\"agreement\":\"%s\"" "}", vhd->pvop_active[LWS_TLS_REQ_ELEMENT_EMAIL], ac->urls[JAD_TOS_URL]); puts(start); pkt_add_hdrs: ac->len = lws_jws_create_packet(&vhd->jwk, start, p - start, ac->replay_nonce, &ac->buf[LWS_PRE], sizeof(ac->buf) - LWS_PRE); if (ac->len < 0) { ac->len = 0; lwsl_notice("lws_jws_create_packet failed\n"); goto failed; } pp = (unsigned char **)in; pend = (*pp) + len; ac->pos = 0; content_type = "application/jose+json"; if (ac->state == ACME_STATE_POLLING_CSR) content_type = "application/pkix-cert"; if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE, (uint8_t *)content_type, 21, pp, pend)) { lwsl_notice("could not add content type\n"); goto failed; } n = sprintf(buf, "%d", ac->len); if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH, (uint8_t *)buf, n, pp, pend)) { lwsl_notice("could not add content length\n"); goto failed; } lws_client_http_body_pending(wsi, 1); lws_callback_on_writable(wsi); lwsl_notice("prepare to send ACME_STATE_NEW_REG\n"); break; case ACME_STATE_NEW_AUTH: p += lws_snprintf(p, end - p, "{" "\"resource\":\"new-authz\"," "\"identifier\":{" "\"type\":\"http-01\"," "\"value\":\"%s\"" "}" "}", vhd->pvop_active[LWS_TLS_REQ_ELEMENT_COMMON_NAME]); goto pkt_add_hdrs; case ACME_STATE_ACCEPT_CHALL: /* * Several of the challenges in this document makes use * of a key authorization string. A key authorization * expresses a domain holder's authorization for a * specified key to satisfy a specified challenge, by * concatenating the token for the challenge with a key * fingerprint, separated by a "." character: * * key-authz = token || '.' || * base64(JWK_Thumbprint(accountKey)) * * The "JWK_Thumbprint" step indicates the computation * specified in [RFC7638], using the SHA-256 digest. As * specified in the individual challenges below, the * token for a challenge is a JSON string comprised * entirely of characters in the base64 alphabet. * The "||" operator indicates concatenation of strings. * * keyAuthorization (required, string): The key * authorization for this challenge. This value MUST * match the token from the challenge and the client's * account key. * * draft acme-01 tls-sni-01: * * { * "keyAuthorization": "evaGxfADs...62jcerQ", * } (Signed as JWS) * * draft acme-07 tls-sni-02: * * POST /acme/authz/1234/1 * Host: example.com * Content-Type: application/jose+json * * { * "protected": base64url({ * "alg": "ES256", * "kid": "https://example.com/acme/acct/1", * "nonce": "JHb54aT_KTXBWQOzGYkt9A", * "url": "https://example.com/acme/authz/1234/1" * }), * "payload": base64url({ * "keyAuthorization": "evaGxfADs...62jcerQ" * }), * "signature": "Q1bURgJoEslbD1c5...3pYdSMLio57mQNN4" * } * * On receiving a response, the server MUST verify that * the key authorization in the response matches the * "token" value in the challenge and the client's * account key. If they do not match, then the server * MUST return an HTTP error in response to the POST * request in which the client sent the challenge. */ lws_jwk_rfc7638_fingerprint(&vhd->jwk, digest); p = start; end = &buf[sizeof(buf) - 1]; p += lws_snprintf(p, end - p, "{\"resource\":\"challenge\"," "\"type\":\"tls-sni-0%d\"," "\"keyAuthorization\":\"%s.", 1 + ac->is_sni_02, ac->chall_token); n = lws_jws_base64_enc(digest, 32, p, end - p); if (n < 0) goto failed; p += n; p += lws_snprintf(p, end - p, "\"}"); puts(start); goto pkt_add_hdrs; case ACME_STATE_POLLING: break; case ACME_STATE_POLLING_CSR: /* * "To obtain a certificate for the domain, the agent * constructs a PKCS#10 Certificate Signing Request that * asks the Let’s Encrypt CA to issue a certificate for * example.com with a specified public key. As usual, * the CSR includes a signature by the private key * corresponding to the public key in the CSR. The agent * also signs the whole CSR with the authorized * key for example.com so that the Let’s Encrypt CA * knows it’s authorized." * * IOW we must create a new RSA keypair which will be * the cert public + private key, and put the public * key in the CSR. The CSR, just for transport, is also * signed with our JWK, showing that as the owner of the * authorized JWK, the request should be allowed. * * The cert comes back with our public key in it showing * that the owner of the matching private key (we * created that keypair) is the owner of the cert. * * We feed the CSR the elements we want in the cert, * like the CN etc, and it gives us the b64URL-encoded * CSR and the PEM-encoded (public +)private key in * memory buffers. */ if (ac->goes_around) break; p += lws_snprintf(p, end - p, "{\"resource\":\"new-cert\"," "\"csr\":\""); n = lws_tls_acme_sni_csr_create(vhd->context, &vhd->pvop_active[0], (uint8_t *)p, end - p, &ac->alloc_privkey_pem, &ac->len_privkey_pem); if (n < 0) { lwsl_notice("CSR generation failed\n"); goto failed; } p += n; p += lws_snprintf(p, end - p, "\"}"); puts(start); goto pkt_add_hdrs; default: break; } break; case LWS_CALLBACK_CLIENT_HTTP_WRITEABLE: lwsl_notice("LWS_CALLBACK_CLIENT_HTTP_WRITEABLE\n"); if (!ac) break; if (ac->pos == ac->len) break; ac->buf[LWS_PRE + ac->len] = '\0'; if (lws_write(wsi, (uint8_t *)ac->buf + LWS_PRE, ac->len, LWS_WRITE_HTTP_FINAL) < 0) return -1; lwsl_notice("wrote %d\n", ac->len); ac->pos = ac->len; lws_client_http_body_pending(wsi, 0); break; /* chunked content */ case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ: if (!ac) return -1; switch (ac->state) { case ACME_STATE_POLLING: case ACME_STATE_ACCEPT_CHALL: case ACME_STATE_NEW_AUTH: case ACME_STATE_DIRECTORY: ((char *)in)[len] = '\0'; puts(in); m = (int)(signed char)lejp_parse(&ac->jctx, (uint8_t *)in, len); if (m < 0 && m != LEJP_CONTINUE) { lwsl_notice("lejp parse failed %d\n", m); goto failed; } break; case ACME_STATE_NEW_REG: ((char *)in)[len] = '\0'; puts(in); break; case ACME_STATE_POLLING_CSR: /* it should be the DER cert! */ if (ac->cpos + len > sizeof(ac->buf)) { lwsl_notice("Incoming cert is too large!\n"); goto failed; } memcpy(&ac->buf[ac->cpos], in, len); ac->cpos += len; break; default: break; } break; /* unchunked content */ case LWS_CALLBACK_RECEIVE_CLIENT_HTTP: lwsl_notice("%s: LWS_CALLBACK_RECEIVE_CLIENT_HTTP\n", __func__); { char buffer[2048 + LWS_PRE]; char *px = buffer + LWS_PRE; int lenx = sizeof(buffer) - LWS_PRE; if (lws_http_client_read(wsi, &px, &lenx) < 0) return -1; } break; case LWS_CALLBACK_COMPLETED_CLIENT_HTTP: lwsl_notice("%s: COMPLETED_CLIENT_HTTP\n", __func__); if (!ac) return -1; switch (ac->state) { case ACME_STATE_DIRECTORY: lejp_destruct(&ac->jctx); /* check dir validity */ for (n = 0; n < 6; n++) lwsl_notice(" %d: %s\n", n, ac->urls[n]); /* * So... having the directory now... we try to * register our keys next. It's OK if it ends up * they're already registered... this eliminates any * gaps where we stored the key but registration did * not complete for some reason... */ ac->state = ACME_STATE_NEW_REG; lws_acme_report_status(vhd->vhost, LWS_CUS_REG, NULL); strcpy(buf, ac->urls[JAD_NEW_REG_URL]); cwsi = lws_acme_client_connect(vhd->context, vhd->vhost, &ac->cwsi, &ac->i, buf, "POST"); if (!cwsi) { lwsl_notice("%s: failed to connect to acme\n", __func__); goto failed; } return -1; /* close the completed client connection */ case ACME_STATE_NEW_REG: if ((ac->resp >= 200 && ac->resp < 299) || ac->resp == 409) { /* * Our account already existed, or exists now. * * Move on to requesting a cert auth. */ ac->state = ACME_STATE_NEW_AUTH; lws_acme_report_status(vhd->vhost, LWS_CUS_AUTH, NULL); strcpy(buf, ac->urls[JAD_NEW_AUTHZ_URL]); cwsi = lws_acme_client_connect(vhd->context, vhd->vhost, &ac->cwsi, &ac->i, buf, "POST"); if (!cwsi) lwsl_notice("%s: failed to connect\n", __func__); return -1; /* close the completed client connection */ } else { lwsl_notice("new-reg replied %d\n", ac->resp); goto failed; } return -1; /* close the completed client connection */ case ACME_STATE_NEW_AUTH: lejp_destruct(&ac->jctx); if (ac->resp / 100 == 4) { lws_snprintf(buf, sizeof(buf), "Auth failed: %s", ac->detail); failreason = buf; lwsl_notice("auth failed\n"); goto failed; } lwsl_notice("chall: %s (%d)\n", ac->chall_token, ac->resp); if (!ac->chall_token[0]) { lwsl_notice("no challenge\n"); goto failed; } ac->state = ACME_STATE_ACCEPT_CHALL; lws_acme_report_status(vhd->vhost, LWS_CUS_CHALLENGE, NULL); /* tls-sni-01 ... what a mess. * The stuff in * https://tools.ietf.org/html/ * draft-ietf-acme-acme-01#section-7.3 * "requires" n but it's missing from let's encrypt * tls-sni-01 challenge. The go docs say that they just * implement one hashing round regardless * https://godoc.org/golang.org/x/crypto/acme * * The go way is what is actually implemented today by * letsencrypt * * "A client responds to this challenge by constructing * a key authorization from the "token" value provided * in the challenge and the client's account key. The * client first computes the SHA-256 digest Z0 of the * UTF8-encoded key authorization, and encodes Z0 in * UTF-8 lower-case hexadecimal form." */ /* tls-sni-02 * * SAN A MUST be constructed as follows: compute the * SHA-256 digest of the UTF-8-encoded challenge token * and encode it in lowercase hexadecimal form. The * dNSName is "x.y.token.acme.invalid", where x * is the first half of the hexadecimal representation * and y is the second half. */ memset(&ac->ci, 0, sizeof(ac->ci)); /* first compute the key authorization */ lws_jwk_rfc7638_fingerprint(&vhd->jwk, digest); p = start; end = &buf[sizeof(buf) - 1]; p += lws_snprintf(p, end - p, "%s.", ac->chall_token); n = lws_jws_base64_enc(digest, 32, p, end - p); if (n < 0) goto failed; p += n; if (lws_genhash_init(&hctx, LWS_GENHASH_TYPE_SHA256)) return -1; if (lws_genhash_update(&hctx, (uint8_t *)start, lws_ptr_diff(p, start))) { lws_genhash_destroy(&hctx, NULL); return -1; } if (lws_genhash_destroy(&hctx, digest)) return -1; p = buf; for (n = 0; n < 32; n++) { p += lws_snprintf(p, end - p, "%02x", digest[n] & 0xff); if (n == (32 / 2) - 1) p = buf + 64; } p = ac->san_a; if (ac->is_sni_02) { lws_snprintf(p, sizeof(ac->san_a), "%s.%s.token.acme.invalid", buf, buf + 64); /* * SAN B MUST be constructed as follows: compute * the SHA-256 digest of the UTF-8 encoded key * authorization and encode it in lowercase * hexadecimal form. The dNSName is * "x.y.ka.acme.invalid" where x is the first * half of the hexadecimal representation and y * is the second half. */ lws_jwk_rfc7638_fingerprint(&vhd->jwk, (char *)digest); p = buf; for (n = 0; n < 32; n++) { p += lws_snprintf(p, end - p, "%02x", digest[n] & 0xff); if (n == (32 / 2) - 1) p = buf + 64; } p = ac->san_b; lws_snprintf(p, sizeof(ac->san_b), "%s.%s.ka.acme.invalid", buf, buf + 64); } else { lws_snprintf(p, sizeof(ac->san_a), "%s.%s.acme.invalid", buf, buf + 64); ac->san_b[0] = '\0'; } lwsl_notice("san_a: '%s'\n", ac->san_a); lwsl_notice("san_b: '%s'\n", ac->san_b); /* * tls-sni-01: * * The client then configures the TLS server at the * domain such that when a handshake is initiated with * the Server Name Indication extension set to * "<Zi[0:32]>.<Zi[32:64]>.acme.invalid", the * corresponding generated certificate is presented. * * tls-sni-02: * * The client MUST ensure that the certificate is * served to TLS connections specifying a Server Name * Indication (SNI) value of SAN A. */ ac->ci.vhost_name = ac->san_a; /* * we bind to exact iface of real vhost, so we can * share the listen socket by SNI */ ac->ci.iface = ac->real_vh_iface; /* listen on the same port as the vhost that triggered * us */ ac->ci.port = ac->real_vh_port; /* Skip filling in any x509 info into the ssl_ctx. * It will be done at the callback * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS * in this callback handler (below) */ ac->ci.options = LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX | LWS_SERVER_OPTION_SKIP_PROTOCOL_INIT | LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; /* make ourselves protocols[0] for the new vhost */ ac->ci.protocols = acme_protocols; /* * vhost .user points to the ac associated with the * temporary vhost */ ac->ci.user = ac; ac->vhost = lws_create_vhost(lws_get_context(wsi), &ac->ci); if (!ac->vhost) goto failed; /* * The challenge-specific vhost is up... let the ACME * server know we are ready to roll... */ ac->goes_around = 0; cwsi = lws_acme_client_connect(vhd->context, vhd->vhost, &ac->cwsi, &ac->i, ac->challenge_uri, "POST"); if (!cwsi) { lwsl_notice("%s: failed to connect\n", __func__); goto failed; } return -1; /* close the completed client connection */ case ACME_STATE_ACCEPT_CHALL: /* * he returned something like this (which we parsed) * * { * "type": "tls-sni-01", * "status": "pending", * "uri": "https://acme-staging.api.letsencrypt.org/ * acme/challenge/xCt7bT3FaxoIQU3Qry87t5h * uKDcC-L-0ERcD5DLAZts/71100507", * "token": "j2Vs-vLI_dsza4A35SFHIU03aIe2PzFRijbqCY * dIVeE", * "keyAuthorization": "j2Vs-vLI_dsza4A35SFHIU03aIe2 * PzFRijbqCYdIVeE.nmOtdFd8Jikn6K8NnYYmT5 * vCM_PwSDT8nLdOYoFXhRU" * } * */ lwsl_notice("%s: COMPLETED accept chall: %s\n", __func__, ac->challenge_uri); poll_again: ac->state = ACME_STATE_POLLING; lws_acme_report_status(vhd->vhost, LWS_CUS_CHALLENGE, NULL); if (ac->goes_around++ == 20) { lwsl_notice("%s: too many chall retries\n", __func__); goto failed; } lws_timed_callback_vh_protocol(vhd->vhost, vhd->protocol, LWS_CALLBACK_USER + 0xac33, ac->goes_around == 1 ? 10 : 2); return -1; /* close the completed client connection */ case ACME_STATE_POLLING: if (ac->resp == 202 && strcmp(ac->status, "invalid") && strcmp(ac->status, "valid")) { lwsl_notice("status: %s\n", ac->status); goto poll_again; } if (!strcmp(ac->status, "invalid")) { lwsl_notice("%s: polling failed\n", __func__); lws_snprintf(buf, sizeof(buf), "Challenge Invalid: %s", ac->detail); failreason = buf; goto failed; } lwsl_notice("Challenge passed\n"); /* * The challenge was validated... so delete the * temp SNI vhost now its job is done */ if (ac->vhost) lws_vhost_destroy(ac->vhost); ac->vhost = NULL; /* * now our JWK is accepted as authorized to make * requests for the domain, next move is create the * CSR signed with the JWK, and send it to the ACME * server to request the actual certs. */ ac->state = ACME_STATE_POLLING_CSR; lws_acme_report_status(vhd->vhost, LWS_CUS_REQ, NULL); ac->goes_around = 0; strcpy(buf, ac->urls[JAD_NEW_CERT_URL]); cwsi = lws_acme_client_connect(vhd->context, vhd->vhost, &ac->cwsi, &ac->i, buf, "POST"); if (!cwsi) { lwsl_notice("%s: failed to connect to acme\n", __func__); goto failed; } return -1; /* close the completed client connection */ case ACME_STATE_POLLING_CSR: /* * (after POSTing the CSR)... * * If the CA decides to issue a certificate, then the * server creates a new certificate resource and * returns a URI for it in the Location header field * of a 201 (Created) response. * * HTTP/1.1 201 Created * Location: https://example.com/acme/cert/asdf * * If the certificate is available at the time of the * response, it is provided in the body of the response. * If the CA has not yet issued the certificate, the * body of this response will be empty. The client * should then send a GET request to the certificate URI * to poll for the certificate. As long as the * certificate is unavailable, the server MUST provide a * 202 (Accepted) response and include a Retry-After * header to indicate when the server believes the * certificate will be issued. */ if (ac->resp < 200 || ac->resp > 202) { lwsl_notice("CSR poll failed on resp %d\n", ac->resp); goto failed; } if (ac->resp == 200) { char *pp; int max; lwsl_notice("The cert was sent..\n"); lws_acme_report_status(vhd->vhost, LWS_CUS_ISSUE, NULL); /* * That means we have the issued cert DER in * ac->buf, length in ac->cpos; and the key in * ac->alloc_privkey_pem, length in * ac->len_privkey_pem. * * We write out a PEM copy of the cert, and a * PEM copy of the private key, using the * write-only fds we opened while we still * had root. * * Estimate the size of the PEM version of the * cert and allocate a temp buffer for it. * * This is a bit complicated because first we * drop the b64url version into the buffer at * +384, then we add the header at 0 and move * lines of it back + '\n' to make PEM. * * This avoids the need for two fullsize * allocations. */ max = (ac->cpos * 4) / 3 + 16 + 384; start = p = malloc(max); if (!p) goto failed; n = lws_b64_encode_string(ac->buf, ac->cpos, start + 384, max - 384); if (n < 0) { free(start); goto failed; } pp = start + 384; p += lws_snprintf(start, 64, "%s", "-----BEGIN CERTIFICATE-----\n"); while (n) { m = 65; if (n < m) m = n; memcpy(p, pp, m); n -= m; p += m; pp += m; if (n) *p++ = '\n'; } p += lws_snprintf(p, max - lws_ptr_diff(p, start), "%s", "\n-----END CERTIFICATE-----\n"); n = lws_plat_write_cert(vhd->vhost, 0, vhd->fd_updated_cert, start, lws_ptr_diff(p, start)); free(start); if (n) { lwsl_err("unable to write ACME cert! %d\n", n); goto failed; } /* * don't close it... we may update the certs * again */ if (lws_plat_write_cert(vhd->vhost, 1, vhd->fd_updated_key, ac->alloc_privkey_pem, ac->len_privkey_pem)) { lwsl_err("unable to write ACME key!\n"); goto failed; } /* * we have written the persistent copies */ lwsl_notice("%s: Updated certs written for %s " "to %s.upd and %s.upd\n", __func__, vhd->pvop_active[LWS_TLS_REQ_ELEMENT_COMMON_NAME], vhd->pvop_active[LWS_TLS_SET_CERT_PATH], vhd->pvop_active[LWS_TLS_SET_KEY_PATH]); /* notify lws there was a cert update */ if (lws_tls_cert_updated(vhd->context, vhd->pvop_active[LWS_TLS_SET_CERT_PATH], vhd->pvop_active[LWS_TLS_SET_KEY_PATH], ac->buf, ac->cpos, ac->alloc_privkey_pem, ac->len_privkey_pem)) { lwsl_notice("problem setting certs\n"); } lws_acme_finished(vhd); lws_acme_report_status(vhd->vhost, LWS_CUS_SUCCESS, NULL); return 0; } lws_acme_report_status(vhd->vhost, LWS_CUS_CONFIRM, NULL); /* he is preparing the cert, go again with a GET */ if (ac->goes_around++ == 30) { lwsl_notice("%s: too many retries\n", __func__); goto failed; } strcpy(buf, ac->challenge_uri); cwsi = lws_acme_client_connect(vhd->context, vhd->vhost, &ac->cwsi, &ac->i, buf, "GET"); if (!cwsi) { lwsl_notice("%s: failed to connect to acme\n", __func__); goto failed; } return -1; /* close the completed client connection */ default: break; } break; case LWS_CALLBACK_USER + 0xac33: if (!vhd) break; cwsi = lws_acme_client_connect(vhd->context, vhd->vhost, &ac->cwsi, &ac->i, ac->challenge_uri, "GET"); if (!cwsi) { lwsl_notice("%s: failed to connect\n", __func__); goto failed; } break; case LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS: /* * This goes to vhost->protocols[0], but for our temp certs * vhost we created, we have arranged that to be our protocol, * so the callback will come here. * * When we created the temp vhost, we set its pvo to point * to the ac associated with the temp vhost. */ lwsl_debug("LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS\n"); ac = (struct acme_connection *)lws_get_vhost_user( (struct lws_vhost *)in); lws_acme_report_status((struct lws_vhost *)in, LWS_CUS_CREATE_REQ, "creating challenge cert"); if (lws_tls_acme_sni_cert_create((struct lws_vhost *)in, ac->san_a, ac->san_b)) { lwsl_err("%s: creating the sni test cert failed\n", __func__); return -1; } break; default: break; } return 0; failed: lwsl_err("%s: failed out\n", __func__); lws_acme_report_status(vhd->vhost, LWS_CUS_FAILED, failreason); lws_acme_finished(vhd); return -1; }
static int callback_lws_mirror(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { struct per_session_data__lws_mirror *pss = (struct per_session_data__lws_mirror *)user; struct per_vhost_data__lws_mirror *v = (struct per_vhost_data__lws_mirror *) lws_protocol_vh_priv_get(lws_get_vhost(wsi), lws_get_protocol(wsi)); int n, m; switch (reason) { case LWS_CALLBACK_ESTABLISHED: lwsl_info("%s: LWS_CALLBACK_ESTABLISHED\n", __func__); pss->ringbuffer_tail = v->ringbuffer_head; pss->wsi = wsi; break; case LWS_CALLBACK_PROTOCOL_INIT: /* per vhost */ lws_protocol_vh_priv_zalloc(lws_get_vhost(wsi), lws_get_protocol(wsi), sizeof(struct per_vhost_data__lws_mirror)); break; case LWS_CALLBACK_PROTOCOL_DESTROY: /* per vhost */ if (!v) break; lwsl_info("%s: mirror protocol cleaning up %p\n", __func__, v); for (n = 0; n < ARRAY_SIZE(v->ringbuffer); n++) if (v->ringbuffer[n].payload) { free(v->ringbuffer[n].payload); v->ringbuffer[n].payload = NULL; } break; case LWS_CALLBACK_SERVER_WRITEABLE: while (pss->ringbuffer_tail != v->ringbuffer_head) { m = v->ringbuffer[pss->ringbuffer_tail].len; n = lws_write(wsi, (unsigned char *) v->ringbuffer[pss->ringbuffer_tail].payload + LWS_PRE, m, LWS_WRITE_TEXT); if (n < 0) { lwsl_err("ERROR %d writing to mirror socket\n", n); return -1; } if (n < m) lwsl_err("mirror partial write %d vs %d\n", n, m); if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1)) pss->ringbuffer_tail = 0; else pss->ringbuffer_tail++; if (((v->ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 15)) lws_rx_flow_allow_all_protocol(lws_get_context(wsi), lws_get_protocol(wsi)); if (lws_send_pipe_choked(wsi)) { lws_callback_on_writable(wsi); break; } } break; case LWS_CALLBACK_RECEIVE: if (((v->ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 1)) { lwsl_err("dropping!\n"); goto choke; } if (v->ringbuffer[v->ringbuffer_head].payload) free(v->ringbuffer[v->ringbuffer_head].payload); v->ringbuffer[v->ringbuffer_head].payload = malloc(LWS_PRE + len); v->ringbuffer[v->ringbuffer_head].len = len; memcpy((char *)v->ringbuffer[v->ringbuffer_head].payload + LWS_PRE, in, len); if (v->ringbuffer_head == (MAX_MESSAGE_QUEUE - 1)) v->ringbuffer_head = 0; else v->ringbuffer_head++; if (((v->ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1)) != (MAX_MESSAGE_QUEUE - 2)) goto done; choke: lwsl_debug("LWS_CALLBACK_RECEIVE: throttling %p\n", wsi); lws_rx_flow_control(wsi, 0); done: lws_callback_on_writable_all_protocol(lws_get_context(wsi), lws_get_protocol(wsi)); break; default: break; } return 0; }
static int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { switch (reason) { /* because we are protocols[0] ... */ case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: lwsl_err("CLIENT_CONNECTION_ERROR: %s\n", in ? (char *)in : "(null)"); client_wsi = NULL; break; case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: status = lws_http_client_http_response(wsi); lwsl_user("Connected with server response: %d\n", status); break; /* chunks of chunked content, with header removed */ case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ: lwsl_user("RECEIVE_CLIENT_HTTP_READ: read %d\n", (int)len); #if 0 /* enable to dump the html */ { const char *p = in; while (len--) if (*p < 0x7f) putchar(*p++); else putchar('.'); } #endif return 0; /* don't passthru */ /* uninterpreted http content */ case LWS_CALLBACK_RECEIVE_CLIENT_HTTP: { char buffer[1024 + LWS_PRE]; char *px = buffer + LWS_PRE; int lenx = sizeof(buffer) - LWS_PRE; if (lws_http_client_read(wsi, &px, &lenx) < 0) return -1; } return 0; /* don't passthru */ case LWS_CALLBACK_COMPLETED_CLIENT_HTTP: lwsl_user("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n"); client_wsi = NULL; bad = status != 200; lws_cancel_service(lws_get_context(wsi)); /* abort poll wait */ break; case LWS_CALLBACK_CLOSED_CLIENT_HTTP: client_wsi = NULL; bad = status != 200; lws_cancel_service(lws_get_context(wsi)); /* abort poll wait */ break; default: break; } return lws_callback_http_dummy(wsi, reason, user, in, len); }