blob: ebd54ba5ce136df2d10c304bf0c952ce0392233d [file] [log] [blame]
Andy Green58eaa742011-03-07 17:54:06 +00001/*
Andy Greena0da8a82010-11-08 17:12:19 +00002 * libwebsockets - small server side websockets and web server implementation
Andy Green8f037e42010-12-19 22:13:26 +00003 *
Andy Greena0da8a82010-11-08 17:12:19 +00004 * Copyright (C) 2010 Andy Green <andy@warmcat.com>
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 * MA 02110-1301 USA
Andy Green05a0a7b2010-10-31 17:51:39 +000020 */
21
Andy Green7c212cc2010-11-08 20:20:42 +000022#include "private-libwebsockets.h"
Andy Greenff95d7a2010-10-28 22:36:01 +010023
Peter Hinz56885f32011-03-02 22:03:47 +000024#ifdef WIN32
25
26#else
27#include <ifaddrs.h>
Andy Green7627af52011-03-09 15:13:52 +000028#include <sys/un.h>
Peter Hinz56885f32011-03-02 22:03:47 +000029#endif
Andy Green2e24da02011-03-05 16:12:04 +000030
31#ifdef LWS_OPENSSL_SUPPORT
32int openssl_websocket_private_data_index;
33#endif
34
Andy Greenbe93fef2011-02-14 20:25:43 +000035/*
36 * In-place str to lower case
37 */
38
39static void
40strtolower(char *s)
41{
42 while (*s) {
43 *s = tolower(*s);
44 s++;
45 }
46}
47
Andy Green0d338332011-02-12 11:57:43 +000048/* file descriptor hash management */
49
50struct libwebsocket *
Peter Hinz56885f32011-03-02 22:03:47 +000051wsi_from_fd(struct libwebsocket_context *context, int fd)
Andy Green0d338332011-02-12 11:57:43 +000052{
53 int h = LWS_FD_HASH(fd);
54 int n = 0;
55
Peter Hinz56885f32011-03-02 22:03:47 +000056 for (n = 0; n < context->fd_hashtable[h].length; n++)
57 if (context->fd_hashtable[h].wsi[n]->sock == fd)
58 return context->fd_hashtable[h].wsi[n];
Andy Green0d338332011-02-12 11:57:43 +000059
60 return NULL;
61}
62
63int
Peter Hinz56885f32011-03-02 22:03:47 +000064insert_wsi(struct libwebsocket_context *context, struct libwebsocket *wsi)
Andy Green0d338332011-02-12 11:57:43 +000065{
66 int h = LWS_FD_HASH(wsi->sock);
67
Peter Hinz56885f32011-03-02 22:03:47 +000068 if (context->fd_hashtable[h].length == MAX_CLIENTS - 1) {
Andy Green0d338332011-02-12 11:57:43 +000069 fprintf(stderr, "hash table overflow\n");
70 return 1;
71 }
72
Peter Hinz56885f32011-03-02 22:03:47 +000073 context->fd_hashtable[h].wsi[context->fd_hashtable[h].length++] = wsi;
Andy Green0d338332011-02-12 11:57:43 +000074
75 return 0;
76}
77
78int
Peter Hinz56885f32011-03-02 22:03:47 +000079delete_from_fd(struct libwebsocket_context *context, int fd)
Andy Green0d338332011-02-12 11:57:43 +000080{
81 int h = LWS_FD_HASH(fd);
82 int n = 0;
83
Peter Hinz56885f32011-03-02 22:03:47 +000084 for (n = 0; n < context->fd_hashtable[h].length; n++)
85 if (context->fd_hashtable[h].wsi[n]->sock == fd) {
86 while (n < context->fd_hashtable[h].length) {
87 context->fd_hashtable[h].wsi[n] =
88 context->fd_hashtable[h].wsi[n + 1];
Andy Green0d338332011-02-12 11:57:43 +000089 n++;
90 }
Peter Hinz56885f32011-03-02 22:03:47 +000091 context->fd_hashtable[h].length--;
Andy Green0d338332011-02-12 11:57:43 +000092
93 return 0;
94 }
95
96 fprintf(stderr, "Failed to find fd %d requested for "
97 "delete in hashtable\n", fd);
98 return 1;
99}
100
Andy Green1f9bf522011-02-14 21:14:37 +0000101#ifdef LWS_OPENSSL_SUPPORT
102static void
103libwebsockets_decode_ssl_error(void)
104{
105 char buf[256];
106 u_long err;
107
108 while ((err = ERR_get_error()) != 0) {
109 ERR_error_string_n(err, buf, sizeof(buf));
110 fprintf(stderr, "*** %s\n", buf);
111 }
112}
113#endif
Andy Green0d338332011-02-12 11:57:43 +0000114
Andy Green32375b72011-02-19 08:32:53 +0000115
116static int
Andy Green6ee372f2012-04-09 15:09:01 +0800117interface_to_sa(const char *ifname, struct sockaddr_in *addr, size_t addrlen)
Andy Green32375b72011-02-19 08:32:53 +0000118{
119 int rc = -1;
Peter Hinz56885f32011-03-02 22:03:47 +0000120#ifdef WIN32
Andy Green6ee372f2012-04-09 15:09:01 +0800121 /* TODO */
Peter Hinz56885f32011-03-02 22:03:47 +0000122#else
Andy Green32375b72011-02-19 08:32:53 +0000123 struct ifaddrs *ifr;
124 struct ifaddrs *ifc;
125 struct sockaddr_in *sin;
126
127 getifaddrs(&ifr);
128 for (ifc = ifr; ifc != NULL; ifc = ifc->ifa_next) {
129 if (strcmp(ifc->ifa_name, ifname))
130 continue;
131 if (ifc->ifa_addr == NULL)
132 continue;
133 sin = (struct sockaddr_in *)ifc->ifa_addr;
134 if (sin->sin_family != AF_INET)
135 continue;
136 memcpy(addr, sin, addrlen);
Andy Green6ee372f2012-04-09 15:09:01 +0800137 rc = 0;
Andy Green32375b72011-02-19 08:32:53 +0000138 }
139
140 freeifaddrs(ifr);
Peter Hinz56885f32011-03-02 22:03:47 +0000141#endif
Andy Green32375b72011-02-19 08:32:53 +0000142 return rc;
143}
144
Andy Green8f037e42010-12-19 22:13:26 +0000145void
Peter Hinz56885f32011-03-02 22:03:47 +0000146libwebsocket_close_and_free_session(struct libwebsocket_context *context,
Andy Green687b0182011-02-26 11:04:01 +0000147 struct libwebsocket *wsi, enum lws_close_status reason)
Andy Green251f6fa2010-11-03 11:13:06 +0000148{
Andy Greenb45993c2010-12-18 15:13:50 +0000149 int n;
Andy Green62c54d22011-02-14 09:14:25 +0000150 int old_state;
Andy Green5e1fa172011-02-10 09:07:05 +0000151 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
152 LWS_SEND_BUFFER_POST_PADDING];
Andy Greenc44159f2011-03-07 07:08:18 +0000153 int ret;
154 int m;
155 struct lws_tokens eff_buf;
Andy Greena41314f2011-05-23 10:00:03 +0100156 struct libwebsocket_extension *ext;
Andy Greenb45993c2010-12-18 15:13:50 +0000157
Andy Green4b6fbe12011-02-14 08:03:48 +0000158 if (!wsi)
Andy Greenb45993c2010-12-18 15:13:50 +0000159 return;
160
Andy Green62c54d22011-02-14 09:14:25 +0000161 old_state = wsi->state;
Andy Green251f6fa2010-11-03 11:13:06 +0000162
Andy Green62c54d22011-02-14 09:14:25 +0000163 if (old_state == WSI_STATE_DEAD_SOCKET)
Andy Green5e1fa172011-02-10 09:07:05 +0000164 return;
165
Andy Greenda527df2011-03-07 07:08:12 +0000166 wsi->close_reason = reason;
167
168 /*
Andy Green68b45042011-05-25 21:41:57 +0100169 * are his extensions okay with him closing? Eg he might be a mux
170 * parent and just his ch1 aspect is closing?
171 */
172
173
174 for (n = 0; n < wsi->count_active_extensions; n++) {
175 if (!wsi->active_extensions[n]->callback)
176 continue;
177
178 m = wsi->active_extensions[n]->callback(context,
179 wsi->active_extensions[n], wsi,
180 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
181 wsi->active_extensions_user[n], NULL, 0);
182
183 /*
184 * if somebody vetoed actually closing him at this time....
185 * up to the extension to track the attempted close, let's
186 * just bail
187 */
188
189 if (m) {
Andy Greencc012472011-11-07 19:53:23 +0800190 debug("extension vetoed close\n");
Andy Green68b45042011-05-25 21:41:57 +0100191 return;
192 }
193 }
194
195
196
197 /*
Andy Greenc44159f2011-03-07 07:08:18 +0000198 * flush any tx pending from extensions, since we may send close packet
199 * if there are problems with send, just nuke the connection
200 */
201
202 ret = 1;
203 while (ret == 1) {
204
205 /* default to nobody has more to spill */
206
207 ret = 0;
208 eff_buf.token = NULL;
209 eff_buf.token_len = 0;
210
211 /* show every extension the new incoming data */
212
213 for (n = 0; n < wsi->count_active_extensions; n++) {
214 m = wsi->active_extensions[n]->callback(
Andy Green46c2ea02011-03-22 09:04:01 +0000215 wsi->protocol->owning_server,
216 wsi->active_extensions[n], wsi,
Andy Greenc44159f2011-03-07 07:08:18 +0000217 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
218 wsi->active_extensions_user[n], &eff_buf, 0);
219 if (m < 0) {
220 fprintf(stderr, "Extension reports "
221 "fatal error\n");
222 goto just_kill_connection;
223 }
224 if (m)
225 /*
226 * at least one extension told us he has more
227 * to spill, so we will go around again after
228 */
229 ret = 1;
230 }
231
232 /* assuming they left us something to send, send it */
233
234 if (eff_buf.token_len)
235 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
236 eff_buf.token_len))
237 goto just_kill_connection;
238 }
239
240 /*
Andy Greenda527df2011-03-07 07:08:12 +0000241 * signal we are closing, libsocket_write will
242 * add any necessary version-specific stuff. If the write fails,
243 * no worries we are closing anyway. If we didn't initiate this
244 * close, then our state has been changed to
245 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
246 *
247 * Likewise if it's a second call to close this connection after we
248 * sent the close indication to the peer already, we are in state
249 * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
250 */
251
252 if (old_state == WSI_STATE_ESTABLISHED &&
253 reason != LWS_CLOSE_STATUS_NOSTATUS) {
Andy Green66a16f32011-05-24 22:07:45 +0100254
Andy Greencc012472011-11-07 19:53:23 +0800255 debug("sending close indication...\n");
Andy Green66a16f32011-05-24 22:07:45 +0100256
Andy Greenda527df2011-03-07 07:08:12 +0000257 n = libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING],
258 0, LWS_WRITE_CLOSE);
259 if (!n) {
260 /*
261 * we have sent a nice protocol level indication we
262 * now wish to close, we should not send anything more
263 */
264
265 wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
266
267 /* and we should wait for a reply for a bit */
268
269 libwebsocket_set_timeout(wsi,
270 PENDING_TIMEOUT_CLOSE_ACK, 5);
271
Andy Greencc012472011-11-07 19:53:23 +0800272 debug("sent close indication, awaiting ack\n");
Andy Greenda527df2011-03-07 07:08:12 +0000273
274 return;
275 }
276
277 /* else, the send failed and we should just hang up */
278 }
279
Andy Greenc44159f2011-03-07 07:08:18 +0000280just_kill_connection:
Andy Green66a16f32011-05-24 22:07:45 +0100281
Andy Greencc012472011-11-07 19:53:23 +0800282 debug("libwebsocket_close_and_free_session: just_kill_connection\n");
Andy Green66a16f32011-05-24 22:07:45 +0100283
Andy Greenda527df2011-03-07 07:08:12 +0000284 /*
285 * we won't be servicing or receiving anything further from this guy
286 * remove this fd from wsi mapping hashtable
287 */
Andy Green4b6fbe12011-02-14 08:03:48 +0000288
Andy Greena41314f2011-05-23 10:00:03 +0100289 if (wsi->sock)
290 delete_from_fd(context, wsi->sock);
Andy Green4b6fbe12011-02-14 08:03:48 +0000291
292 /* delete it from the internal poll list if still present */
293
Peter Hinz56885f32011-03-02 22:03:47 +0000294 for (n = 0; n < context->fds_count; n++) {
295 if (context->fds[n].fd != wsi->sock)
Andy Green4b6fbe12011-02-14 08:03:48 +0000296 continue;
Peter Hinz56885f32011-03-02 22:03:47 +0000297 while (n < context->fds_count - 1) {
298 context->fds[n] = context->fds[n + 1];
Andy Green4b6fbe12011-02-14 08:03:48 +0000299 n++;
300 }
Peter Hinz56885f32011-03-02 22:03:47 +0000301 context->fds_count--;
Andy Green4b6fbe12011-02-14 08:03:48 +0000302 /* we only have to deal with one */
Peter Hinz56885f32011-03-02 22:03:47 +0000303 n = context->fds_count;
Andy Green4b6fbe12011-02-14 08:03:48 +0000304 }
305
306 /* remove also from external POLL support via protocol 0 */
Andy Greena41314f2011-05-23 10:00:03 +0100307 if (wsi->sock)
308 context->protocols[0].callback(context, wsi,
Andy Green4b6fbe12011-02-14 08:03:48 +0000309 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
310
Andy Green251f6fa2010-11-03 11:13:06 +0000311 wsi->state = WSI_STATE_DEAD_SOCKET;
312
Andy Green4b6fbe12011-02-14 08:03:48 +0000313 /* tell the user it's all over for this guy */
314
Andy Greend4302732011-02-28 07:45:29 +0000315 if (wsi->protocol && wsi->protocol->callback &&
Andy Green6ee372f2012-04-09 15:09:01 +0800316 ((old_state == WSI_STATE_ESTABLISHED) ||
317 (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
318 (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
Andy Greencc012472011-11-07 19:53:23 +0800319 debug("calling back CLOSED\n");
Peter Hinz56885f32011-03-02 22:03:47 +0000320 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
Andy Greene77ddd82010-11-13 10:03:47 +0000321 wsi->user_space, NULL, 0);
Andy Greencc012472011-11-07 19:53:23 +0800322 } else
Andy Green6ee372f2012-04-09 15:09:01 +0800323 debug("not calling back closed, old_state=%d\n", old_state);
Andy Green251f6fa2010-11-03 11:13:06 +0000324
Andy Greenef660a92011-03-06 10:29:38 +0000325 /* deallocate any active extension contexts */
326
327 for (n = 0; n < wsi->count_active_extensions; n++) {
328 if (!wsi->active_extensions[n]->callback)
329 continue;
330
Andy Green46c2ea02011-03-22 09:04:01 +0000331 wsi->active_extensions[n]->callback(context,
332 wsi->active_extensions[n], wsi,
333 LWS_EXT_CALLBACK_DESTROY,
334 wsi->active_extensions_user[n], NULL, 0);
Andy Greenef660a92011-03-06 10:29:38 +0000335
336 free(wsi->active_extensions_user[n]);
337 }
338
Andy Greena41314f2011-05-23 10:00:03 +0100339 /*
340 * inform all extensions in case they tracked this guy out of band
341 * even though not active on him specifically
342 */
343
344 ext = context->extensions;
345 while (ext && ext->callback) {
346 ext->callback(context, ext, wsi,
347 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
348 NULL, NULL, 0);
349 ext++;
350 }
351
Andy Greenef660a92011-03-06 10:29:38 +0000352 /* free up his parsing allocations */
Andy Green4b6fbe12011-02-14 08:03:48 +0000353
Andy Green251f6fa2010-11-03 11:13:06 +0000354 for (n = 0; n < WSI_TOKEN_COUNT; n++)
355 if (wsi->utf8_token[n].token)
356 free(wsi->utf8_token[n].token);
357
Andy Greena41314f2011-05-23 10:00:03 +0100358 if (wsi->c_address)
359 free(wsi->c_address);
360
Andy Green0ca6a172010-12-19 20:50:01 +0000361/* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
Andy Green251f6fa2010-11-03 11:13:06 +0000362
Andy Green3faa9c72010-11-08 17:03:03 +0000363#ifdef LWS_OPENSSL_SUPPORT
Andy Green90c7cbc2011-01-27 06:26:52 +0000364 if (wsi->ssl) {
Andy Green3faa9c72010-11-08 17:03:03 +0000365 n = SSL_get_fd(wsi->ssl);
366 SSL_shutdown(wsi->ssl);
Peter Hinz56885f32011-03-02 22:03:47 +0000367#ifdef WIN32
368 closesocket(n);
369#else
Andy Green3faa9c72010-11-08 17:03:03 +0000370 close(n);
Peter Hinz56885f32011-03-02 22:03:47 +0000371#endif
Andy Green3faa9c72010-11-08 17:03:03 +0000372 SSL_free(wsi->ssl);
373 } else {
374#endif
375 shutdown(wsi->sock, SHUT_RDWR);
Peter Hinz56885f32011-03-02 22:03:47 +0000376#ifdef WIN32
Andy Green66a16f32011-05-24 22:07:45 +0100377 if (wsi->sock)
378 closesocket(wsi->sock);
Peter Hinz56885f32011-03-02 22:03:47 +0000379#else
Andy Green66a16f32011-05-24 22:07:45 +0100380 if (wsi->sock)
381 close(wsi->sock);
Peter Hinz56885f32011-03-02 22:03:47 +0000382#endif
Andy Green3faa9c72010-11-08 17:03:03 +0000383#ifdef LWS_OPENSSL_SUPPORT
384 }
385#endif
Andy Green4f3943a2010-11-12 10:44:16 +0000386 if (wsi->user_space)
387 free(wsi->user_space);
388
Andy Green251f6fa2010-11-03 11:13:06 +0000389 free(wsi);
390}
391
Andy Green07034092011-02-13 08:37:12 +0000392/**
Andy Greenf7ee5492011-02-13 09:04:21 +0000393 * libwebsockets_hangup_on_client() - Server calls to terminate client
Andy Green6ee372f2012-04-09 15:09:01 +0800394 * connection
Peter Hinz56885f32011-03-02 22:03:47 +0000395 * @context: libwebsockets context
Andy Greenf7ee5492011-02-13 09:04:21 +0000396 * @fd: Connection socket descriptor
397 */
398
399void
Peter Hinz56885f32011-03-02 22:03:47 +0000400libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
Andy Greenf7ee5492011-02-13 09:04:21 +0000401{
Peter Hinz56885f32011-03-02 22:03:47 +0000402 struct libwebsocket *wsi = wsi_from_fd(context, fd);
Andy Greenf7ee5492011-02-13 09:04:21 +0000403
404 if (wsi == NULL)
405 return;
406
Peter Hinz56885f32011-03-02 22:03:47 +0000407 libwebsocket_close_and_free_session(context, wsi,
Andy Green6da560c2011-02-26 11:06:27 +0000408 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenf7ee5492011-02-13 09:04:21 +0000409}
410
411
412/**
Andy Green07034092011-02-13 08:37:12 +0000413 * libwebsockets_get_peer_addresses() - Get client address information
414 * @fd: Connection socket descriptor
415 * @name: Buffer to take client address name
416 * @name_len: Length of client address name buffer
417 * @rip: Buffer to take client address IP qotted quad
418 * @rip_len: Length of client address IP buffer
419 *
420 * This function fills in @name and @rip with the name and IP of
Andy Green6ee372f2012-04-09 15:09:01 +0800421 * the client connected with socket descriptor @fd. Names may be
422 * truncated if there is not enough room. If either cannot be
423 * determined, they will be returned as valid zero-length strings.
Andy Green07034092011-02-13 08:37:12 +0000424 */
425
426void
427libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
428 char *rip, int rip_len)
429{
430 unsigned int len;
431 struct sockaddr_in sin;
432 struct hostent *host;
433 struct hostent *host1;
434 char ip[128];
Andy Greenf92def72011-03-09 15:02:20 +0000435 unsigned char *p;
Andy Green07034092011-02-13 08:37:12 +0000436 int n;
Andy Green7627af52011-03-09 15:13:52 +0000437 struct sockaddr_un *un;
Andy Green07034092011-02-13 08:37:12 +0000438
439 rip[0] = '\0';
440 name[0] = '\0';
441
442 len = sizeof sin;
443 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
444 perror("getpeername");
445 return;
446 }
Andy Green6ee372f2012-04-09 15:09:01 +0800447
Andy Green07034092011-02-13 08:37:12 +0000448 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
449 AF_INET);
450 if (host == NULL) {
451 perror("gethostbyaddr");
452 return;
453 }
454
455 strncpy(name, host->h_name, name_len);
456 name[name_len - 1] = '\0';
457
458 host1 = gethostbyname(host->h_name);
459 if (host1 == NULL)
460 return;
Andy Greenf92def72011-03-09 15:02:20 +0000461 p = (unsigned char *)host1;
Andy Green07034092011-02-13 08:37:12 +0000462 n = 0;
463 while (p != NULL) {
Andy Greenf92def72011-03-09 15:02:20 +0000464 p = (unsigned char *)host1->h_addr_list[n++];
Andy Green07034092011-02-13 08:37:12 +0000465 if (p == NULL)
466 continue;
Peter Hinzbb45a902011-03-10 18:14:01 +0000467 if ((host1->h_addrtype != AF_INET)
468#ifdef AF_LOCAL
469 && (host1->h_addrtype != AF_LOCAL)
470#endif
471 )
Andy Green07034092011-02-13 08:37:12 +0000472 continue;
473
Andy Green7627af52011-03-09 15:13:52 +0000474 if (host1->h_addrtype == AF_INET)
475 sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
Peter Hinzbb45a902011-03-10 18:14:01 +0000476#ifdef AF_LOCAL
Andy Green7627af52011-03-09 15:13:52 +0000477 else {
478 un = (struct sockaddr_un *)p;
Andy Green6ee372f2012-04-09 15:09:01 +0800479 strncpy(ip, un->sun_path, sizeof(ip) - 1);
Andy Green7627af52011-03-09 15:13:52 +0000480 ip[sizeof(ip) - 1] = '\0';
481 }
Peter Hinzbb45a902011-03-10 18:14:01 +0000482#endif
Andy Green07034092011-02-13 08:37:12 +0000483 p = NULL;
484 strncpy(rip, ip, rip_len);
485 rip[rip_len - 1] = '\0';
486 }
487}
Andy Green9f990342011-02-12 11:57:45 +0000488
Peter Hinz56885f32011-03-02 22:03:47 +0000489int libwebsockets_get_random(struct libwebsocket_context *context,
490 void *buf, int len)
491{
492 int n;
493 char *p = buf;
494
495#ifdef WIN32
496 for (n = 0; n < len; n++)
497 p[n] = (unsigned char)rand();
498#else
499 n = read(context->fd_random, p, len);
500#endif
501
502 return n;
503}
504
Andy Green2836c642011-03-07 20:47:41 +0000505unsigned char *
506libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md)
507{
508 return SHA1(d, n, md);
509}
510
Andy Greeneeaacb32011-03-01 20:44:24 +0000511void libwebsockets_00_spaceout(char *key, int spaces, int seed)
512{
513 char *p;
Andy Green6ee372f2012-04-09 15:09:01 +0800514
Andy Greeneeaacb32011-03-01 20:44:24 +0000515 key++;
516 while (spaces--) {
517 if (*key && (seed & 1))
518 key++;
519 seed >>= 1;
Andy Green6ee372f2012-04-09 15:09:01 +0800520
Andy Greeneeaacb32011-03-01 20:44:24 +0000521 p = key + strlen(key);
522 while (p >= key) {
523 p[1] = p[0];
524 p--;
525 }
526 *key++ = ' ';
527 }
528}
529
530void libwebsockets_00_spam(char *key, int count, int seed)
531{
532 char *p;
533
534 key++;
535 while (count--) {
Andy Green6ee372f2012-04-09 15:09:01 +0800536
Andy Greeneeaacb32011-03-01 20:44:24 +0000537 if (*key && (seed & 1))
538 key++;
539 seed >>= 1;
540
541 p = key + strlen(key);
542 while (p >= key) {
543 p[1] = p[0];
544 p--;
545 }
546 *key++ = 0x21 + ((seed & 0xffff) % 15);
547 /* 4 would use it up too fast.. not like it matters */
548 seed >>= 1;
549 }
550}
551
Andy Green95a7b5d2011-03-06 10:29:39 +0000552int lws_send_pipe_choked(struct libwebsocket *wsi)
553{
554 struct pollfd fds;
555
556 fds.fd = wsi->sock;
557 fds.events = POLLOUT;
558 fds.revents = 0;
559
560 if (poll(&fds, 1, 0) != 1)
561 return 1;
562
563 if ((fds.revents & POLLOUT) == 0)
564 return 1;
565
566 /* okay to send another packet without blocking */
567
568 return 0;
569}
570
Andy Greena41314f2011-05-23 10:00:03 +0100571int
Andy Green3b84c002011-03-06 13:14:42 +0000572lws_handle_POLLOUT_event(struct libwebsocket_context *context,
573 struct libwebsocket *wsi, struct pollfd *pollfd)
574{
575 struct lws_tokens eff_buf;
576 int n;
577 int ret;
578 int m;
Andy Greena41314f2011-05-23 10:00:03 +0100579 int handled = 0;
Andy Green3b84c002011-03-06 13:14:42 +0000580
Andy Greena41314f2011-05-23 10:00:03 +0100581 for (n = 0; n < wsi->count_active_extensions; n++) {
582 if (!wsi->active_extensions[n]->callback)
583 continue;
584
585 m = wsi->active_extensions[n]->callback(context,
586 wsi->active_extensions[n], wsi,
587 LWS_EXT_CALLBACK_IS_WRITEABLE,
588 wsi->active_extensions_user[n], NULL, 0);
589 if (m > handled)
590 handled = m;
591 }
592
593 if (handled == 1)
594 goto notify_action;
595
596 if (!wsi->extension_data_pending || handled == 2)
Andy Green3b84c002011-03-06 13:14:42 +0000597 goto user_service;
598
599 /*
600 * check in on the active extensions, see if they
601 * had pending stuff to spill... they need to get the
602 * first look-in otherwise sequence will be disordered
603 *
604 * NULL, zero-length eff_buf means just spill pending
605 */
606
607 ret = 1;
608 while (ret == 1) {
609
610 /* default to nobody has more to spill */
611
612 ret = 0;
613 eff_buf.token = NULL;
614 eff_buf.token_len = 0;
615
616 /* give every extension a chance to spill */
617
618 for (n = 0; n < wsi->count_active_extensions; n++) {
619 m = wsi->active_extensions[n]->callback(
Andy Green46c2ea02011-03-22 09:04:01 +0000620 wsi->protocol->owning_server,
621 wsi->active_extensions[n], wsi,
Andy Green3b84c002011-03-06 13:14:42 +0000622 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
623 wsi->active_extensions_user[n], &eff_buf, 0);
624 if (m < 0) {
Andy Green6ee372f2012-04-09 15:09:01 +0800625 fprintf(stderr, "ext reports fatal error\n");
Andy Green3b84c002011-03-06 13:14:42 +0000626 return -1;
627 }
628 if (m)
629 /*
630 * at least one extension told us he has more
631 * to spill, so we will go around again after
632 */
633 ret = 1;
634 }
635
636 /* assuming they gave us something to send, send it */
637
638 if (eff_buf.token_len) {
639 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
640 eff_buf.token_len))
641 return -1;
642 } else
643 continue;
644
645 /* no extension has more to spill */
646
647 if (!ret)
648 continue;
649
650 /*
651 * There's more to spill from an extension, but we just sent
652 * something... did that leave the pipe choked?
653 */
654
655 if (!lws_send_pipe_choked(wsi))
656 /* no we could add more */
657 continue;
658
Andy Greencc012472011-11-07 19:53:23 +0800659 debug("choked in POLLOUT service\n");
Andy Green3b84c002011-03-06 13:14:42 +0000660
661 /*
662 * Yes, he's choked. Leave the POLLOUT masked on so we will
663 * come back here when he is unchoked. Don't call the user
664 * callback to enforce ordering of spilling, he'll get called
665 * when we come back here and there's nothing more to spill.
666 */
667
668 return 0;
669 }
670
671 wsi->extension_data_pending = 0;
672
673user_service:
674 /* one shot */
675
Andy Greena41314f2011-05-23 10:00:03 +0100676 if (pollfd) {
677 pollfd->events &= ~POLLOUT;
Andy Green3b84c002011-03-06 13:14:42 +0000678
Andy Greena41314f2011-05-23 10:00:03 +0100679 /* external POLL support via protocol 0 */
680 context->protocols[0].callback(context, wsi,
681 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
682 (void *)(long)wsi->sock, NULL, POLLOUT);
683 }
684
685notify_action:
Andy Green3b84c002011-03-06 13:14:42 +0000686
Andy Green9e4c2b62011-03-07 20:47:39 +0000687 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
688 n = LWS_CALLBACK_CLIENT_WRITEABLE;
689 else
690 n = LWS_CALLBACK_SERVER_WRITEABLE;
691
692 wsi->protocol->callback(context, wsi, n, wsi->user_space, NULL, 0);
Andy Green3b84c002011-03-06 13:14:42 +0000693
694 return 0;
695}
696
697
698
Andy Greena41314f2011-05-23 10:00:03 +0100699void
700libwebsocket_service_timeout_check(struct libwebsocket_context *context,
701 struct libwebsocket *wsi, unsigned int sec)
702{
703 int n;
704
705 /*
706 * if extensions want in on it (eg, we are a mux parent)
707 * give them a chance to service child timeouts
708 */
709
710 for (n = 0; n < wsi->count_active_extensions; n++)
711 wsi->active_extensions[n]->callback(
712 context, wsi->active_extensions[n],
713 wsi, LWS_EXT_CALLBACK_1HZ,
714 wsi->active_extensions_user[n], NULL, sec);
715
716 if (!wsi->pending_timeout)
717 return;
Andy Green6ee372f2012-04-09 15:09:01 +0800718
Andy Greena41314f2011-05-23 10:00:03 +0100719 /*
720 * if we went beyond the allowed time, kill the
721 * connection
722 */
723
724 if (sec > wsi->pending_timeout_limit) {
Andy Greencc012472011-11-07 19:53:23 +0800725 debug("TIMEDOUT WAITING\n");
Andy Greena41314f2011-05-23 10:00:03 +0100726 libwebsocket_close_and_free_session(context,
727 wsi, LWS_CLOSE_STATUS_NOSTATUS);
728 }
729}
730
731struct libwebsocket *
732libwebsocket_create_new_server_wsi(struct libwebsocket_context *context)
733{
734 struct libwebsocket *new_wsi;
735 int n;
736
737 new_wsi = malloc(sizeof(struct libwebsocket));
738 if (new_wsi == NULL) {
739 fprintf(stderr, "Out of memory for new connection\n");
740 return NULL;
741 }
742
Andy Green6ee372f2012-04-09 15:09:01 +0800743 memset(new_wsi, 0, sizeof(struct libwebsocket));
Andy Greena41314f2011-05-23 10:00:03 +0100744 new_wsi->count_active_extensions = 0;
745 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
746
747 /* intialize the instance struct */
748
749 new_wsi->state = WSI_STATE_HTTP;
750 new_wsi->name_buffer_pos = 0;
751 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
752
753 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
754 new_wsi->utf8_token[n].token = NULL;
755 new_wsi->utf8_token[n].token_len = 0;
756 }
757
758 /*
759 * these can only be set once the protocol is known
760 * we set an unestablished connection's protocol pointer
761 * to the start of the supported list, so it can look
762 * for matching ones during the handshake
763 */
764 new_wsi->protocol = context->protocols;
765 new_wsi->user_space = NULL;
766
767 /*
768 * Default protocol is 76 / 00
769 * After 76, there's a header specified to inform which
770 * draft the client wants, when that's seen we modify
771 * the individual connection's spec revision accordingly
772 */
773 new_wsi->ietf_spec_revision = 0;
774
775 return new_wsi;
776}
777
778char *
779libwebsockets_generate_client_handshake(struct libwebsocket_context *context,
780 struct libwebsocket *wsi, char *pkt)
781{
782 char hash[20];
783 char *p = pkt;
784 int n;
785 struct libwebsocket_extension *ext;
Andy Green09226502011-05-28 10:19:19 +0100786 struct libwebsocket_extension *ext1;
Andy Greena41314f2011-05-23 10:00:03 +0100787 int ext_count = 0;
Andy Green6ee372f2012-04-09 15:09:01 +0800788 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
789 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
Andy Greena41314f2011-05-23 10:00:03 +0100790 static const char magic_websocket_guid[] =
791 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
792
793 /*
794 * create the random key
795 */
796
797 n = libwebsockets_get_random(context, hash, 16);
798 if (n != 16) {
799 fprintf(stderr, "Unable to read from random dev %s\n",
800 SYSTEM_RANDOM_FILEPATH);
801 free(wsi->c_path);
802 free(wsi->c_host);
803 if (wsi->c_origin)
804 free(wsi->c_origin);
805 if (wsi->c_protocol)
806 free(wsi->c_protocol);
807 libwebsocket_close_and_free_session(context, wsi,
808 LWS_CLOSE_STATUS_NOSTATUS);
809 return NULL;
810 }
811
812 lws_b64_encode_string(hash, 16, wsi->key_b64,
813 sizeof wsi->key_b64);
814
815 /*
816 * 00 example client handshake
817 *
818 * GET /socket.io/websocket HTTP/1.1
819 * Upgrade: WebSocket
820 * Connection: Upgrade
821 * Host: 127.0.0.1:9999
822 * Origin: http://127.0.0.1
823 * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7 92 ^
824 * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
825 * Cookie: socketio=websocket
826 *
827 * (Á®Ä0¶†≥
828 *
829 * 04 example client handshake
830 *
831 * GET /chat HTTP/1.1
832 * Host: server.example.com
833 * Upgrade: websocket
834 * Connection: Upgrade
835 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
836 * Sec-WebSocket-Origin: http://example.com
837 * Sec-WebSocket-Protocol: chat, superchat
838 * Sec-WebSocket-Version: 4
839 */
840
841 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
842
843 if (wsi->ietf_spec_revision == 0) {
844 unsigned char spaces_1, spaces_2;
845 unsigned int max_1, max_2;
846 unsigned int num_1, num_2;
847 unsigned long product_1, product_2;
848 char key_1[40];
849 char key_2[40];
850 unsigned int seed;
851 unsigned int count;
852 char challenge[16];
853
Andy Green6ee372f2012-04-09 15:09:01 +0800854 libwebsockets_get_random(context, &spaces_1, sizeof(char));
855 libwebsockets_get_random(context, &spaces_2, sizeof(char));
Andy Greena41314f2011-05-23 10:00:03 +0100856
857 spaces_1 = (spaces_1 % 12) + 1;
858 spaces_2 = (spaces_2 % 12) + 1;
859
860 max_1 = 4294967295 / spaces_1;
861 max_2 = 4294967295 / spaces_2;
862
863 libwebsockets_get_random(context, &num_1, sizeof(int));
864 libwebsockets_get_random(context, &num_2, sizeof(int));
865
866 num_1 = (num_1 % max_1);
867 num_2 = (num_2 % max_2);
868
869 challenge[0] = num_1 >> 24;
870 challenge[1] = num_1 >> 16;
871 challenge[2] = num_1 >> 8;
872 challenge[3] = num_1;
873 challenge[4] = num_2 >> 24;
874 challenge[5] = num_2 >> 16;
875 challenge[6] = num_2 >> 8;
876 challenge[7] = num_2;
877
878 product_1 = num_1 * spaces_1;
879 product_2 = num_2 * spaces_2;
880
881 sprintf(key_1, "%lu", product_1);
882 sprintf(key_2, "%lu", product_2);
883
884 libwebsockets_get_random(context, &seed, sizeof(int));
885 libwebsockets_get_random(context, &count, sizeof(int));
886
887 libwebsockets_00_spam(key_1, (count % 12) + 1, seed);
888
889 libwebsockets_get_random(context, &seed, sizeof(int));
890 libwebsockets_get_random(context, &count, sizeof(int));
891
892 libwebsockets_00_spam(key_2, (count % 12) + 1, seed);
893
894 libwebsockets_get_random(context, &seed, sizeof(int));
895
896 libwebsockets_00_spaceout(key_1, spaces_1, seed);
897 libwebsockets_00_spaceout(key_2, spaces_2, seed >> 16);
898
899 p += sprintf(p, "Upgrade: WebSocket\x0d\x0a"
900 "Connection: Upgrade\x0d\x0aHost: %s\x0d\x0a",
901 wsi->c_host);
902 if (wsi->c_origin)
Andy Green6ee372f2012-04-09 15:09:01 +0800903 p += sprintf(p, "Origin: %s\x0d\x0a", wsi->c_origin);
Andy Greena41314f2011-05-23 10:00:03 +0100904
905 if (wsi->c_protocol)
906 p += sprintf(p, "Sec-WebSocket-Protocol: %s"
907 "\x0d\x0a", wsi->c_protocol);
908
Andy Green6ee372f2012-04-09 15:09:01 +0800909 p += sprintf(p, "Sec-WebSocket-Key1: %s\x0d\x0a", key_1);
910 p += sprintf(p, "Sec-WebSocket-Key2: %s\x0d\x0a", key_2);
Andy Greena41314f2011-05-23 10:00:03 +0100911
912 /* give userland a chance to append, eg, cookies */
913
914 context->protocols[0].callback(context, wsi,
915 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
916 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
917
918 p += sprintf(p, "\x0d\x0a");
919
920 if (libwebsockets_get_random(context, p, 8) != 8)
921 return NULL;
922 memcpy(&challenge[8], p, 8);
923 p += 8;
924
925 /* precompute what we want to see from the server */
926
927 MD5((unsigned char *)challenge, 16,
928 (unsigned char *)wsi->initial_handshake_hash_base64);
929
930 goto issue_hdr;
931 }
932
933 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
934 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
935 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
936 "Sec-WebSocket-Key: ");
937 strcpy(p, wsi->key_b64);
938 p += strlen(wsi->key_b64);
939 p += sprintf(p, "\x0d\x0a");
940 if (wsi->c_origin)
941 p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
942 wsi->c_origin);
943 if (wsi->c_protocol)
944 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
945 wsi->c_protocol);
946
947 /* tell the server what extensions we could support */
948
949 p += sprintf(p, "Sec-WebSocket-Extensions: ");
950
Andy Green6ee372f2012-04-09 15:09:01 +0800951 ext = context->extensions;
Andy Greena41314f2011-05-23 10:00:03 +0100952 while (ext && ext->callback) {
953
954 n = 0;
Andy Green09226502011-05-28 10:19:19 +0100955 ext1 = context->extensions;
Andy Green09226502011-05-28 10:19:19 +0100956
Andy Green6ee372f2012-04-09 15:09:01 +0800957 while (ext1 && ext1->callback) {
Andy Green09226502011-05-28 10:19:19 +0100958 n |= ext1->callback(context, ext1, wsi,
959 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
960 NULL, (char *)ext->name, 0);
961
962 ext1++;
963 }
964
Andy Green6ee372f2012-04-09 15:09:01 +0800965 if (n) { /* an extension vetos us */
Andy Greencc012472011-11-07 19:53:23 +0800966 debug("ext %s vetoed\n", (char *)ext->name);
Andy Green09226502011-05-28 10:19:19 +0100967 ext++;
968 continue;
969 }
970
Andy Greena41314f2011-05-23 10:00:03 +0100971 n = context->protocols[0].callback(context, wsi,
972 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
973 wsi->user_space, (char *)ext->name, 0);
974
975 /*
976 * zero return from callback means
977 * go ahead and allow the extension,
978 * it's what we get if the callback is
979 * unhandled
980 */
981
982 if (n) {
983 ext++;
984 continue;
985 }
986
987 /* apply it */
988
989 if (ext_count)
990 *p++ = ',';
991 p += sprintf(p, "%s", ext->name);
992 ext_count++;
993
994 ext++;
995 }
996
997 p += sprintf(p, "\x0d\x0a");
998
999 if (wsi->ietf_spec_revision)
1000 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
1001 wsi->ietf_spec_revision);
1002
1003 /* give userland a chance to append, eg, cookies */
1004
1005 context->protocols[0].callback(context, wsi,
1006 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
1007 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
1008
1009 p += sprintf(p, "\x0d\x0a");
1010
1011 /* prepare the expected server accept response */
1012
1013 strcpy((char *)buf, wsi->key_b64);
1014 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
1015
1016 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
1017
1018 lws_b64_encode_string(hash, 20,
1019 wsi->initial_handshake_hash_base64,
1020 sizeof wsi->initial_handshake_hash_base64);
1021
1022issue_hdr:
1023
Andy Green6ee372f2012-04-09 15:09:01 +08001024#if 0
1025 puts(pkt);
1026#endif
Andy Green09226502011-05-28 10:19:19 +01001027
Andy Greena41314f2011-05-23 10:00:03 +01001028 /* done with these now */
1029
1030 free(wsi->c_path);
1031 free(wsi->c_host);
1032 if (wsi->c_origin)
1033 free(wsi->c_origin);
1034
1035 return p;
1036}
1037
1038int
1039lws_client_interpret_server_handshake(struct libwebsocket_context *context,
1040 struct libwebsocket *wsi)
1041{
Andy Green6ee372f2012-04-09 15:09:01 +08001042 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
1043 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
Andy Greena41314f2011-05-23 10:00:03 +01001044 char pkt[1024];
1045 char *p = &pkt[0];
1046 const char *pc;
1047 const char *c;
1048 int more = 1;
1049 int okay = 0;
1050 char ext_name[128];
1051 struct libwebsocket_extension *ext;
1052 void *v;
Andy Greenc15cb382011-06-26 10:27:28 +01001053 int len = 0;
Andy Greena41314f2011-05-23 10:00:03 +01001054 int n;
1055 static const char magic_websocket_04_masking_guid[] =
1056 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
1057
1058 /*
1059 * 00 / 76 -->
1060 *
1061 * HTTP/1.1 101 WebSocket Protocol Handshake
1062 * Upgrade: WebSocket
1063 * Connection: Upgrade
1064 * Sec-WebSocket-Origin: http://127.0.0.1
1065 * Sec-WebSocket-Location: ws://127.0.0.1:9999/socket.io/websocket
1066 *
1067 * xxxxxxxxxxxxxxxx
1068 */
1069
1070 if (wsi->ietf_spec_revision == 0) {
1071 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1072 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1073 !wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
1074 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1075 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1076 wsi->c_protocol != NULL)) {
Andy Greencc012472011-11-07 19:53:23 +08001077 debug("libwebsocket_client_handshake "
Andy Greena41314f2011-05-23 10:00:03 +01001078 "missing required header(s)\n");
1079 pkt[len] = '\0';
Andy Greencc012472011-11-07 19:53:23 +08001080 debug("%s", pkt);
Andy Greena41314f2011-05-23 10:00:03 +01001081 goto bail3;
1082 }
1083
1084 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
Andy Green6ee372f2012-04-09 15:09:01 +08001085 if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
Andy Greena41314f2011-05-23 10:00:03 +01001086 fprintf(stderr, "libwebsocket_client_handshake "
1087 "server sent bad HTTP response '%s'\n",
1088 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1089 goto bail3;
1090 }
1091
Andy Green6ee372f2012-04-09 15:09:01 +08001092 if (wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len < 16) {
Andy Greena41314f2011-05-23 10:00:03 +01001093 fprintf(stderr, "libwebsocket_client_handshake "
1094 "challenge reply too short %d\n",
1095 wsi->utf8_token[
1096 WSI_TOKEN_CHALLENGE].token_len);
1097 pkt[len] = '\0';
Andy Greencc012472011-11-07 19:53:23 +08001098 debug("%s", pkt);
Andy Greena41314f2011-05-23 10:00:03 +01001099 goto bail3;
1100
1101 }
1102
1103 goto select_protocol;
1104 }
1105
1106 /*
1107 * well, what the server sent looked reasonable for syntax.
1108 * Now let's confirm it sent all the necessary headers
1109 */
1110#if 0
Andy Green6ee372f2012-04-09 15:09:01 +08001111 fprintf(stderr, "WSI_TOKEN_HTTP: %d\n",
1112 wsi->utf8_token[WSI_TOKEN_HTTP].token_len);
1113 fprintf(stderr, "WSI_TOKEN_UPGRADE: %d\n",
1114 wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len);
1115 fprintf(stderr, "WSI_TOKEN_CONNECTION: %d\n",
1116 wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len);
1117 fprintf(stderr, "WSI_TOKEN_ACCEPT: %d\n",
1118 wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len);
1119 fprintf(stderr, "WSI_TOKEN_NONCE: %d\n",
1120 wsi->utf8_token[WSI_TOKEN_NONCE].token_len);
1121 fprintf(stderr, "WSI_TOKEN_PROTOCOL: %d\n",
1122 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
Andy Greena41314f2011-05-23 10:00:03 +01001123#endif
Andy Green6ee372f2012-04-09 15:09:01 +08001124 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1125 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1126 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1127 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
1128 (!wsi->utf8_token[WSI_TOKEN_NONCE].token_len &&
Andy Greena41314f2011-05-23 10:00:03 +01001129 wsi->ietf_spec_revision == 4) ||
Andy Green6ee372f2012-04-09 15:09:01 +08001130 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1131 wsi->c_protocol != NULL)) {
1132 debug("libwebsocket_client_handshake "
Andy Greena41314f2011-05-23 10:00:03 +01001133 "missing required header(s)\n");
1134 pkt[len] = '\0';
Andy Greencc012472011-11-07 19:53:23 +08001135 debug("%s", pkt);
Andy Greena41314f2011-05-23 10:00:03 +01001136 goto bail3;
1137 }
1138
1139 /*
1140 * Everything seems to be there, now take a closer look at what
1141 * is in each header
1142 */
1143
1144 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
Artem Egorkined515ddd2011-11-23 10:46:24 +02001145 if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
Andy Greena41314f2011-05-23 10:00:03 +01001146 fprintf(stderr, "libwebsocket_client_handshake "
1147 "server sent bad HTTP response '%s'\n",
1148 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1149 goto bail3;
1150 }
1151
1152 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1153 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
1154 "websocket")) {
1155 fprintf(stderr, "libwebsocket_client_handshake server "
1156 "sent bad Upgrade header '%s'\n",
1157 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1158 goto bail3;
1159 }
1160
1161 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1162 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
1163 "upgrade")) {
1164 fprintf(stderr, "libwebsocket_client_handshake server "
1165 "sent bad Connection hdr '%s'\n",
1166 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1167 goto bail3;
1168 }
1169
1170select_protocol:
1171 pc = wsi->c_protocol;
1172 if (pc == NULL)
Andy Green6ee372f2012-04-09 15:09:01 +08001173 fprintf(stderr, "lws_client_interpret_server_handshake: "
1174 "NULL c_protocol\n");
Andy Greena41314f2011-05-23 10:00:03 +01001175 else
Andy Green6ee372f2012-04-09 15:09:01 +08001176 debug("lws_client_interpret_server_handshake: "
1177 "cPprotocol='%s'\n", pc);
Andy Greena41314f2011-05-23 10:00:03 +01001178
1179 /*
1180 * confirm the protocol the server wants to talk was in the list
1181 * of protocols we offered
1182 */
1183
1184 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
1185
Andy Green6ee372f2012-04-09 15:09:01 +08001186 fprintf(stderr, "lws_client_interpret_server_handshake "
1187 "WSI_TOKEN_PROTOCOL is null\n");
Andy Greena41314f2011-05-23 10:00:03 +01001188 /*
1189 * no protocol name to work from,
1190 * default to first protocol
1191 */
1192 wsi->protocol = &context->protocols[0];
1193
1194 free(wsi->c_protocol);
1195
1196 goto check_accept;
1197 }
1198
1199 while (*pc && !okay) {
Andy Green6ee372f2012-04-09 15:09:01 +08001200 if ((!strncmp(pc, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1201 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
1202 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
1203 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
Andy Greena41314f2011-05-23 10:00:03 +01001204 okay = 1;
1205 continue;
1206 }
1207 while (*pc && *pc != ',')
1208 pc++;
1209 while (*pc && *pc != ' ')
1210 pc++;
1211 }
1212
1213 /* done with him now */
1214
1215 if (wsi->c_protocol)
1216 free(wsi->c_protocol);
1217
Andy Greena41314f2011-05-23 10:00:03 +01001218 if (!okay) {
1219 fprintf(stderr, "libwebsocket_client_handshake server "
1220 "sent bad protocol '%s'\n",
1221 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1222 goto bail2;
1223 }
1224
1225 /*
1226 * identify the selected protocol struct and set it
1227 */
1228 n = 0;
1229 wsi->protocol = NULL;
1230 while (context->protocols[n].callback) {
1231 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1232 context->protocols[n].name) == 0)
1233 wsi->protocol = &context->protocols[n];
1234 n++;
1235 }
1236
1237 if (wsi->protocol == NULL) {
1238 fprintf(stderr, "libwebsocket_client_handshake server "
1239 "requested protocol '%s', which we "
1240 "said we supported but we don't!\n",
1241 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1242 goto bail2;
1243 }
1244
1245
1246 /* instantiate the accepted extensions */
1247
1248 if (!wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token_len) {
Andy Green6ee372f2012-04-09 15:09:01 +08001249 debug("no client extenstions allowed by server\n");
Andy Greena41314f2011-05-23 10:00:03 +01001250 goto check_accept;
1251 }
1252
1253 /*
1254 * break down the list of server accepted extensions
1255 * and go through matching them or identifying bogons
1256 */
1257
1258 c = wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token;
1259 n = 0;
1260 while (more) {
1261
1262 if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
1263 ext_name[n] = *c++;
1264 if (n < sizeof(ext_name) - 1)
1265 n++;
1266 continue;
1267 }
1268 ext_name[n] = '\0';
1269 if (!*c)
1270 more = 0;
1271 else {
1272 c++;
1273 if (!n)
1274 continue;
1275 }
1276
1277 /* check we actually support it */
1278
Andy Greencc012472011-11-07 19:53:23 +08001279 debug("checking client ext %s\n", ext_name);
Andy Greena41314f2011-05-23 10:00:03 +01001280
1281 n = 0;
1282 ext = wsi->protocol->owning_server->extensions;
1283 while (ext && ext->callback) {
1284
1285 if (strcmp(ext_name, ext->name)) {
1286 ext++;
1287 continue;
1288 }
1289
1290 n = 1;
1291
Andy Greencc012472011-11-07 19:53:23 +08001292 debug("instantiating client ext %s\n", ext_name);
Andy Greena41314f2011-05-23 10:00:03 +01001293
1294 /* instantiate the extension on this conn */
1295
1296 wsi->active_extensions_user[
1297 wsi->count_active_extensions] =
1298 malloc(ext->per_session_data_size);
Andy Greenf6652412011-05-25 20:46:18 +01001299 memset(wsi->active_extensions_user[
1300 wsi->count_active_extensions], 0,
1301 ext->per_session_data_size);
Andy Greena41314f2011-05-23 10:00:03 +01001302 wsi->active_extensions[
1303 wsi->count_active_extensions] = ext;
1304
1305 /* allow him to construct his context */
1306
1307 ext->callback(wsi->protocol->owning_server,
1308 ext, wsi,
1309 LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
1310 wsi->active_extensions_user[
1311 wsi->count_active_extensions],
1312 NULL, 0);
1313
1314 wsi->count_active_extensions++;
1315
1316 ext++;
1317 }
1318
1319 if (n == 0) {
1320 fprintf(stderr, "Server said we should use"
1321 "an unknown extension '%s'!\n", ext_name);
1322 goto bail2;
1323 }
1324
1325 n = 0;
1326 }
1327
1328
1329check_accept:
1330
1331 if (wsi->ietf_spec_revision == 0) {
1332
1333 if (memcmp(wsi->initial_handshake_hash_base64,
1334 wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 16)) {
1335 fprintf(stderr, "libwebsocket_client_handshake "
1336 "failed 00 challenge compare\n");
1337 pkt[len] = '\0';
1338 fprintf(stderr, "%s", pkt);
1339 goto bail2;
1340 }
1341
1342 goto accept_ok;
1343 }
1344
1345 /*
1346 * Confirm his accept token is the one we precomputed
1347 */
1348
1349 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1350 wsi->initial_handshake_hash_base64)) {
1351 fprintf(stderr, "libwebsocket_client_handshake server "
1352 "sent bad ACCEPT '%s' vs computed '%s'\n",
1353 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1354 wsi->initial_handshake_hash_base64);
1355 goto bail2;
1356 }
1357
1358 if (wsi->ietf_spec_revision == 4) {
1359 /*
1360 * Calculate the 04 masking key to use when
1361 * sending data to server
1362 */
1363
1364 strcpy((char *)buf, wsi->key_b64);
1365 p = (char *)buf + strlen(wsi->key_b64);
1366 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1367 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1368 strcpy(p, magic_websocket_04_masking_guid);
1369 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1370 }
Andy Green6ee372f2012-04-09 15:09:01 +08001371accept_ok:
Andy Greena41314f2011-05-23 10:00:03 +01001372
1373 /* allocate the per-connection user memory (if any) */
Andy Green6ee372f2012-04-09 15:09:01 +08001374 if (wsi->protocol->per_session_data_size &&
1375 !libwebsocket_ensure_user_space(wsi))
1376 goto bail2;
Andy Greena41314f2011-05-23 10:00:03 +01001377
1378 /* clear his proxy connection timeout */
1379
1380 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1381
1382 /* mark him as being alive */
1383
1384 wsi->state = WSI_STATE_ESTABLISHED;
1385 wsi->mode = LWS_CONNMODE_WS_CLIENT;
1386
Andy Green6ee372f2012-04-09 15:09:01 +08001387 fprintf(stderr, "handshake OK for protocol %s\n", wsi->protocol->name);
Andy Greena41314f2011-05-23 10:00:03 +01001388
1389 /* call him back to inform him he is up */
1390
1391 wsi->protocol->callback(context, wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08001392 LWS_CALLBACK_CLIENT_ESTABLISHED,
1393 wsi->user_space, NULL, 0);
Andy Greena41314f2011-05-23 10:00:03 +01001394
1395 /*
1396 * inform all extensions, not just active ones since they
1397 * already know
1398 */
1399
1400 ext = context->extensions;
1401
1402 while (ext && ext->callback) {
1403 v = NULL;
1404 for (n = 0; n < wsi->count_active_extensions; n++)
1405 if (wsi->active_extensions[n] == ext)
1406 v = wsi->active_extensions_user[n];
1407
1408 ext->callback(context, ext, wsi,
1409 LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0);
1410 ext++;
1411 }
1412
1413 return 0;
1414
1415bail3:
1416 if (wsi->c_protocol)
1417 free(wsi->c_protocol);
1418
1419bail2:
1420 libwebsocket_close_and_free_session(context, wsi,
1421 LWS_CLOSE_STATUS_NOSTATUS);
1422 return 1;
1423}
1424
1425
1426
Andy Green9f990342011-02-12 11:57:45 +00001427/**
1428 * libwebsocket_service_fd() - Service polled socket with something waiting
Peter Hinz56885f32011-03-02 22:03:47 +00001429 * @context: Websocket context
Andy Green9f990342011-02-12 11:57:45 +00001430 * @pollfd: The pollfd entry describing the socket fd and which events
Andy Green6ee372f2012-04-09 15:09:01 +08001431 * happened.
Andy Green9f990342011-02-12 11:57:45 +00001432 *
1433 * This function closes any active connections and then frees the
1434 * context. After calling this, any further use of the context is
1435 * undefined.
1436 */
1437
1438int
Peter Hinz56885f32011-03-02 22:03:47 +00001439libwebsocket_service_fd(struct libwebsocket_context *context,
Andy Green0d338332011-02-12 11:57:43 +00001440 struct pollfd *pollfd)
Andy Greenb45993c2010-12-18 15:13:50 +00001441{
Andy Green6ee372f2012-04-09 15:09:01 +08001442 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
1443 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
Andy Greena71eafc2011-02-14 17:59:43 +00001444 struct libwebsocket *wsi;
Andy Green0d338332011-02-12 11:57:43 +00001445 struct libwebsocket *new_wsi;
Andy Greenb45993c2010-12-18 15:13:50 +00001446 int n;
Andy Green0d338332011-02-12 11:57:43 +00001447 int m;
Tobias Maiere8c9b562012-04-05 11:57:12 +02001448 ssize_t len;
Andy Green0d338332011-02-12 11:57:43 +00001449 int accept_fd;
1450 unsigned int clilen;
1451 struct sockaddr_in cli_addr;
Andy Greena71eafc2011-02-14 17:59:43 +00001452 struct timeval tv;
Andy Greenbe93fef2011-02-14 20:25:43 +00001453 char pkt[1024];
1454 char *p = &pkt[0];
Andy Green2366b1c2011-03-06 13:15:31 +00001455 int more = 1;
Andy Green98a717c2011-03-06 13:14:15 +00001456 struct lws_tokens eff_buf;
Andy Green6c939552011-03-08 08:56:57 +00001457 int opt = 1;
Yonathan Yusim3ae39ff2012-04-09 06:42:39 +08001458 char c;
Andy Greenc6517fa2011-03-06 13:15:29 +00001459
Andy Greenbe93fef2011-02-14 20:25:43 +00001460#ifdef LWS_OPENSSL_SUPPORT
1461 char ssl_err_buf[512];
1462#endif
Andy Greena71eafc2011-02-14 17:59:43 +00001463 /*
1464 * you can call us with pollfd = NULL to just allow the once-per-second
1465 * global timeout checks; if less than a second since the last check
1466 * it returns immediately then.
1467 */
1468
1469 gettimeofday(&tv, NULL);
1470
Peter Hinz56885f32011-03-02 22:03:47 +00001471 if (context->last_timeout_check_s != tv.tv_sec) {
1472 context->last_timeout_check_s = tv.tv_sec;
Andy Greena71eafc2011-02-14 17:59:43 +00001473
1474 /* global timeout check once per second */
1475
Peter Hinz56885f32011-03-02 22:03:47 +00001476 for (n = 0; n < context->fds_count; n++) {
1477 wsi = wsi_from_fd(context, context->fds[n].fd);
Andy Greena71eafc2011-02-14 17:59:43 +00001478
Andy Greena41314f2011-05-23 10:00:03 +01001479 libwebsocket_service_timeout_check(context, wsi,
1480 tv.tv_sec);
Andy Greena71eafc2011-02-14 17:59:43 +00001481 }
1482 }
1483
1484 /* just here for timeout management? */
1485
1486 if (pollfd == NULL)
1487 return 0;
1488
1489 /* no, here to service a socket descriptor */
1490
Peter Hinz56885f32011-03-02 22:03:47 +00001491 wsi = wsi_from_fd(context, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +00001492
Andy Green0d338332011-02-12 11:57:43 +00001493 if (wsi == NULL)
1494 return 1;
Andy Green8f037e42010-12-19 22:13:26 +00001495
Andy Green0d338332011-02-12 11:57:43 +00001496 switch (wsi->mode) {
1497 case LWS_CONNMODE_SERVER_LISTENER:
1498
1499 /* pollin means a client has connected to us then */
1500
1501 if (!pollfd->revents & POLLIN)
1502 break;
1503
David Galeanof7009352011-09-26 12:09:54 +01001504 if (context->fds_count >= MAX_CLIENTS) {
1505 fprintf(stderr, "too busy to accept new client\n");
1506 break;
1507 }
1508
Andy Green0d338332011-02-12 11:57:43 +00001509 /* listen socket got an unencrypted connection... */
1510
1511 clilen = sizeof(cli_addr);
1512 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1513 &clilen);
1514 if (accept_fd < 0) {
1515 fprintf(stderr, "ERROR on accept");
1516 break;
1517 }
1518
Andy Green6c939552011-03-08 08:56:57 +00001519 /* Disable Nagle */
1520 opt = 1;
Andy Green6ee372f2012-04-09 15:09:01 +08001521 setsockopt(accept_fd, IPPROTO_TCP, TCP_NODELAY,
1522 (const void *)&opt, sizeof(opt));
Andy Green6c939552011-03-08 08:56:57 +00001523
Andy Green07034092011-02-13 08:37:12 +00001524 /*
1525 * look at who we connected to and give user code a chance
1526 * to reject based on client IP. There's no protocol selected
1527 * yet so we issue this to protocols[0]
1528 */
1529
Peter Hinz56885f32011-03-02 22:03:47 +00001530 if ((context->protocols[0].callback)(context, wsi,
Andy Green07034092011-02-13 08:37:12 +00001531 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
Andy Green6ee372f2012-04-09 15:09:01 +08001532 (void *)(long)accept_fd, NULL, 0)) {
Andy Greencc012472011-11-07 19:53:23 +08001533 debug("Callback denied network connection\n");
Peter Hinz56885f32011-03-02 22:03:47 +00001534#ifdef WIN32
1535 closesocket(accept_fd);
1536#else
Andy Green07034092011-02-13 08:37:12 +00001537 close(accept_fd);
Peter Hinz56885f32011-03-02 22:03:47 +00001538#endif
Andy Green07034092011-02-13 08:37:12 +00001539 break;
1540 }
1541
Andy Green0d338332011-02-12 11:57:43 +00001542 /* accepting connection to main listener */
1543
Andy Greena41314f2011-05-23 10:00:03 +01001544 new_wsi = libwebsocket_create_new_server_wsi(context);
1545 if (new_wsi == NULL)
Andy Green0d338332011-02-12 11:57:43 +00001546 break;
Andy Green0d338332011-02-12 11:57:43 +00001547
Andy Green0d338332011-02-12 11:57:43 +00001548 new_wsi->sock = accept_fd;
Andy Greena41314f2011-05-23 10:00:03 +01001549
Andy Green0d338332011-02-12 11:57:43 +00001550
1551#ifdef LWS_OPENSSL_SUPPORT
1552 new_wsi->ssl = NULL;
Andy Green0d338332011-02-12 11:57:43 +00001553
Peter Hinz56885f32011-03-02 22:03:47 +00001554 if (context->use_ssl) {
Andy Green0d338332011-02-12 11:57:43 +00001555
Peter Hinz56885f32011-03-02 22:03:47 +00001556 new_wsi->ssl = SSL_new(context->ssl_ctx);
Andy Green0d338332011-02-12 11:57:43 +00001557 if (new_wsi->ssl == NULL) {
1558 fprintf(stderr, "SSL_new failed: %s\n",
1559 ERR_error_string(SSL_get_error(
1560 new_wsi->ssl, 0), NULL));
Andy Green1f9bf522011-02-14 21:14:37 +00001561 libwebsockets_decode_ssl_error();
Andy Green0d338332011-02-12 11:57:43 +00001562 free(new_wsi);
1563 break;
1564 }
1565
1566 SSL_set_fd(new_wsi->ssl, accept_fd);
1567
1568 n = SSL_accept(new_wsi->ssl);
1569 if (n != 1) {
1570 /*
1571 * browsers seem to probe with various
1572 * ssl params which fail then retry
1573 * and succeed
1574 */
1575 debug("SSL_accept failed skt %u: %s\n",
1576 pollfd->fd,
1577 ERR_error_string(SSL_get_error(
1578 new_wsi->ssl, n), NULL));
1579 SSL_free(
1580 new_wsi->ssl);
1581 free(new_wsi);
1582 break;
1583 }
Andy Green6ee372f2012-04-09 15:09:01 +08001584
Andy Green0d338332011-02-12 11:57:43 +00001585 debug("accepted new SSL conn "
1586 "port %u on fd=%d SSL ver %s\n",
1587 ntohs(cli_addr.sin_port), accept_fd,
1588 SSL_get_version(new_wsi->ssl));
1589
1590 } else
1591#endif
1592 debug("accepted new conn port %u on fd=%d\n",
1593 ntohs(cli_addr.sin_port), accept_fd);
1594
Peter Hinz56885f32011-03-02 22:03:47 +00001595 insert_wsi(context, new_wsi);
Andy Green0d338332011-02-12 11:57:43 +00001596
Andy Green0d338332011-02-12 11:57:43 +00001597 /*
1598 * make sure NO events are seen yet on this new socket
1599 * (otherwise we inherit old fds[client].revents from
1600 * previous socket there and die mysteriously! )
1601 */
Peter Hinz56885f32011-03-02 22:03:47 +00001602 context->fds[context->fds_count].revents = 0;
Andy Green0d338332011-02-12 11:57:43 +00001603
Peter Hinz56885f32011-03-02 22:03:47 +00001604 context->fds[context->fds_count].events = POLLIN;
1605 context->fds[context->fds_count++].fd = accept_fd;
Andy Green0d338332011-02-12 11:57:43 +00001606
Andy Green3221f922011-02-12 13:14:11 +00001607 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001608 context->protocols[0].callback(context, new_wsi,
Andy Green3221f922011-02-12 13:14:11 +00001609 LWS_CALLBACK_ADD_POLL_FD,
1610 (void *)(long)accept_fd, NULL, POLLIN);
1611
Andy Green0d338332011-02-12 11:57:43 +00001612 break;
1613
1614 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
1615
1616 /* as we are listening, POLLIN means accept() is needed */
Andy Green6ee372f2012-04-09 15:09:01 +08001617
Andy Green0d338332011-02-12 11:57:43 +00001618 if (!pollfd->revents & POLLIN)
1619 break;
1620
1621 /* listen socket got an unencrypted connection... */
1622
1623 clilen = sizeof(cli_addr);
1624 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1625 &clilen);
1626 if (accept_fd < 0) {
1627 fprintf(stderr, "ERROR on accept");
1628 break;
1629 }
1630
Peter Hinz56885f32011-03-02 22:03:47 +00001631 if (context->fds_count >= MAX_CLIENTS) {
Andy Green3221f922011-02-12 13:14:11 +00001632 fprintf(stderr, "too busy to accept new broadcast "
1633 "proxy client\n");
Peter Hinz56885f32011-03-02 22:03:47 +00001634#ifdef WIN32
1635 closesocket(accept_fd);
1636#else
Andy Green0d338332011-02-12 11:57:43 +00001637 close(accept_fd);
Peter Hinz56885f32011-03-02 22:03:47 +00001638#endif
Andy Green0d338332011-02-12 11:57:43 +00001639 break;
1640 }
1641
1642 /* create a dummy wsi for the connection and add it */
1643
1644 new_wsi = malloc(sizeof(struct libwebsocket));
Andy Green6ee372f2012-04-09 15:09:01 +08001645 memset(new_wsi, 0, sizeof(struct libwebsocket));
Andy Green0d338332011-02-12 11:57:43 +00001646 new_wsi->sock = accept_fd;
1647 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
1648 new_wsi->state = WSI_STATE_ESTABLISHED;
Andy Greend6e09112011-03-05 16:12:15 +00001649 new_wsi->count_active_extensions = 0;
Andy Green0d338332011-02-12 11:57:43 +00001650 /* note which protocol we are proxying */
1651 new_wsi->protocol_index_for_broadcast_proxy =
1652 wsi->protocol_index_for_broadcast_proxy;
Peter Hinz56885f32011-03-02 22:03:47 +00001653 insert_wsi(context, new_wsi);
Andy Green0d338332011-02-12 11:57:43 +00001654
1655 /* add connected socket to internal poll array */
1656
Peter Hinz56885f32011-03-02 22:03:47 +00001657 context->fds[context->fds_count].revents = 0;
1658 context->fds[context->fds_count].events = POLLIN;
1659 context->fds[context->fds_count++].fd = accept_fd;
Andy Green0d338332011-02-12 11:57:43 +00001660
Andy Green3221f922011-02-12 13:14:11 +00001661 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001662 context->protocols[0].callback(context, new_wsi,
Andy Green3221f922011-02-12 13:14:11 +00001663 LWS_CALLBACK_ADD_POLL_FD,
1664 (void *)(long)accept_fd, NULL, POLLIN);
1665
Andy Green0d338332011-02-12 11:57:43 +00001666 break;
1667
1668 case LWS_CONNMODE_BROADCAST_PROXY:
Andy Green8f037e42010-12-19 22:13:26 +00001669
Andy Greenb45993c2010-12-18 15:13:50 +00001670 /* handle session socket closed */
Andy Green8f037e42010-12-19 22:13:26 +00001671
Andy Green0d338332011-02-12 11:57:43 +00001672 if (pollfd->revents & (POLLERR | POLLHUP)) {
Andy Green8f037e42010-12-19 22:13:26 +00001673
Andy Green0d338332011-02-12 11:57:43 +00001674 debug("Session Socket %p (fd=%d) dead\n",
Timothy J Fontaineb86d64e2011-02-14 17:55:27 +00001675 (void *)wsi, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +00001676
Peter Hinz56885f32011-03-02 22:03:47 +00001677 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001678 LWS_CLOSE_STATUS_NORMAL);
Andy Green4b6fbe12011-02-14 08:03:48 +00001679 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001680 }
Andy Green8f037e42010-12-19 22:13:26 +00001681
Andy Green3b84c002011-03-06 13:14:42 +00001682 /*
1683 * either extension code with stuff to spill, or the user code,
1684 * requested a callback when it was OK to write
1685 */
Andy Green90c7cbc2011-01-27 06:26:52 +00001686
Andy Green3b84c002011-03-06 13:14:42 +00001687 if (pollfd->revents & POLLOUT)
Andy Green6ee372f2012-04-09 15:09:01 +08001688 if (lws_handle_POLLOUT_event(context, wsi,
1689 pollfd) < 0) {
1690 libwebsocket_close_and_free_session(
1691 context, wsi, LWS_CLOSE_STATUS_NORMAL);
Andy Green3b84c002011-03-06 13:14:42 +00001692 return 1;
1693 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001694
Andy Greenb45993c2010-12-18 15:13:50 +00001695 /* any incoming data ready? */
1696
Andy Green0d338332011-02-12 11:57:43 +00001697 if (!(pollfd->revents & POLLIN))
1698 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001699
Andy Green0d338332011-02-12 11:57:43 +00001700 /* get the issued broadcast payload from the socket */
Andy Greenb45993c2010-12-18 15:13:50 +00001701
Andy Green0d338332011-02-12 11:57:43 +00001702 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
1703 MAX_BROADCAST_PAYLOAD);
1704 if (len < 0) {
1705 fprintf(stderr, "Error reading broadcast payload\n");
Andy Green4b6fbe12011-02-14 08:03:48 +00001706 break;
Andy Green0d338332011-02-12 11:57:43 +00001707 }
Andy Greenb45993c2010-12-18 15:13:50 +00001708
Andy Green0d338332011-02-12 11:57:43 +00001709 /* broadcast it to all guys with this protocol index */
Andy Green8f037e42010-12-19 22:13:26 +00001710
Andy Green0d338332011-02-12 11:57:43 +00001711 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Green8f037e42010-12-19 22:13:26 +00001712
Peter Hinz56885f32011-03-02 22:03:47 +00001713 for (m = 0; m < context->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +00001714
Peter Hinz56885f32011-03-02 22:03:47 +00001715 new_wsi = context->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +00001716
Andy Green0d338332011-02-12 11:57:43 +00001717 /* only to clients we are serving to */
Andy Greenb45993c2010-12-18 15:13:50 +00001718
Andy Green0d338332011-02-12 11:57:43 +00001719 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
Andy Greenb45993c2010-12-18 15:13:50 +00001720 continue;
1721
1722 /*
1723 * never broadcast to non-established
1724 * connection
1725 */
1726
Andy Green0d338332011-02-12 11:57:43 +00001727 if (new_wsi->state != WSI_STATE_ESTABLISHED)
Andy Green4739e5c2011-01-22 12:51:57 +00001728 continue;
1729
Andy Greenb45993c2010-12-18 15:13:50 +00001730 /*
1731 * only broadcast to connections using
1732 * the requested protocol
1733 */
1734
Andy Green0d338332011-02-12 11:57:43 +00001735 if (new_wsi->protocol->protocol_index !=
1736 wsi->protocol_index_for_broadcast_proxy)
Andy Greenb45993c2010-12-18 15:13:50 +00001737 continue;
1738
Andy Green8f037e42010-12-19 22:13:26 +00001739 /* broadcast it to this connection */
1740
Peter Hinz56885f32011-03-02 22:03:47 +00001741 new_wsi->protocol->callback(context, new_wsi,
Andy Green8f037e42010-12-19 22:13:26 +00001742 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +00001743 new_wsi->user_space,
Andy Green0ca6a172010-12-19 20:50:01 +00001744 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
Andy Greenb45993c2010-12-18 15:13:50 +00001745 }
Andy Green0d338332011-02-12 11:57:43 +00001746 }
1747 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001748
Andy Greenbe93fef2011-02-14 20:25:43 +00001749 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
1750
1751 /* handle proxy hung up on us */
1752
1753 if (pollfd->revents & (POLLERR | POLLHUP)) {
1754
1755 fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
1756 (void *)wsi, pollfd->fd);
1757
Peter Hinz56885f32011-03-02 22:03:47 +00001758 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001759 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001760 return 1;
1761 }
1762
Andy Green72c34322011-04-16 10:46:21 +01001763 n = recv(wsi->sock, pkt, sizeof pkt, 0);
Andy Greenbe93fef2011-02-14 20:25:43 +00001764 if (n < 0) {
Peter Hinz56885f32011-03-02 22:03:47 +00001765 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001766 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001767 fprintf(stderr, "ERROR reading from proxy socket\n");
1768 return 1;
1769 }
1770
1771 pkt[13] = '\0';
1772 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
Peter Hinz56885f32011-03-02 22:03:47 +00001773 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001774 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001775 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
1776 return 1;
1777 }
1778
1779 /* clear his proxy connection timeout */
1780
1781 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1782
1783 /* fallthru */
1784
1785 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
1786
1787 #ifdef LWS_OPENSSL_SUPPORT
1788 if (wsi->use_ssl) {
1789
Peter Hinz56885f32011-03-02 22:03:47 +00001790 wsi->ssl = SSL_new(context->ssl_client_ctx);
1791 wsi->client_bio = BIO_new_socket(wsi->sock,
1792 BIO_NOCLOSE);
Andy Greenbe93fef2011-02-14 20:25:43 +00001793 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
1794
Andy Green6901cb32011-02-21 08:06:47 +00001795 SSL_set_ex_data(wsi->ssl,
Andy Green2e24da02011-03-05 16:12:04 +00001796 openssl_websocket_private_data_index,
Peter Hinz56885f32011-03-02 22:03:47 +00001797 context);
Andy Green6901cb32011-02-21 08:06:47 +00001798
Andy Greenbe93fef2011-02-14 20:25:43 +00001799 if (SSL_connect(wsi->ssl) <= 0) {
1800 fprintf(stderr, "SSL connect error %s\n",
Andy Green687b0182011-02-26 11:04:01 +00001801 ERR_error_string(ERR_get_error(),
1802 ssl_err_buf));
Andy Green6ee372f2012-04-09 15:09:01 +08001803 libwebsocket_close_and_free_session(context,
1804 wsi, LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001805 return 1;
1806 }
1807
1808 n = SSL_get_verify_result(wsi->ssl);
Andy Green2e24da02011-03-05 16:12:04 +00001809 if ((n != X509_V_OK) && (
Andy Green687b0182011-02-26 11:04:01 +00001810 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
1811 wsi->use_ssl != 2)) {
Andy Greenbe93fef2011-02-14 20:25:43 +00001812
Andy Green687b0182011-02-26 11:04:01 +00001813 fprintf(stderr, "server's cert didn't "
1814 "look good %d\n", n);
Peter Hinz56885f32011-03-02 22:03:47 +00001815 libwebsocket_close_and_free_session(context,
1816 wsi, LWS_CLOSE_STATUS_NOSTATUS);
Andy Green687b0182011-02-26 11:04:01 +00001817 return 1;
Andy Greenbe93fef2011-02-14 20:25:43 +00001818 }
1819 } else {
1820 wsi->ssl = NULL;
1821 #endif
1822
1823
1824 #ifdef LWS_OPENSSL_SUPPORT
1825 }
1826 #endif
1827
Andy Greena41314f2011-05-23 10:00:03 +01001828 p = libwebsockets_generate_client_handshake(context, wsi, p);
Andy Green6ee372f2012-04-09 15:09:01 +08001829 if (p == NULL)
Andy Greenbe93fef2011-02-14 20:25:43 +00001830 return 1;
Andy Greeneeaacb32011-03-01 20:44:24 +00001831
Andy Greenbe93fef2011-02-14 20:25:43 +00001832 /* send our request to the server */
1833
1834 #ifdef LWS_OPENSSL_SUPPORT
1835 if (wsi->use_ssl)
1836 n = SSL_write(wsi->ssl, pkt, p - pkt);
1837 else
1838 #endif
1839 n = send(wsi->sock, pkt, p - pkt, 0);
1840
1841 if (n < 0) {
1842 fprintf(stderr, "ERROR writing to client socket\n");
Peter Hinz56885f32011-03-02 22:03:47 +00001843 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001844 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001845 return 1;
1846 }
1847
1848 wsi->parser_state = WSI_TOKEN_NAME_PART;
1849 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
1850 libwebsocket_set_timeout(wsi,
1851 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
1852
1853 break;
1854
1855 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
1856
1857 /* handle server hung up on us */
1858
1859 if (pollfd->revents & (POLLERR | POLLHUP)) {
1860
1861 fprintf(stderr, "Server connection %p (fd=%d) dead\n",
1862 (void *)wsi, pollfd->fd);
1863
1864 goto bail3;
1865 }
1866
1867
1868 /* interpret the server response */
1869
1870 /*
1871 * HTTP/1.1 101 Switching Protocols
1872 * Upgrade: websocket
1873 * Connection: Upgrade
1874 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
1875 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
1876 * Sec-WebSocket-Protocol: chat
1877 */
1878
Yonathan Yusim3ae39ff2012-04-09 06:42:39 +08001879 /*
1880 * we have to take some care here to only take from the
1881 * socket bytewise. The browser may (and has been seen to
1882 * in the case that onopen() performs websocket traffic)
1883 * coalesce both handshake response and websocket traffic
1884 * in one packet, since at that point the connection is
1885 * definitively ready from browser pov.
1886 */
Andy Greenbe93fef2011-02-14 20:25:43 +00001887
Andy Green7b5af9a2012-04-09 15:23:47 +08001888 len = 1;
Yonathan Yusim3ae39ff2012-04-09 06:42:39 +08001889 while (wsi->parser_state != WSI_PARSING_COMPLETE && len > 0) {
1890#ifdef LWS_OPENSSL_SUPPORT
1891 if (wsi->use_ssl)
1892 len = SSL_read(wsi->ssl, &c, 1);
1893 else
1894#endif
1895 len = recv(wsi->sock, &c, 1, 0);
1896
1897 libwebsocket_parse(wsi, c);
Andy Greenbe93fef2011-02-14 20:25:43 +00001898 }
1899
Andy Green27a0b912011-04-16 10:54:28 +01001900 /*
Andy Green6ee372f2012-04-09 15:09:01 +08001901 * hs may also be coming in multiple packets, there is a 5-sec
Andy Green27a0b912011-04-16 10:54:28 +01001902 * libwebsocket timeout still active here too, so if parsing did
1903 * not complete just wait for next packet coming in this state
1904 */
1905
1906 if (wsi->parser_state != WSI_PARSING_COMPLETE)
1907 break;
Andy Greenbe93fef2011-02-14 20:25:43 +00001908
Yonathan Yusim3ae39ff2012-04-09 06:42:39 +08001909 /*
1910 * otherwise deal with the handshake. If there's any
1911 * packet traffic already arrived we'll trigger poll() again
1912 * right away and deal with it that way
1913 */
1914
Andy Greena41314f2011-05-23 10:00:03 +01001915 return lws_client_interpret_server_handshake(context, wsi);
Andy Greenbe93fef2011-02-14 20:25:43 +00001916
1917bail3:
1918 if (wsi->c_protocol)
1919 free(wsi->c_protocol);
Peter Hinz56885f32011-03-02 22:03:47 +00001920 libwebsocket_close_and_free_session(context, wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08001921 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001922 return 1;
Andy Greena41314f2011-05-23 10:00:03 +01001923
1924 case LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT:
Andy Green6ee372f2012-04-09 15:09:01 +08001925 fprintf(stderr,
1926 "LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT\n");
Andy Greena41314f2011-05-23 10:00:03 +01001927 break;
1928
1929 case LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD:
Andy Green6ee372f2012-04-09 15:09:01 +08001930 fprintf(stderr,
1931 "LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD\n");
Andy Greena41314f2011-05-23 10:00:03 +01001932 break;
1933
Andy Greenbe93fef2011-02-14 20:25:43 +00001934
Andy Green0d338332011-02-12 11:57:43 +00001935 case LWS_CONNMODE_WS_SERVING:
1936 case LWS_CONNMODE_WS_CLIENT:
1937
1938 /* handle session socket closed */
1939
1940 if (pollfd->revents & (POLLERR | POLLHUP)) {
1941
Andy Green62c54d22011-02-14 09:14:25 +00001942 fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
Andy Green0d338332011-02-12 11:57:43 +00001943 (void *)wsi, pollfd->fd);
1944
Peter Hinz56885f32011-03-02 22:03:47 +00001945 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001946 LWS_CLOSE_STATUS_NOSTATUS);
Andy Green4b6fbe12011-02-14 08:03:48 +00001947 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001948 }
1949
Andy Green0d338332011-02-12 11:57:43 +00001950 /* the guy requested a callback when it was OK to write */
1951
Andy Greenda527df2011-03-07 07:08:12 +00001952 if ((pollfd->revents & POLLOUT) &&
1953 wsi->state == WSI_STATE_ESTABLISHED)
1954 if (lws_handle_POLLOUT_event(context, wsi,
1955 pollfd) < 0) {
1956 libwebsocket_close_and_free_session(
1957 context, wsi, LWS_CLOSE_STATUS_NORMAL);
Andy Green3b84c002011-03-06 13:14:42 +00001958 return 1;
1959 }
Andy Green0d338332011-02-12 11:57:43 +00001960
Andy Green0d338332011-02-12 11:57:43 +00001961
1962 /* any incoming data ready? */
1963
1964 if (!(pollfd->revents & POLLIN))
1965 break;
1966
Andy Greenb45993c2010-12-18 15:13:50 +00001967#ifdef LWS_OPENSSL_SUPPORT
Andy Green0d338332011-02-12 11:57:43 +00001968 if (wsi->ssl)
Andy Green98a717c2011-03-06 13:14:15 +00001969 eff_buf.token_len = SSL_read(wsi->ssl, buf, sizeof buf);
Andy Greenb45993c2010-12-18 15:13:50 +00001970 else
1971#endif
Andy Green98a717c2011-03-06 13:14:15 +00001972 eff_buf.token_len =
Andy Green72c34322011-04-16 10:46:21 +01001973 recv(pollfd->fd, buf, sizeof buf, 0);
Andy Greenb45993c2010-12-18 15:13:50 +00001974
Andy Green98a717c2011-03-06 13:14:15 +00001975 if (eff_buf.token_len < 0) {
1976 fprintf(stderr, "Socket read returned %d\n",
1977 eff_buf.token_len);
Nick Dowellc04c1932012-04-05 10:29:39 +08001978 if (errno != EINTR)
Andy Green6ee372f2012-04-09 15:09:01 +08001979 libwebsocket_close_and_free_session(context,
1980 wsi, LWS_CLOSE_STATUS_NOSTATUS);
Nick Dowellc04c1932012-04-05 10:29:39 +08001981 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001982 }
Andy Green98a717c2011-03-06 13:14:15 +00001983 if (!eff_buf.token_len) {
Peter Hinz56885f32011-03-02 22:03:47 +00001984 libwebsocket_close_and_free_session(context, wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08001985 LWS_CLOSE_STATUS_NOSTATUS);
Andy Green4b6fbe12011-02-14 08:03:48 +00001986 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001987 }
1988
Andy Green98a717c2011-03-06 13:14:15 +00001989 /*
1990 * give any active extensions a chance to munge the buffer
1991 * before parse. We pass in a pointer to an lws_tokens struct
1992 * prepared with the default buffer and content length that's in
1993 * there. Rather than rewrite the default buffer, extensions
1994 * that expect to grow the buffer can adapt .token to
1995 * point to their own per-connection buffer in the extension
1996 * user allocation. By default with no extensions or no
1997 * extension callback handling, just the normal input buffer is
1998 * used then so it is efficient.
1999 */
Andy Greenb45993c2010-12-18 15:13:50 +00002000
Andy Green98a717c2011-03-06 13:14:15 +00002001 eff_buf.token = (char *)buf;
Andy Greenb45993c2010-12-18 15:13:50 +00002002
Andy Green98a717c2011-03-06 13:14:15 +00002003 more = 1;
2004 while (more) {
Andy Green0d338332011-02-12 11:57:43 +00002005
Andy Green98a717c2011-03-06 13:14:15 +00002006 more = 0;
2007
2008 for (n = 0; n < wsi->count_active_extensions; n++) {
Andy Green46c2ea02011-03-22 09:04:01 +00002009 m = wsi->active_extensions[n]->callback(context,
2010 wsi->active_extensions[n], wsi,
Andy Green98a717c2011-03-06 13:14:15 +00002011 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
Andy Green46c2ea02011-03-22 09:04:01 +00002012 wsi->active_extensions_user[n],
2013 &eff_buf, 0);
Andy Green98a717c2011-03-06 13:14:15 +00002014 if (m < 0) {
Andy Green6ee372f2012-04-09 15:09:01 +08002015 fprintf(stderr,
2016 "Extension reports fatal error\n");
2017 libwebsocket_close_and_free_session(
2018 context, wsi,
2019 LWS_CLOSE_STATUS_NOSTATUS);
Andy Green98a717c2011-03-06 13:14:15 +00002020 return 1;
2021 }
2022 if (m)
2023 more = 1;
2024 }
2025
2026 /* service incoming data */
2027
2028 if (eff_buf.token_len) {
2029 n = libwebsocket_read(context, wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08002030 (unsigned char *)eff_buf.token,
2031 eff_buf.token_len);
Andy Green98a717c2011-03-06 13:14:15 +00002032 if (n < 0)
2033 /* we closed wsi */
2034 return 1;
2035 }
2036
2037 eff_buf.token = NULL;
2038 eff_buf.token_len = 0;
2039 }
2040 break;
Andy Greenb45993c2010-12-18 15:13:50 +00002041 }
2042
2043 return 0;
2044}
2045
Andy Green0d338332011-02-12 11:57:43 +00002046
Andy Green6964bb52011-01-23 16:50:33 +00002047/**
2048 * libwebsocket_context_destroy() - Destroy the websocket context
Peter Hinz56885f32011-03-02 22:03:47 +00002049 * @context: Websocket context
Andy Green6964bb52011-01-23 16:50:33 +00002050 *
2051 * This function closes any active connections and then frees the
2052 * context. After calling this, any further use of the context is
2053 * undefined.
2054 */
2055void
Peter Hinz56885f32011-03-02 22:03:47 +00002056libwebsocket_context_destroy(struct libwebsocket_context *context)
Andy Green6964bb52011-01-23 16:50:33 +00002057{
Andy Green0d338332011-02-12 11:57:43 +00002058 int n;
2059 int m;
2060 struct libwebsocket *wsi;
Andy Greena41314f2011-05-23 10:00:03 +01002061 struct libwebsocket_extension *ext;
Andy Green6964bb52011-01-23 16:50:33 +00002062
Andy Green4b6fbe12011-02-14 08:03:48 +00002063 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
Peter Hinz56885f32011-03-02 22:03:47 +00002064 for (m = 0; m < context->fd_hashtable[n].length; m++) {
2065 wsi = context->fd_hashtable[n].wsi[m];
2066 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00002067 LWS_CLOSE_STATUS_GOINGAWAY);
Andy Greenf3d3b402011-02-09 07:16:34 +00002068 }
Andy Green6964bb52011-01-23 16:50:33 +00002069
Andy Greena41314f2011-05-23 10:00:03 +01002070 /*
2071 * give all extensions a chance to clean up any per-context
2072 * allocations they might have made
2073 */
2074
2075 ext = context->extensions;
2076 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
2077 if (context->listen_port)
2078 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
2079 while (ext->callback) {
2080 ext->callback(context, ext, NULL, m, NULL, NULL, 0);
2081 ext++;
2082 }
2083
Peter Hinz56885f32011-03-02 22:03:47 +00002084#ifdef WIN32
2085#else
2086 close(context->fd_random);
Andy Green6964bb52011-01-23 16:50:33 +00002087#endif
2088
Peter Hinz56885f32011-03-02 22:03:47 +00002089#ifdef LWS_OPENSSL_SUPPORT
2090 if (context->ssl_ctx)
2091 SSL_CTX_free(context->ssl_ctx);
2092 if (context->ssl_client_ctx)
2093 SSL_CTX_free(context->ssl_client_ctx);
2094#endif
2095
2096 free(context);
2097
2098#ifdef WIN32
2099 WSACleanup();
2100#endif
Andy Green6964bb52011-01-23 16:50:33 +00002101}
2102
2103/**
2104 * libwebsocket_service() - Service any pending websocket activity
Peter Hinz56885f32011-03-02 22:03:47 +00002105 * @context: Websocket context
Andy Green6964bb52011-01-23 16:50:33 +00002106 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2107 * service otherwise block and service immediately, returning
2108 * after the timeout if nothing needed service.
2109 *
2110 * This function deals with any pending websocket traffic, for three
2111 * kinds of event. It handles these events on both server and client
2112 * types of connection the same.
2113 *
2114 * 1) Accept new connections to our context's server
2115 *
2116 * 2) Perform pending broadcast writes initiated from other forked
2117 * processes (effectively serializing asynchronous broadcasts)
2118 *
2119 * 3) Call the receive callback for incoming frame data received by
2120 * server or client connections.
2121 *
2122 * You need to call this service function periodically to all the above
2123 * functions to happen; if your application is single-threaded you can
2124 * just call it in your main event loop.
2125 *
2126 * Alternatively you can fork a new process that asynchronously handles
2127 * calling this service in a loop. In that case you are happy if this
2128 * call blocks your thread until it needs to take care of something and
2129 * would call it with a large nonzero timeout. Your loop then takes no
2130 * CPU while there is nothing happening.
2131 *
2132 * If you are calling it in a single-threaded app, you don't want it to
2133 * wait around blocking other things in your loop from happening, so you
2134 * would call it with a timeout_ms of 0, so it returns immediately if
2135 * nothing is pending, or as soon as it services whatever was pending.
2136 */
2137
Andy Greenb45993c2010-12-18 15:13:50 +00002138
Andy Greene92cd172011-01-19 13:11:55 +00002139int
Peter Hinz56885f32011-03-02 22:03:47 +00002140libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
Andy Greene92cd172011-01-19 13:11:55 +00002141{
2142 int n;
Andy Greene92cd172011-01-19 13:11:55 +00002143
2144 /* stay dead once we are dead */
2145
Peter Hinz56885f32011-03-02 22:03:47 +00002146 if (context == NULL)
Andy Greene92cd172011-01-19 13:11:55 +00002147 return 1;
2148
Andy Green0d338332011-02-12 11:57:43 +00002149 /* wait for something to need service */
Andy Green4739e5c2011-01-22 12:51:57 +00002150
Peter Hinz56885f32011-03-02 22:03:47 +00002151 n = poll(context->fds, context->fds_count, timeout_ms);
Andy Green3221f922011-02-12 13:14:11 +00002152 if (n == 0) /* poll timeout */
2153 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00002154
Andy Green62c54d22011-02-14 09:14:25 +00002155 if (n < 0) {
Andy Green5e1fa172011-02-10 09:07:05 +00002156 /*
Andy Greene92cd172011-01-19 13:11:55 +00002157 fprintf(stderr, "Listen Socket dead\n");
Andy Green5e1fa172011-02-10 09:07:05 +00002158 */
Andy Green0d338332011-02-12 11:57:43 +00002159 return 1;
Andy Greene92cd172011-01-19 13:11:55 +00002160 }
Andy Greene92cd172011-01-19 13:11:55 +00002161
2162 /* handle accept on listening socket? */
2163
Peter Hinz56885f32011-03-02 22:03:47 +00002164 for (n = 0; n < context->fds_count; n++)
2165 if (context->fds[n].revents)
2166 libwebsocket_service_fd(context, &context->fds[n]);
Andy Greene92cd172011-01-19 13:11:55 +00002167
2168 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00002169}
2170
Andy Greena41314f2011-05-23 10:00:03 +01002171int
2172lws_any_extension_handled(struct libwebsocket_context *context,
Andy Green6ee372f2012-04-09 15:09:01 +08002173 struct libwebsocket *wsi,
2174 enum libwebsocket_extension_callback_reasons r,
Andy Greena41314f2011-05-23 10:00:03 +01002175 void *v, size_t len)
2176{
2177 int n;
2178 int handled = 0;
2179
2180 /* maybe an extension will take care of it for us */
2181
2182 for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
2183 if (!wsi->active_extensions[n]->callback)
2184 continue;
2185
2186 handled |= wsi->active_extensions[n]->callback(context,
2187 wsi->active_extensions[n], wsi,
2188 r, wsi->active_extensions_user[n], v, len);
2189 }
2190
2191 return handled;
2192}
2193
2194
2195void *
2196lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08002197 struct libwebsocket_extension *ext)
Andy Greena41314f2011-05-23 10:00:03 +01002198{
2199 int n = 0;
2200
Andy Green68b45042011-05-25 21:41:57 +01002201 if (wsi == NULL)
2202 return NULL;
2203
Andy Greena41314f2011-05-23 10:00:03 +01002204 while (n < wsi->count_active_extensions) {
2205 if (wsi->active_extensions[n] != ext) {
2206 n++;
2207 continue;
2208 }
2209 return wsi->active_extensions_user[n];
2210 }
2211
2212 return NULL;
2213}
2214
Andy Green90c7cbc2011-01-27 06:26:52 +00002215/**
2216 * libwebsocket_callback_on_writable() - Request a callback when this socket
2217 * becomes able to be written to without
2218 * blocking
Andy Green32375b72011-02-19 08:32:53 +00002219 *
Peter Hinz56885f32011-03-02 22:03:47 +00002220 * @context: libwebsockets context
Andy Green90c7cbc2011-01-27 06:26:52 +00002221 * @wsi: Websocket connection instance to get callback for
2222 */
2223
2224int
Peter Hinz56885f32011-03-02 22:03:47 +00002225libwebsocket_callback_on_writable(struct libwebsocket_context *context,
Andy Green6ee372f2012-04-09 15:09:01 +08002226 struct libwebsocket *wsi)
Andy Green90c7cbc2011-01-27 06:26:52 +00002227{
Andy Green90c7cbc2011-01-27 06:26:52 +00002228 int n;
Andy Greena41314f2011-05-23 10:00:03 +01002229 int handled = 0;
2230
2231 /* maybe an extension will take care of it for us */
2232
2233 for (n = 0; n < wsi->count_active_extensions; n++) {
2234 if (!wsi->active_extensions[n]->callback)
2235 continue;
2236
2237 handled |= wsi->active_extensions[n]->callback(context,
2238 wsi->active_extensions[n], wsi,
2239 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
2240 wsi->active_extensions_user[n], NULL, 0);
2241 }
2242
2243 if (handled)
2244 return 1;
Andy Green90c7cbc2011-01-27 06:26:52 +00002245
Peter Hinz56885f32011-03-02 22:03:47 +00002246 for (n = 0; n < context->fds_count; n++)
2247 if (context->fds[n].fd == wsi->sock) {
2248 context->fds[n].events |= POLLOUT;
Andy Greena41314f2011-05-23 10:00:03 +01002249 n = context->fds_count + 1;
Andy Green90c7cbc2011-01-27 06:26:52 +00002250 }
2251
Andy Greena41314f2011-05-23 10:00:03 +01002252 if (n == context->fds_count)
Andy Green6ee372f2012-04-09 15:09:01 +08002253 fprintf(stderr, "libwebsocket_callback_on_writable: "
2254 "failed to find socket %d\n", wsi->sock);
Andy Greena41314f2011-05-23 10:00:03 +01002255
Andy Green3221f922011-02-12 13:14:11 +00002256 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002257 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002258 LWS_CALLBACK_SET_MODE_POLL_FD,
2259 (void *)(long)wsi->sock, NULL, POLLOUT);
2260
Andy Green90c7cbc2011-01-27 06:26:52 +00002261 return 1;
2262}
2263
2264/**
2265 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
2266 * all connections using the given protocol when it
2267 * becomes possible to write to each socket without
2268 * blocking in turn.
2269 *
2270 * @protocol: Protocol whose connections will get callbacks
2271 */
2272
2273int
2274libwebsocket_callback_on_writable_all_protocol(
2275 const struct libwebsocket_protocols *protocol)
2276{
Peter Hinz56885f32011-03-02 22:03:47 +00002277 struct libwebsocket_context *context = protocol->owning_server;
Andy Green90c7cbc2011-01-27 06:26:52 +00002278 int n;
Andy Green0d338332011-02-12 11:57:43 +00002279 int m;
2280 struct libwebsocket *wsi;
Andy Green90c7cbc2011-01-27 06:26:52 +00002281
Andy Green0d338332011-02-12 11:57:43 +00002282 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
2283
Peter Hinz56885f32011-03-02 22:03:47 +00002284 for (m = 0; m < context->fd_hashtable[n].length; m++) {
Andy Green0d338332011-02-12 11:57:43 +00002285
Peter Hinz56885f32011-03-02 22:03:47 +00002286 wsi = context->fd_hashtable[n].wsi[m];
Andy Green0d338332011-02-12 11:57:43 +00002287
2288 if (wsi->protocol == protocol)
Peter Hinz56885f32011-03-02 22:03:47 +00002289 libwebsocket_callback_on_writable(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00002290 }
2291 }
Andy Green90c7cbc2011-01-27 06:26:52 +00002292
2293 return 0;
2294}
2295
Andy Greenbe93fef2011-02-14 20:25:43 +00002296/**
2297 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
2298 *
2299 * You will not need this unless you are doing something special
2300 *
2301 * @wsi: Websocket connection instance
2302 * @reason: timeout reason
2303 * @secs: how many seconds
2304 */
2305
2306void
2307libwebsocket_set_timeout(struct libwebsocket *wsi,
2308 enum pending_timeout reason, int secs)
2309{
2310 struct timeval tv;
2311
2312 gettimeofday(&tv, NULL);
2313
2314 wsi->pending_timeout_limit = tv.tv_sec + secs;
2315 wsi->pending_timeout = reason;
2316}
2317
Andy Greena6cbece2011-01-27 20:06:03 +00002318
2319/**
2320 * libwebsocket_get_socket_fd() - returns the socket file descriptor
2321 *
2322 * You will not need this unless you are doing something special
2323 *
2324 * @wsi: Websocket connection instance
2325 */
2326
2327int
2328libwebsocket_get_socket_fd(struct libwebsocket *wsi)
2329{
2330 return wsi->sock;
2331}
2332
Andy Green90c7cbc2011-01-27 06:26:52 +00002333/**
2334 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
2335 * receieved packets.
2336 *
2337 * If the output side of a server process becomes choked, this allows flow
2338 * control for the input side.
2339 *
2340 * @wsi: Websocket connection instance to get callback for
2341 * @enable: 0 = disable read servicing for this connection, 1 = enable
2342 */
2343
2344int
2345libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
2346{
Peter Hinz56885f32011-03-02 22:03:47 +00002347 struct libwebsocket_context *context = wsi->protocol->owning_server;
Andy Green90c7cbc2011-01-27 06:26:52 +00002348 int n;
2349
Peter Hinz56885f32011-03-02 22:03:47 +00002350 for (n = 0; n < context->fds_count; n++)
2351 if (context->fds[n].fd == wsi->sock) {
Andy Green90c7cbc2011-01-27 06:26:52 +00002352 if (enable)
Peter Hinz56885f32011-03-02 22:03:47 +00002353 context->fds[n].events |= POLLIN;
Andy Green90c7cbc2011-01-27 06:26:52 +00002354 else
Peter Hinz56885f32011-03-02 22:03:47 +00002355 context->fds[n].events &= ~POLLIN;
Andy Green90c7cbc2011-01-27 06:26:52 +00002356
2357 return 0;
2358 }
2359
Andy Green3221f922011-02-12 13:14:11 +00002360 if (enable)
2361 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002362 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002363 LWS_CALLBACK_SET_MODE_POLL_FD,
2364 (void *)(long)wsi->sock, NULL, POLLIN);
2365 else
2366 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002367 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002368 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
2369 (void *)(long)wsi->sock, NULL, POLLIN);
2370
Andy Greena41314f2011-05-23 10:00:03 +01002371#if 0
2372 fprintf(stderr, "libwebsocket_rx_flow_control "
Andy Green90c7cbc2011-01-27 06:26:52 +00002373 "unable to find socket\n");
Andy Greena41314f2011-05-23 10:00:03 +01002374#endif
Andy Green90c7cbc2011-01-27 06:26:52 +00002375 return 1;
2376}
2377
Andy Green2ac5a6f2011-01-28 10:00:18 +00002378/**
2379 * libwebsocket_canonical_hostname() - returns this host's hostname
2380 *
2381 * This is typically used by client code to fill in the host parameter
2382 * when making a client connection. You can only call it after the context
2383 * has been created.
2384 *
Peter Hinz56885f32011-03-02 22:03:47 +00002385 * @context: Websocket context
Andy Green2ac5a6f2011-01-28 10:00:18 +00002386 */
2387
2388
2389extern const char *
Peter Hinz56885f32011-03-02 22:03:47 +00002390libwebsocket_canonical_hostname(struct libwebsocket_context *context)
Andy Green2ac5a6f2011-01-28 10:00:18 +00002391{
Peter Hinz56885f32011-03-02 22:03:47 +00002392 return (const char *)context->canonical_hostname;
Andy Green2ac5a6f2011-01-28 10:00:18 +00002393}
2394
2395
Andy Green90c7cbc2011-01-27 06:26:52 +00002396static void sigpipe_handler(int x)
2397{
2398}
2399
Andy Green6901cb32011-02-21 08:06:47 +00002400#ifdef LWS_OPENSSL_SUPPORT
2401static int
2402OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
2403{
2404
2405 SSL *ssl;
2406 int n;
Andy Green2e24da02011-03-05 16:12:04 +00002407 struct libwebsocket_context *context;
Andy Green6901cb32011-02-21 08:06:47 +00002408
2409 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
2410 SSL_get_ex_data_X509_STORE_CTX_idx());
2411
2412 /*
Andy Green2e24da02011-03-05 16:12:04 +00002413 * !!! nasty openssl requires the index to come as a library-scope
2414 * static
Andy Green6901cb32011-02-21 08:06:47 +00002415 */
Andy Green2e24da02011-03-05 16:12:04 +00002416 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
Andy Green6ee372f2012-04-09 15:09:01 +08002417
Peter Hinz56885f32011-03-02 22:03:47 +00002418 n = context->protocols[0].callback(NULL, NULL,
Andy Green6901cb32011-02-21 08:06:47 +00002419 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
2420 x509_ctx, ssl, preverify_ok);
2421
2422 /* convert return code from 0 = OK to 1 = OK */
2423
2424 if (!n)
2425 n = 1;
2426 else
2427 n = 0;
2428
2429 return n;
2430}
2431#endif
2432
Andy Greenb45993c2010-12-18 15:13:50 +00002433
Andy Greenab990e42010-10-31 12:42:52 +00002434/**
Andy Green4739e5c2011-01-22 12:51:57 +00002435 * libwebsocket_create_context() - Create the websocket handler
2436 * @port: Port to listen on... you can use 0 to suppress listening on
Andy Green6964bb52011-01-23 16:50:33 +00002437 * any port, that's what you want if you are not running a
2438 * websocket server at all but just using it as a client
Peter Hinz56885f32011-03-02 22:03:47 +00002439 * @interf: NULL to bind the listen socket to all interfaces, or the
Andy Green32375b72011-02-19 08:32:53 +00002440 * interface name, eg, "eth2"
Andy Green4f3943a2010-11-12 10:44:16 +00002441 * @protocols: Array of structures listing supported protocols and a protocol-
Andy Green8f037e42010-12-19 22:13:26 +00002442 * specific callback for each one. The list is ended with an
2443 * entry that has a NULL callback pointer.
Andy Green6964bb52011-01-23 16:50:33 +00002444 * It's not const because we write the owning_server member
Andy Greenc5114822011-03-06 10:29:35 +00002445 * @extensions: NULL or array of libwebsocket_extension structs listing the
Andy Green6ee372f2012-04-09 15:09:01 +08002446 * extensions this context supports
Andy Green3faa9c72010-11-08 17:03:03 +00002447 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
Andy Green8f037e42010-12-19 22:13:26 +00002448 * to listen using SSL, set to the filepath to fetch the
2449 * server cert from, otherwise NULL for unencrypted
Andy Green3faa9c72010-11-08 17:03:03 +00002450 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
Andy Green8f037e42010-12-19 22:13:26 +00002451 * else ignored
Andy Green3faa9c72010-11-08 17:03:03 +00002452 * @gid: group id to change to after setting listen socket, or -1.
2453 * @uid: user id to change to after setting listen socket, or -1.
Andy Greenbfb051f2011-02-09 08:49:14 +00002454 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
Andy Green05464c62010-11-12 10:44:18 +00002455 *
Andy Green8f037e42010-12-19 22:13:26 +00002456 * This function creates the listening socket and takes care
2457 * of all initialization in one step.
2458 *
Andy Greene92cd172011-01-19 13:11:55 +00002459 * After initialization, it returns a struct libwebsocket_context * that
2460 * represents this server. After calling, user code needs to take care
2461 * of calling libwebsocket_service() with the context pointer to get the
2462 * server's sockets serviced. This can be done in the same process context
2463 * or a forked process, or another thread,
Andy Green05464c62010-11-12 10:44:18 +00002464 *
Andy Green8f037e42010-12-19 22:13:26 +00002465 * The protocol callback functions are called for a handful of events
2466 * including http requests coming in, websocket connections becoming
2467 * established, and data arriving; it's also called periodically to allow
2468 * async transmission.
2469 *
2470 * HTTP requests are sent always to the FIRST protocol in @protocol, since
2471 * at that time websocket protocol has not been negotiated. Other
2472 * protocols after the first one never see any HTTP callack activity.
2473 *
2474 * The server created is a simple http server by default; part of the
2475 * websocket standard is upgrading this http connection to a websocket one.
2476 *
2477 * This allows the same server to provide files like scripts and favicon /
2478 * images or whatever over http and dynamic data over websockets all in
2479 * one place; they're all handled in the user callback.
Andy Greenab990e42010-10-31 12:42:52 +00002480 */
Andy Green4ea60062010-10-30 12:15:07 +01002481
Andy Greene92cd172011-01-19 13:11:55 +00002482struct libwebsocket_context *
Peter Hinz56885f32011-03-02 22:03:47 +00002483libwebsocket_create_context(int port, const char *interf,
Andy Greenb45993c2010-12-18 15:13:50 +00002484 struct libwebsocket_protocols *protocols,
Andy Greend6e09112011-03-05 16:12:15 +00002485 struct libwebsocket_extension *extensions,
Andy Green8f037e42010-12-19 22:13:26 +00002486 const char *ssl_cert_filepath,
2487 const char *ssl_private_key_filepath,
Andy Green8014b292011-01-30 20:57:25 +00002488 int gid, int uid, unsigned int options)
Andy Greenff95d7a2010-10-28 22:36:01 +01002489{
2490 int n;
Andy Greena41314f2011-05-23 10:00:03 +01002491 int m;
Andy Green4739e5c2011-01-22 12:51:57 +00002492 int sockfd = 0;
Andy Green251f6fa2010-11-03 11:13:06 +00002493 int fd;
Andy Greenff95d7a2010-10-28 22:36:01 +01002494 struct sockaddr_in serv_addr, cli_addr;
Andy Green251f6fa2010-11-03 11:13:06 +00002495 int opt = 1;
Peter Hinz56885f32011-03-02 22:03:47 +00002496 struct libwebsocket_context *context = NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002497 unsigned int slen;
Andy Green9659f372011-01-27 22:01:43 +00002498 char *p;
Andy Green2ac5a6f2011-01-28 10:00:18 +00002499 char hostname[1024];
Andy Green42f69142011-01-30 08:10:02 +00002500 struct hostent *he;
Andy Green0d338332011-02-12 11:57:43 +00002501 struct libwebsocket *wsi;
Andy Greenff95d7a2010-10-28 22:36:01 +01002502
Andy Green3faa9c72010-11-08 17:03:03 +00002503#ifdef LWS_OPENSSL_SUPPORT
Andy Greenf2f54d52010-11-15 22:08:00 +00002504 SSL_METHOD *method;
Andy Green3faa9c72010-11-08 17:03:03 +00002505 char ssl_err_buf[512];
Andy Green3faa9c72010-11-08 17:03:03 +00002506#endif
2507
Peter Hinz56885f32011-03-02 22:03:47 +00002508#ifdef _WIN32
2509 {
2510 WORD wVersionRequested;
2511 WSADATA wsaData;
2512 int err;
Andy Green6ee372f2012-04-09 15:09:01 +08002513 HMODULE wsdll;
Peter Hinz56885f32011-03-02 22:03:47 +00002514
2515 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
2516 wVersionRequested = MAKEWORD(2, 2);
2517
2518 err = WSAStartup(wVersionRequested, &wsaData);
2519 if (err != 0) {
2520 /* Tell the user that we could not find a usable */
2521 /* Winsock DLL. */
2522 fprintf(stderr, "WSAStartup failed with error: %d\n",
2523 err);
2524 return NULL;
2525 }
David Galeano7b11fec2011-10-04 19:55:18 +08002526
Andy Green6ee372f2012-04-09 15:09:01 +08002527 /* default to a poll() made out of select() */
2528 poll = emulated_poll;
David Galeano7b11fec2011-10-04 19:55:18 +08002529
Andy Green6ee372f2012-04-09 15:09:01 +08002530 /* if windows socket lib available, use his WSAPoll */
2531 wsdll = GetModuleHandle("Ws2_32.dll");
2532 if (wsdll)
2533 poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
Peter Hinz56885f32011-03-02 22:03:47 +00002534 }
2535#endif
2536
2537
2538 context = malloc(sizeof(struct libwebsocket_context));
2539 if (!context) {
Andy Green90c7cbc2011-01-27 06:26:52 +00002540 fprintf(stderr, "No memory for websocket context\n");
2541 return NULL;
2542 }
Peter Hinz56885f32011-03-02 22:03:47 +00002543 context->protocols = protocols;
2544 context->listen_port = port;
2545 context->http_proxy_port = 0;
2546 context->http_proxy_address[0] = '\0';
2547 context->options = options;
2548 context->fds_count = 0;
Andy Greend6e09112011-03-05 16:12:15 +00002549 context->extensions = extensions;
Andy Green9659f372011-01-27 22:01:43 +00002550
Peter Hinz56885f32011-03-02 22:03:47 +00002551#ifdef WIN32
2552 context->fd_random = 0;
2553#else
2554 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
2555 if (context->fd_random < 0) {
Andy Green44eee682011-02-10 09:32:24 +00002556 fprintf(stderr, "Unable to open random device %s %d\n",
Peter Hinz56885f32011-03-02 22:03:47 +00002557 SYSTEM_RANDOM_FILEPATH, context->fd_random);
Andy Green44eee682011-02-10 09:32:24 +00002558 return NULL;
2559 }
Peter Hinz56885f32011-03-02 22:03:47 +00002560#endif
Andy Green44eee682011-02-10 09:32:24 +00002561
Peter Hinz56885f32011-03-02 22:03:47 +00002562#ifdef LWS_OPENSSL_SUPPORT
2563 context->use_ssl = 0;
2564 context->ssl_ctx = NULL;
2565 context->ssl_client_ctx = NULL;
Andy Green2e24da02011-03-05 16:12:04 +00002566 openssl_websocket_private_data_index = 0;
Peter Hinz56885f32011-03-02 22:03:47 +00002567#endif
Andy Green2ac5a6f2011-01-28 10:00:18 +00002568 /* find canonical hostname */
2569
2570 hostname[(sizeof hostname) - 1] = '\0';
2571 gethostname(hostname, (sizeof hostname) - 1);
2572 he = gethostbyname(hostname);
Darin Willitsc19456f2011-02-14 17:52:39 +00002573 if (he) {
Peter Hinz56885f32011-03-02 22:03:47 +00002574 strncpy(context->canonical_hostname, he->h_name,
2575 sizeof context->canonical_hostname - 1);
2576 context->canonical_hostname[
2577 sizeof context->canonical_hostname - 1] = '\0';
Darin Willitsc19456f2011-02-14 17:52:39 +00002578 } else
Peter Hinz56885f32011-03-02 22:03:47 +00002579 strncpy(context->canonical_hostname, hostname,
2580 sizeof context->canonical_hostname - 1);
Andy Green2ac5a6f2011-01-28 10:00:18 +00002581
Andy Green9659f372011-01-27 22:01:43 +00002582 /* split the proxy ads:port if given */
2583
2584 p = getenv("http_proxy");
2585 if (p) {
Peter Hinz56885f32011-03-02 22:03:47 +00002586 strncpy(context->http_proxy_address, p,
Andy Green6ee372f2012-04-09 15:09:01 +08002587 sizeof context->http_proxy_address - 1);
Peter Hinz56885f32011-03-02 22:03:47 +00002588 context->http_proxy_address[
2589 sizeof context->http_proxy_address - 1] = '\0';
Andy Green9659f372011-01-27 22:01:43 +00002590
Peter Hinz56885f32011-03-02 22:03:47 +00002591 p = strchr(context->http_proxy_address, ':');
Andy Green9659f372011-01-27 22:01:43 +00002592 if (p == NULL) {
2593 fprintf(stderr, "http_proxy needs to be ads:port\n");
2594 return NULL;
2595 }
2596 *p = '\0';
Peter Hinz56885f32011-03-02 22:03:47 +00002597 context->http_proxy_port = atoi(p + 1);
Andy Green9659f372011-01-27 22:01:43 +00002598
2599 fprintf(stderr, "Using proxy %s:%u\n",
Peter Hinz56885f32011-03-02 22:03:47 +00002600 context->http_proxy_address,
2601 context->http_proxy_port);
Andy Green9659f372011-01-27 22:01:43 +00002602 }
Andy Green90c7cbc2011-01-27 06:26:52 +00002603
2604 if (port) {
2605
Andy Green3faa9c72010-11-08 17:03:03 +00002606#ifdef LWS_OPENSSL_SUPPORT
Peter Hinz56885f32011-03-02 22:03:47 +00002607 context->use_ssl = ssl_cert_filepath != NULL &&
Andy Green90c7cbc2011-01-27 06:26:52 +00002608 ssl_private_key_filepath != NULL;
Peter Hinz56885f32011-03-02 22:03:47 +00002609 if (context->use_ssl)
Andy Green90c7cbc2011-01-27 06:26:52 +00002610 fprintf(stderr, " Compiled with SSL support, "
2611 "using it\n");
2612 else
2613 fprintf(stderr, " Compiled with SSL support, "
2614 "not using it\n");
Andy Green3faa9c72010-11-08 17:03:03 +00002615
Andy Green90c7cbc2011-01-27 06:26:52 +00002616#else
2617 if (ssl_cert_filepath != NULL &&
2618 ssl_private_key_filepath != NULL) {
2619 fprintf(stderr, " Not compiled for OpenSSl support!\n");
Andy Greene92cd172011-01-19 13:11:55 +00002620 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002621 }
Andy Green90c7cbc2011-01-27 06:26:52 +00002622 fprintf(stderr, " Compiled without SSL support, "
2623 "serving unencrypted\n");
2624#endif
2625 }
2626
2627 /* ignore SIGPIPE */
Peter Hinz56885f32011-03-02 22:03:47 +00002628#ifdef WIN32
2629#else
Andy Green90c7cbc2011-01-27 06:26:52 +00002630 signal(SIGPIPE, sigpipe_handler);
Peter Hinz56885f32011-03-02 22:03:47 +00002631#endif
Andy Green90c7cbc2011-01-27 06:26:52 +00002632
2633
2634#ifdef LWS_OPENSSL_SUPPORT
2635
2636 /* basic openssl init */
2637
2638 SSL_library_init();
2639
2640 OpenSSL_add_all_algorithms();
2641 SSL_load_error_strings();
2642
Andy Green2e24da02011-03-05 16:12:04 +00002643 openssl_websocket_private_data_index =
Andy Green6901cb32011-02-21 08:06:47 +00002644 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
2645
Andy Green90c7cbc2011-01-27 06:26:52 +00002646 /*
2647 * Firefox insists on SSLv23 not SSLv3
2648 * Konq disables SSLv2 by default now, SSLv23 works
2649 */
2650
2651 method = (SSL_METHOD *)SSLv23_server_method();
2652 if (!method) {
2653 fprintf(stderr, "problem creating ssl method: %s\n",
2654 ERR_error_string(ERR_get_error(), ssl_err_buf));
2655 return NULL;
2656 }
Peter Hinz56885f32011-03-02 22:03:47 +00002657 context->ssl_ctx = SSL_CTX_new(method); /* create context */
2658 if (!context->ssl_ctx) {
Andy Green90c7cbc2011-01-27 06:26:52 +00002659 fprintf(stderr, "problem creating ssl context: %s\n",
2660 ERR_error_string(ERR_get_error(), ssl_err_buf));
2661 return NULL;
2662 }
2663
2664 /* client context */
Andy Green6ee372f2012-04-09 15:09:01 +08002665
2666 if (port == CONTEXT_PORT_NO_LISTEN) {
Peter Hinz56885f32011-03-02 22:03:47 +00002667 method = (SSL_METHOD *)SSLv23_client_method();
2668 if (!method) {
2669 fprintf(stderr, "problem creating ssl method: %s\n",
2670 ERR_error_string(ERR_get_error(), ssl_err_buf));
2671 return NULL;
2672 }
2673 /* create context */
2674 context->ssl_client_ctx = SSL_CTX_new(method);
2675 if (!context->ssl_client_ctx) {
2676 fprintf(stderr, "problem creating ssl context: %s\n",
2677 ERR_error_string(ERR_get_error(), ssl_err_buf));
2678 return NULL;
2679 }
Andy Green90c7cbc2011-01-27 06:26:52 +00002680
Peter Hinz56885f32011-03-02 22:03:47 +00002681 /* openssl init for cert verification (for client sockets) */
Andy Green90c7cbc2011-01-27 06:26:52 +00002682
Peter Hinz56885f32011-03-02 22:03:47 +00002683 if (!SSL_CTX_load_verify_locations(
2684 context->ssl_client_ctx, NULL,
2685 LWS_OPENSSL_CLIENT_CERTS))
2686 fprintf(stderr,
2687 "Unable to load SSL Client certs from %s "
2688 "(set by --with-client-cert-dir= in configure) -- "
2689 " client ssl isn't going to work",
Andy Green90c7cbc2011-01-27 06:26:52 +00002690 LWS_OPENSSL_CLIENT_CERTS);
Peter Hinz56885f32011-03-02 22:03:47 +00002691
2692 /*
2693 * callback allowing user code to load extra verification certs
2694 * helping the client to verify server identity
2695 */
2696
2697 context->protocols[0].callback(context, NULL,
2698 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
2699 context->ssl_client_ctx, NULL, 0);
Andy Green90c7cbc2011-01-27 06:26:52 +00002700 }
Andy Green6ee372f2012-04-09 15:09:01 +08002701
Andy Greenc6bf2c22011-02-20 11:10:47 +00002702 /* as a server, are we requiring clients to identify themselves? */
2703
2704 if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
2705
2706 /* absolutely require the client cert */
Andy Green6ee372f2012-04-09 15:09:01 +08002707
Peter Hinz56885f32011-03-02 22:03:47 +00002708 SSL_CTX_set_verify(context->ssl_ctx,
Andy Green6901cb32011-02-21 08:06:47 +00002709 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2710 OpenSSL_verify_callback);
Andy Greenc6bf2c22011-02-20 11:10:47 +00002711
2712 /*
2713 * give user code a chance to load certs into the server
2714 * allowing it to verify incoming client certs
2715 */
2716
Peter Hinz56885f32011-03-02 22:03:47 +00002717 context->protocols[0].callback(context, NULL,
Andy Greenc6bf2c22011-02-20 11:10:47 +00002718 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
Peter Hinz56885f32011-03-02 22:03:47 +00002719 context->ssl_ctx, NULL, 0);
Andy Greenc6bf2c22011-02-20 11:10:47 +00002720 }
2721
Peter Hinz56885f32011-03-02 22:03:47 +00002722 if (context->use_ssl) {
Andy Green90c7cbc2011-01-27 06:26:52 +00002723
2724 /* openssl init for server sockets */
2725
Andy Green3faa9c72010-11-08 17:03:03 +00002726 /* set the local certificate from CertFile */
Peter Hinz56885f32011-03-02 22:03:47 +00002727 n = SSL_CTX_use_certificate_file(context->ssl_ctx,
Andy Green3faa9c72010-11-08 17:03:03 +00002728 ssl_cert_filepath, SSL_FILETYPE_PEM);
2729 if (n != 1) {
2730 fprintf(stderr, "problem getting cert '%s': %s\n",
2731 ssl_cert_filepath,
2732 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00002733 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002734 }
2735 /* set the private key from KeyFile */
Peter Hinz56885f32011-03-02 22:03:47 +00002736 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2737 ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
Andy Green018d8eb2010-11-08 21:04:23 +00002738 fprintf(stderr, "ssl problem getting key '%s': %s\n",
2739 ssl_private_key_filepath,
2740 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00002741 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002742 }
2743 /* verify private key */
Peter Hinz56885f32011-03-02 22:03:47 +00002744 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
Andy Green018d8eb2010-11-08 21:04:23 +00002745 fprintf(stderr, "Private SSL key doesn't match cert\n");
Andy Greene92cd172011-01-19 13:11:55 +00002746 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002747 }
2748
2749 /* SSL is happy and has a cert it's content with */
2750 }
2751#endif
Andy Greenb45993c2010-12-18 15:13:50 +00002752
Andy Greendf736162011-01-18 15:39:02 +00002753 /* selftest */
2754
2755 if (lws_b64_selftest())
Andy Greene92cd172011-01-19 13:11:55 +00002756 return NULL;
Andy Greendf736162011-01-18 15:39:02 +00002757
Andy Green0d338332011-02-12 11:57:43 +00002758 /* fd hashtable init */
2759
2760 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
Peter Hinz56885f32011-03-02 22:03:47 +00002761 context->fd_hashtable[n].length = 0;
Andy Green0d338332011-02-12 11:57:43 +00002762
Andy Greenb45993c2010-12-18 15:13:50 +00002763 /* set up our external listening socket we serve on */
Andy Green8f037e42010-12-19 22:13:26 +00002764
Andy Green4739e5c2011-01-22 12:51:57 +00002765 if (port) {
Andy Green8f037e42010-12-19 22:13:26 +00002766
Andy Green4739e5c2011-01-22 12:51:57 +00002767 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2768 if (sockfd < 0) {
2769 fprintf(stderr, "ERROR opening socket");
2770 return NULL;
2771 }
Andy Green775c0dd2010-10-29 14:15:22 +01002772
Andy Green4739e5c2011-01-22 12:51:57 +00002773 /* allow us to restart even if old sockets in TIME_WAIT */
Andy Green6ee372f2012-04-09 15:09:01 +08002774 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
2775 (const void *)&opt, sizeof(opt));
Andy Green6c939552011-03-08 08:56:57 +00002776
2777 /* Disable Nagle */
2778 opt = 1;
Andy Green6ee372f2012-04-09 15:09:01 +08002779 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
2780 (const void *)&opt, sizeof(opt));
Andy Green6c939552011-03-08 08:56:57 +00002781
Andy Green4739e5c2011-01-22 12:51:57 +00002782 bzero((char *) &serv_addr, sizeof(serv_addr));
2783 serv_addr.sin_family = AF_INET;
Peter Hinz56885f32011-03-02 22:03:47 +00002784 if (interf == NULL)
Andy Green32375b72011-02-19 08:32:53 +00002785 serv_addr.sin_addr.s_addr = INADDR_ANY;
2786 else
Peter Hinz56885f32011-03-02 22:03:47 +00002787 interface_to_sa(interf, &serv_addr,
Andy Green32375b72011-02-19 08:32:53 +00002788 sizeof(serv_addr));
Andy Green4739e5c2011-01-22 12:51:57 +00002789 serv_addr.sin_port = htons(port);
2790
2791 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2792 sizeof(serv_addr));
2793 if (n < 0) {
2794 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Green8f037e42010-12-19 22:13:26 +00002795 port, n, errno);
Andy Green4739e5c2011-01-22 12:51:57 +00002796 return NULL;
2797 }
Andy Green0d338332011-02-12 11:57:43 +00002798
2799 wsi = malloc(sizeof(struct libwebsocket));
Andy Green6ee372f2012-04-09 15:09:01 +08002800 memset(wsi, 0, sizeof(struct libwebsocket));
Andy Green0d338332011-02-12 11:57:43 +00002801 wsi->sock = sockfd;
Andy Greend6e09112011-03-05 16:12:15 +00002802 wsi->count_active_extensions = 0;
Andy Green0d338332011-02-12 11:57:43 +00002803 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
Peter Hinz56885f32011-03-02 22:03:47 +00002804 insert_wsi(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00002805
2806 listen(sockfd, 5);
2807 fprintf(stderr, " Listening on port %d\n", port);
2808
2809 /* list in the internal poll array */
Andy Green6ee372f2012-04-09 15:09:01 +08002810
Peter Hinz56885f32011-03-02 22:03:47 +00002811 context->fds[context->fds_count].fd = sockfd;
2812 context->fds[context->fds_count++].events = POLLIN;
Andy Green3221f922011-02-12 13:14:11 +00002813
2814 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002815 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002816 LWS_CALLBACK_ADD_POLL_FD,
2817 (void *)(long)sockfd, NULL, POLLIN);
2818
Andy Green8f037e42010-12-19 22:13:26 +00002819 }
Andy Greenb45993c2010-12-18 15:13:50 +00002820
Andy Green6ee372f2012-04-09 15:09:01 +08002821 /*
2822 * drop any root privs for this process
2823 * to listen on port < 1023 we would have needed root, but now we are
2824 * listening, we don't want the power for anything else
2825 */
Peter Hinz56885f32011-03-02 22:03:47 +00002826#ifdef WIN32
2827#else
Andy Green3faa9c72010-11-08 17:03:03 +00002828 if (gid != -1)
2829 if (setgid(gid))
2830 fprintf(stderr, "setgid: %s\n", strerror(errno));
2831 if (uid != -1)
2832 if (setuid(uid))
2833 fprintf(stderr, "setuid: %s\n", strerror(errno));
Peter Hinz56885f32011-03-02 22:03:47 +00002834#endif
Andy Greenb45993c2010-12-18 15:13:50 +00002835
2836 /* set up our internal broadcast trigger sockets per-protocol */
2837
Peter Hinz56885f32011-03-02 22:03:47 +00002838 for (context->count_protocols = 0;
2839 protocols[context->count_protocols].callback;
2840 context->count_protocols++) {
Andy Green2d1301e2011-05-24 10:14:41 +01002841
Andy Green6ee372f2012-04-09 15:09:01 +08002842 fprintf(stderr, " Protocol: %s\n",
2843 protocols[context->count_protocols].name);
Andy Green2d1301e2011-05-24 10:14:41 +01002844
Peter Hinz56885f32011-03-02 22:03:47 +00002845 protocols[context->count_protocols].owning_server = context;
2846 protocols[context->count_protocols].protocol_index =
2847 context->count_protocols;
Andy Greenb45993c2010-12-18 15:13:50 +00002848
2849 fd = socket(AF_INET, SOCK_STREAM, 0);
2850 if (fd < 0) {
2851 fprintf(stderr, "ERROR opening socket");
Andy Greene92cd172011-01-19 13:11:55 +00002852 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002853 }
Andy Green8f037e42010-12-19 22:13:26 +00002854
Andy Greenb45993c2010-12-18 15:13:50 +00002855 /* allow us to restart even if old sockets in TIME_WAIT */
Andy Green6ee372f2012-04-09 15:09:01 +08002856 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt,
2857 sizeof(opt));
Andy Greenb45993c2010-12-18 15:13:50 +00002858
2859 bzero((char *) &serv_addr, sizeof(serv_addr));
2860 serv_addr.sin_family = AF_INET;
2861 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2862 serv_addr.sin_port = 0; /* pick the port for us */
2863
2864 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2865 if (n < 0) {
Andy Green8f037e42010-12-19 22:13:26 +00002866 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Greenb45993c2010-12-18 15:13:50 +00002867 port, n, errno);
Andy Greene92cd172011-01-19 13:11:55 +00002868 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002869 }
2870
2871 slen = sizeof cli_addr;
2872 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2873 if (n < 0) {
2874 fprintf(stderr, "getsockname failed\n");
Andy Greene92cd172011-01-19 13:11:55 +00002875 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002876 }
Peter Hinz56885f32011-03-02 22:03:47 +00002877 protocols[context->count_protocols].broadcast_socket_port =
Andy Greenb45993c2010-12-18 15:13:50 +00002878 ntohs(cli_addr.sin_port);
2879 listen(fd, 5);
2880
2881 debug(" Protocol %s broadcast socket %d\n",
Peter Hinz56885f32011-03-02 22:03:47 +00002882 protocols[context->count_protocols].name,
Andy Greenb45993c2010-12-18 15:13:50 +00002883 ntohs(cli_addr.sin_port));
2884
Andy Green0d338332011-02-12 11:57:43 +00002885 /* dummy wsi per broadcast proxy socket */
2886
2887 wsi = malloc(sizeof(struct libwebsocket));
Andy Green6ee372f2012-04-09 15:09:01 +08002888 memset(wsi, 0, sizeof(struct libwebsocket));
Andy Green0d338332011-02-12 11:57:43 +00002889 wsi->sock = fd;
2890 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
Andy Greend6e09112011-03-05 16:12:15 +00002891 wsi->count_active_extensions = 0;
Andy Green0d338332011-02-12 11:57:43 +00002892 /* note which protocol we are proxying */
Peter Hinz56885f32011-03-02 22:03:47 +00002893 wsi->protocol_index_for_broadcast_proxy =
2894 context->count_protocols;
2895 insert_wsi(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00002896
2897 /* list in internal poll array */
2898
Peter Hinz56885f32011-03-02 22:03:47 +00002899 context->fds[context->fds_count].fd = fd;
2900 context->fds[context->fds_count].events = POLLIN;
2901 context->fds[context->fds_count].revents = 0;
2902 context->fds_count++;
Andy Green3221f922011-02-12 13:14:11 +00002903
2904 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002905 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002906 LWS_CALLBACK_ADD_POLL_FD,
2907 (void *)(long)fd, NULL, POLLIN);
Andy Greenb45993c2010-12-18 15:13:50 +00002908 }
2909
Andy Greena41314f2011-05-23 10:00:03 +01002910 /*
2911 * give all extensions a chance to create any per-context
2912 * allocations they need
2913 */
2914
2915 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
2916 if (port)
2917 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
2918 while (extensions->callback) {
Andy Green2d1301e2011-05-24 10:14:41 +01002919 fprintf(stderr, " Extension: %s\n", extensions->name);
Andy Greena41314f2011-05-23 10:00:03 +01002920 extensions->callback(context, extensions,
2921 NULL, m, NULL, NULL, 0);
2922 extensions++;
2923 }
2924
Peter Hinz56885f32011-03-02 22:03:47 +00002925 return context;
Andy Greene92cd172011-01-19 13:11:55 +00002926}
Andy Greenb45993c2010-12-18 15:13:50 +00002927
Andy Green4739e5c2011-01-22 12:51:57 +00002928
Andy Greened11a022011-01-20 10:23:50 +00002929#ifndef LWS_NO_FORK
2930
Andy Greene92cd172011-01-19 13:11:55 +00002931/**
2932 * libwebsockets_fork_service_loop() - Optional helper function forks off
2933 * a process for the websocket server loop.
Andy Green6964bb52011-01-23 16:50:33 +00002934 * You don't have to use this but if not, you
2935 * have to make sure you are calling
2936 * libwebsocket_service periodically to service
2937 * the websocket traffic
Peter Hinz56885f32011-03-02 22:03:47 +00002938 * @context: server context returned by creation function
Andy Greene92cd172011-01-19 13:11:55 +00002939 */
Andy Greenb45993c2010-12-18 15:13:50 +00002940
Andy Greene92cd172011-01-19 13:11:55 +00002941int
Peter Hinz56885f32011-03-02 22:03:47 +00002942libwebsockets_fork_service_loop(struct libwebsocket_context *context)
Andy Greene92cd172011-01-19 13:11:55 +00002943{
Andy Greene92cd172011-01-19 13:11:55 +00002944 int fd;
2945 struct sockaddr_in cli_addr;
2946 int n;
Andy Green3221f922011-02-12 13:14:11 +00002947 int p;
Andy Greenb45993c2010-12-18 15:13:50 +00002948
Andy Greened11a022011-01-20 10:23:50 +00002949 n = fork();
2950 if (n < 0)
2951 return n;
2952
2953 if (!n) {
2954
2955 /* main process context */
2956
Andy Green3221f922011-02-12 13:14:11 +00002957 /*
2958 * set up the proxy sockets to allow broadcast from
2959 * service process context
2960 */
2961
Peter Hinz56885f32011-03-02 22:03:47 +00002962 for (p = 0; p < context->count_protocols; p++) {
Andy Greened11a022011-01-20 10:23:50 +00002963 fd = socket(AF_INET, SOCK_STREAM, 0);
2964 if (fd < 0) {
2965 fprintf(stderr, "Unable to create socket\n");
2966 return -1;
2967 }
2968 cli_addr.sin_family = AF_INET;
2969 cli_addr.sin_port = htons(
Peter Hinz56885f32011-03-02 22:03:47 +00002970 context->protocols[p].broadcast_socket_port);
Andy Greened11a022011-01-20 10:23:50 +00002971 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2972 n = connect(fd, (struct sockaddr *)&cli_addr,
2973 sizeof cli_addr);
2974 if (n < 0) {
2975 fprintf(stderr, "Unable to connect to "
2976 "broadcast socket %d, %s\n",
Andy Green3221f922011-02-12 13:14:11 +00002977 n, strerror(errno));
Andy Greened11a022011-01-20 10:23:50 +00002978 return -1;
2979 }
2980
Peter Hinz56885f32011-03-02 22:03:47 +00002981 context->protocols[p].broadcast_socket_user_fd = fd;
Andy Greened11a022011-01-20 10:23:50 +00002982 }
2983
Andy Greene92cd172011-01-19 13:11:55 +00002984 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +00002985 }
2986
2987 /* we want a SIGHUP when our parent goes down */
2988 prctl(PR_SET_PDEATHSIG, SIGHUP);
2989
2990 /* in this forked process, sit and service websocket connections */
Andy Green8f037e42010-12-19 22:13:26 +00002991
Andy Greene92cd172011-01-19 13:11:55 +00002992 while (1)
Peter Hinz56885f32011-03-02 22:03:47 +00002993 if (libwebsocket_service(context, 1000))
Andy Greene92cd172011-01-19 13:11:55 +00002994 return -1;
Andy Green8f037e42010-12-19 22:13:26 +00002995
Andy Green251f6fa2010-11-03 11:13:06 +00002996 return 0;
Andy Greenff95d7a2010-10-28 22:36:01 +01002997}
2998
Andy Greened11a022011-01-20 10:23:50 +00002999#endif
3000
Andy Greenb45993c2010-12-18 15:13:50 +00003001/**
3002 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
Andy Green8f037e42010-12-19 22:13:26 +00003003 * connection.
Andy Greenb45993c2010-12-18 15:13:50 +00003004 * @wsi: pointer to struct websocket you want to know the protocol of
3005 *
Andy Green8f037e42010-12-19 22:13:26 +00003006 *
3007 * This is useful to get the protocol to broadcast back to from inside
Andy Greenb45993c2010-12-18 15:13:50 +00003008 * the callback.
3009 */
Andy Greenab990e42010-10-31 12:42:52 +00003010
Andy Greenb45993c2010-12-18 15:13:50 +00003011const struct libwebsocket_protocols *
3012libwebsockets_get_protocol(struct libwebsocket *wsi)
3013{
3014 return wsi->protocol;
3015}
3016
3017/**
Andy Greene92cd172011-01-19 13:11:55 +00003018 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
Andy Green8f037e42010-12-19 22:13:26 +00003019 * connections of the given protocol.
Andy Greenb45993c2010-12-18 15:13:50 +00003020 * @protocol: pointer to the protocol you will broadcast to all members of
3021 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
Andy Green8f037e42010-12-19 22:13:26 +00003022 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
3023 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
3024 * case you are calling this function from callback context.
Andy Greenb45993c2010-12-18 15:13:50 +00003025 * @len: length of payload data in buf, starting from buf.
Andy Green8f037e42010-12-19 22:13:26 +00003026 *
3027 * This function allows bulk sending of a packet to every connection using
Andy Greenb45993c2010-12-18 15:13:50 +00003028 * the given protocol. It does not send the data directly; instead it calls
3029 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
3030 * wants to actually send the data for that connection, the callback itself
3031 * should call libwebsocket_write().
3032 *
3033 * libwebsockets_broadcast() can be called from another fork context without
3034 * having to take any care about data visibility between the processes, it'll
3035 * "just work".
3036 */
3037
3038
3039int
Andy Green8f037e42010-12-19 22:13:26 +00003040libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
Andy Greenb45993c2010-12-18 15:13:50 +00003041 unsigned char *buf, size_t len)
3042{
Peter Hinz56885f32011-03-02 22:03:47 +00003043 struct libwebsocket_context *context = protocol->owning_server;
Andy Greenb45993c2010-12-18 15:13:50 +00003044 int n;
Andy Green0d338332011-02-12 11:57:43 +00003045 int m;
Andy Green6ee372f2012-04-09 15:09:01 +08003046 struct libwebsocket *wsi;
Andy Greenb45993c2010-12-18 15:13:50 +00003047
3048 if (!protocol->broadcast_socket_user_fd) {
3049 /*
Andy Greene92cd172011-01-19 13:11:55 +00003050 * We are either running unforked / flat, or we are being
3051 * called from poll thread context
Andy Greenb45993c2010-12-18 15:13:50 +00003052 * eg, from a callback. In that case don't use sockets for
3053 * broadcast IPC (since we can't open a socket connection to
3054 * a socket listening on our own thread) but directly do the
3055 * send action.
3056 *
3057 * Locking is not needed because we are by definition being
3058 * called in the poll thread context and are serialized.
3059 */
3060
Andy Green0d338332011-02-12 11:57:43 +00003061 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Greenb45993c2010-12-18 15:13:50 +00003062
Peter Hinz56885f32011-03-02 22:03:47 +00003063 for (m = 0; m < context->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +00003064
Peter Hinz56885f32011-03-02 22:03:47 +00003065 wsi = context->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +00003066
Andy Green0d338332011-02-12 11:57:43 +00003067 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
3068 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00003069
Andy Green0d338332011-02-12 11:57:43 +00003070 /*
3071 * never broadcast to
3072 * non-established connections
3073 */
3074 if (wsi->state != WSI_STATE_ESTABLISHED)
3075 continue;
3076
3077 /* only broadcast to guys using
3078 * requested protocol
3079 */
3080 if (wsi->protocol != protocol)
3081 continue;
3082
Peter Hinz56885f32011-03-02 22:03:47 +00003083 wsi->protocol->callback(context, wsi,
Andy Green8f037e42010-12-19 22:13:26 +00003084 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +00003085 wsi->user_space,
Andy Greenb45993c2010-12-18 15:13:50 +00003086 buf, len);
Andy Green0d338332011-02-12 11:57:43 +00003087 }
Andy Greenb45993c2010-12-18 15:13:50 +00003088 }
3089
3090 return 0;
3091 }
3092
Andy Green0ca6a172010-12-19 20:50:01 +00003093 /*
3094 * We're being called from a different process context than the server
3095 * loop. Instead of broadcasting directly, we send our
3096 * payload on a socket to do the IPC; the server process will serialize
3097 * the broadcast action in its main poll() loop.
3098 *
3099 * There's one broadcast socket listening for each protocol supported
3100 * set up when the websocket server initializes
3101 */
3102
Andy Green6964bb52011-01-23 16:50:33 +00003103 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
Andy Greenb45993c2010-12-18 15:13:50 +00003104
3105 return n;
3106}
Andy Green82c3d542011-03-07 21:16:31 +00003107
3108int
3109libwebsocket_is_final_fragment(struct libwebsocket *wsi)
3110{
3111 return wsi->final;
3112}
Alex Bligh49146db2011-11-07 17:19:25 +08003113
3114void *
3115libwebsocket_ensure_user_space(struct libwebsocket *wsi)
3116{
3117 /* allocate the per-connection user memory (if any) */
3118
3119 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
3120 wsi->user_space = malloc(
3121 wsi->protocol->per_session_data_size);
3122 if (wsi->user_space == NULL) {
3123 fprintf(stderr, "Out of memory for "
3124 "conn user space\n");
3125 return NULL;
3126 }
Andy Green6ee372f2012-04-09 15:09:01 +08003127 memset(wsi->user_space, 0,
3128 wsi->protocol->per_session_data_size);
Alex Bligh49146db2011-11-07 17:19:25 +08003129 }
3130 return wsi->user_space;
3131}