debug move most spew into debug macro
[profile/ivi/libwebsockets.git] / lib / libwebsockets.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * 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
20  */
21
22 #include "private-libwebsockets.h"
23
24 #ifdef WIN32
25
26 #else
27 #include <ifaddrs.h>
28 #include <sys/un.h>
29 #endif
30
31 #ifdef LWS_OPENSSL_SUPPORT
32 int openssl_websocket_private_data_index;
33 #endif
34
35 /*
36  * In-place str to lower case
37  */
38
39 static void
40 strtolower(char *s)
41 {
42         while (*s) {
43                 *s = tolower(*s);
44                 s++;
45         }
46 }
47
48 /* file descriptor hash management */
49
50 struct libwebsocket *
51 wsi_from_fd(struct libwebsocket_context *context, int fd)
52 {
53         int h = LWS_FD_HASH(fd);
54         int n = 0;
55
56         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];
59
60         return NULL;
61 }
62
63 int
64 insert_wsi(struct libwebsocket_context *context, struct libwebsocket *wsi)
65 {
66         int h = LWS_FD_HASH(wsi->sock);
67
68         if (context->fd_hashtable[h].length == MAX_CLIENTS - 1) {
69                 fprintf(stderr, "hash table overflow\n");
70                 return 1;
71         }
72
73         context->fd_hashtable[h].wsi[context->fd_hashtable[h].length++] = wsi;
74
75         return 0;
76 }
77
78 int
79 delete_from_fd(struct libwebsocket_context *context, int fd)
80 {
81         int h = LWS_FD_HASH(fd);
82         int n = 0;
83
84         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];
89                                 n++;
90                         }
91                         context->fd_hashtable[h].length--;
92
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
101 #ifdef LWS_OPENSSL_SUPPORT
102 static void
103 libwebsockets_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
114
115
116 static int
117 interface_to_sa(const char* ifname, struct sockaddr_in *addr, size_t addrlen)
118 {
119         int rc = -1;
120 #ifdef WIN32
121         // TODO
122 #else
123         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);
137                 rc = 0; 
138         }
139
140         freeifaddrs(ifr);
141 #endif
142         return rc;
143 }
144
145 void
146 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
147                          struct libwebsocket *wsi, enum lws_close_status reason)
148 {
149         int n;
150         int old_state;
151         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
152                                                   LWS_SEND_BUFFER_POST_PADDING];
153         int ret;
154         int m;
155         struct lws_tokens eff_buf;
156         struct libwebsocket_extension *ext;
157
158         if (!wsi)
159                 return;
160
161         old_state = wsi->state;
162
163         if (old_state == WSI_STATE_DEAD_SOCKET)
164                 return;
165
166         wsi->close_reason = reason;
167
168         /*
169          * 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) {
190                         debug("extension vetoed close\n");
191                         return;
192                 }
193         }
194
195
196
197         /*
198          * 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(
215                                         wsi->protocol->owning_server,
216                                         wsi->active_extensions[n], wsi,
217                                         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         /*
241          * 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) {
254
255                 debug("sending close indication...\n");
256
257                 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
272                         debug("sent close indication, awaiting ack\n");
273
274                         return;
275                 }
276
277                 /* else, the send failed and we should just hang up */
278         }
279
280 just_kill_connection:
281
282         debug("libwebsocket_close_and_free_session: just_kill_connection\n");
283
284         /*
285          * we won't be servicing or receiving anything further from this guy
286          * remove this fd from wsi mapping hashtable
287          */
288
289         if (wsi->sock)
290                 delete_from_fd(context, wsi->sock);
291
292         /* delete it from the internal poll list if still present */
293
294         for (n = 0; n < context->fds_count; n++) {
295                 if (context->fds[n].fd != wsi->sock)
296                         continue;
297                 while (n < context->fds_count - 1) {
298                         context->fds[n] = context->fds[n + 1];
299                         n++;
300                 }
301                 context->fds_count--;
302                 /* we only have to deal with one */
303                 n = context->fds_count;
304         }
305
306         /* remove also from external POLL support via protocol 0 */
307         if (wsi->sock)
308                 context->protocols[0].callback(context, wsi,
309                     LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
310
311         wsi->state = WSI_STATE_DEAD_SOCKET;
312
313         /* tell the user it's all over for this guy */
314
315         if (wsi->protocol && wsi->protocol->callback &&
316                                 ((old_state == WSI_STATE_ESTABLISHED) ||
317                                  (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
318                                  (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
319                 debug("calling back CLOSED\n");
320                 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
321                                                       wsi->user_space, NULL, 0);
322         } else
323                 debug("not calling back closed due to old_state=%d\n",
324                                                                      old_state);
325
326
327         /* deallocate any active extension contexts */
328
329         for (n = 0; n < wsi->count_active_extensions; n++) {
330                 if (!wsi->active_extensions[n]->callback)
331                         continue;
332
333                 wsi->active_extensions[n]->callback(context,
334                         wsi->active_extensions[n], wsi,
335                                 LWS_EXT_CALLBACK_DESTROY,
336                                        wsi->active_extensions_user[n], NULL, 0);
337
338                 free(wsi->active_extensions_user[n]);
339         }
340
341         /*
342          * inform all extensions in case they tracked this guy out of band
343          * even though not active on him specifically
344          */
345
346         ext = context->extensions;
347         while (ext && ext->callback) {
348                 ext->callback(context, ext, wsi,
349                                 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
350                                        NULL, NULL, 0);
351                 ext++;
352         }
353
354         /* free up his parsing allocations */
355
356         for (n = 0; n < WSI_TOKEN_COUNT; n++)
357                 if (wsi->utf8_token[n].token)
358                         free(wsi->utf8_token[n].token);
359
360         if (wsi->c_address)
361                 free(wsi->c_address);
362
363 /*      fprintf(stderr, "closing fd=%d\n", wsi->sock); */
364
365 #ifdef LWS_OPENSSL_SUPPORT
366         if (wsi->ssl) {
367                 n = SSL_get_fd(wsi->ssl);
368                 SSL_shutdown(wsi->ssl);
369 #ifdef WIN32
370                 closesocket(n);
371 #else
372                 close(n);
373 #endif
374                 SSL_free(wsi->ssl);
375         } else {
376 #endif
377                 shutdown(wsi->sock, SHUT_RDWR);
378 #ifdef WIN32
379                 if (wsi->sock)
380                         closesocket(wsi->sock);
381 #else
382                 if (wsi->sock)
383                         close(wsi->sock);
384 #endif
385 #ifdef LWS_OPENSSL_SUPPORT
386         }
387 #endif
388         if (wsi->user_space)
389                 free(wsi->user_space);
390
391         free(wsi);
392 }
393
394 /**
395  * libwebsockets_hangup_on_client() - Server calls to terminate client
396  *                                      connection
397  * @context:    libwebsockets context
398  * @fd:         Connection socket descriptor
399  */
400
401 void
402 libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
403 {
404         struct libwebsocket *wsi = wsi_from_fd(context, fd);
405
406         if (wsi == NULL)
407                 return;
408
409         libwebsocket_close_and_free_session(context, wsi,
410                                                      LWS_CLOSE_STATUS_NOSTATUS);
411 }
412
413
414 /**
415  * libwebsockets_get_peer_addresses() - Get client address information
416  * @fd:         Connection socket descriptor
417  * @name:       Buffer to take client address name
418  * @name_len:   Length of client address name buffer
419  * @rip:        Buffer to take client address IP qotted quad
420  * @rip_len:    Length of client address IP buffer
421  *
422  *      This function fills in @name and @rip with the name and IP of
423  *      the client connected with socket descriptor @fd.  Names may be
424  *      truncated if there is not enough room.  If either cannot be
425  *      determined, they will be returned as valid zero-length strings.
426  */
427
428 void
429 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
430                                         char *rip, int rip_len)
431 {
432         unsigned int len;
433         struct sockaddr_in sin;
434         struct hostent *host;
435         struct hostent *host1;
436         char ip[128];
437         unsigned char *p;
438         int n;
439         struct sockaddr_un *un;
440
441         rip[0] = '\0';
442         name[0] = '\0';
443
444         len = sizeof sin;
445         if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
446                 perror("getpeername");
447                 return;
448         }
449                 
450         host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
451                                                                        AF_INET);
452         if (host == NULL) {
453                 perror("gethostbyaddr");
454                 return;
455         }
456
457         strncpy(name, host->h_name, name_len);
458         name[name_len - 1] = '\0';
459
460         host1 = gethostbyname(host->h_name);
461         if (host1 == NULL)
462                 return;
463         p = (unsigned char *)host1;
464         n = 0;
465         while (p != NULL) {
466                 p = (unsigned char *)host1->h_addr_list[n++];
467                 if (p == NULL)
468                         continue;
469                 if ((host1->h_addrtype != AF_INET)
470 #ifdef AF_LOCAL
471                         && (host1->h_addrtype != AF_LOCAL)
472 #endif
473                         )
474                         continue;
475
476                 if (host1->h_addrtype == AF_INET)
477                         sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
478 #ifdef AF_LOCAL
479                 else {
480                         un = (struct sockaddr_un *)p;
481                         strncpy(ip, un->sun_path, sizeof(ip) -1);
482                         ip[sizeof(ip) - 1] = '\0';
483                 }
484 #endif
485                 p = NULL;
486                 strncpy(rip, ip, rip_len);
487                 rip[rip_len - 1] = '\0';
488         }
489 }
490
491 int libwebsockets_get_random(struct libwebsocket_context *context,
492                                                              void *buf, int len)
493 {
494         int n;
495         char *p = buf;
496
497 #ifdef WIN32
498         for (n = 0; n < len; n++)
499                 p[n] = (unsigned char)rand();
500 #else
501         n = read(context->fd_random, p, len);
502 #endif
503
504         return n;
505 }
506
507 unsigned char *
508 libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md)
509 {
510         return SHA1(d, n, md);
511 }
512
513 void libwebsockets_00_spaceout(char *key, int spaces, int seed)
514 {
515         char *p;
516         
517         key++;
518         while (spaces--) {
519                 if (*key && (seed & 1))
520                         key++;
521                 seed >>= 1;
522                 
523                 p = key + strlen(key);
524                 while (p >= key) {
525                         p[1] = p[0];
526                         p--;
527                 }
528                 *key++ = ' ';
529         }
530 }
531
532 void libwebsockets_00_spam(char *key, int count, int seed)
533 {
534         char *p;
535
536         key++;
537         while (count--) {
538                 
539                 if (*key && (seed & 1))
540                         key++;
541                 seed >>= 1;
542
543                 p = key + strlen(key);
544                 while (p >= key) {
545                         p[1] = p[0];
546                         p--;
547                 }
548                 *key++ = 0x21 + ((seed & 0xffff) % 15);
549                 /* 4 would use it up too fast.. not like it matters */
550                 seed >>= 1;
551         }
552 }
553
554 int lws_send_pipe_choked(struct libwebsocket *wsi)
555 {
556         struct pollfd fds;
557
558         fds.fd = wsi->sock;
559         fds.events = POLLOUT;
560         fds.revents = 0;
561
562         if (poll(&fds, 1, 0) != 1)
563                 return 1;
564
565         if ((fds.revents & POLLOUT) == 0)
566                 return 1;
567
568         /* okay to send another packet without blocking */
569
570         return 0;
571 }
572
573 int
574 lws_handle_POLLOUT_event(struct libwebsocket_context *context,
575                                 struct libwebsocket *wsi, struct pollfd *pollfd)
576 {
577         struct lws_tokens eff_buf;
578         int n;
579         int ret;
580         int m;
581         int handled = 0;
582
583         for (n = 0; n < wsi->count_active_extensions; n++) {
584                 if (!wsi->active_extensions[n]->callback)
585                         continue;
586
587                 m = wsi->active_extensions[n]->callback(context,
588                         wsi->active_extensions[n], wsi,
589                         LWS_EXT_CALLBACK_IS_WRITEABLE,
590                                        wsi->active_extensions_user[n], NULL, 0);
591                 if (m > handled)
592                         handled = m;
593         }
594
595         if (handled == 1)
596                 goto notify_action;
597
598         if (!wsi->extension_data_pending || handled == 2)
599                 goto user_service;
600
601         /*
602          * check in on the active extensions, see if they
603          * had pending stuff to spill... they need to get the
604          * first look-in otherwise sequence will be disordered
605          *
606          * NULL, zero-length eff_buf means just spill pending
607          */
608
609         ret = 1;
610         while (ret == 1) {
611
612                 /* default to nobody has more to spill */
613
614                 ret = 0;
615                 eff_buf.token = NULL;
616                 eff_buf.token_len = 0;
617
618                 /* give every extension a chance to spill */
619
620                 for (n = 0; n < wsi->count_active_extensions; n++) {
621                         m = wsi->active_extensions[n]->callback(
622                                 wsi->protocol->owning_server,
623                                 wsi->active_extensions[n], wsi,
624                                         LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
625                                    wsi->active_extensions_user[n], &eff_buf, 0);
626                         if (m < 0) {
627                                 fprintf(stderr, "extension reports fatal error\n");
628                                 return -1;
629                         }
630                         if (m)
631                                 /*
632                                  * at least one extension told us he has more
633                                  * to spill, so we will go around again after
634                                  */
635                                 ret = 1;
636                 }
637
638                 /* assuming they gave us something to send, send it */
639
640                 if (eff_buf.token_len) {
641                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
642                                                              eff_buf.token_len))
643                                 return -1;
644                 } else
645                         continue;
646
647                 /* no extension has more to spill */
648
649                 if (!ret)
650                         continue;
651
652                 /*
653                  * There's more to spill from an extension, but we just sent
654                  * something... did that leave the pipe choked?
655                  */
656
657                 if (!lws_send_pipe_choked(wsi))
658                         /* no we could add more */
659                         continue;
660
661                 debug("choked in POLLOUT service\n");
662
663                 /*
664                  * Yes, he's choked.  Leave the POLLOUT masked on so we will
665                  * come back here when he is unchoked.  Don't call the user
666                  * callback to enforce ordering of spilling, he'll get called
667                  * when we come back here and there's nothing more to spill.
668                  */
669
670                 return 0;
671         }
672
673         wsi->extension_data_pending = 0;
674
675 user_service:
676         /* one shot */
677
678         if (pollfd) {
679                 pollfd->events &= ~POLLOUT;
680
681                 /* external POLL support via protocol 0 */
682                 context->protocols[0].callback(context, wsi,
683                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
684                         (void *)(long)wsi->sock, NULL, POLLOUT);
685         }
686
687 notify_action:
688
689         if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
690                 n = LWS_CALLBACK_CLIENT_WRITEABLE;
691         else
692                 n = LWS_CALLBACK_SERVER_WRITEABLE;
693
694         wsi->protocol->callback(context, wsi, n, wsi->user_space, NULL, 0);
695
696         return 0;
697 }
698
699
700
701 void
702 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
703                                      struct libwebsocket *wsi, unsigned int sec)
704 {
705         int n;
706
707         /*
708          * if extensions want in on it (eg, we are a mux parent)
709          * give them a chance to service child timeouts
710          */
711
712         for (n = 0; n < wsi->count_active_extensions; n++)
713                 wsi->active_extensions[n]->callback(
714                                     context, wsi->active_extensions[n],
715                                     wsi, LWS_EXT_CALLBACK_1HZ,
716                                     wsi->active_extensions_user[n], NULL, sec);
717
718         if (!wsi->pending_timeout)
719                 return;
720                           
721         /*
722          * if we went beyond the allowed time, kill the
723          * connection
724          */
725
726         if (sec > wsi->pending_timeout_limit) {
727                 debug("TIMEDOUT WAITING\n");
728                 libwebsocket_close_and_free_session(context,
729                                 wsi, LWS_CLOSE_STATUS_NOSTATUS);
730         }
731 }
732
733 struct libwebsocket *
734 libwebsocket_create_new_server_wsi(struct libwebsocket_context *context)
735 {
736         struct libwebsocket *new_wsi;
737         int n;
738
739         new_wsi = malloc(sizeof(struct libwebsocket));
740         if (new_wsi == NULL) {
741                 fprintf(stderr, "Out of memory for new connection\n");
742                 return NULL;
743         }
744
745         memset(new_wsi, 0, sizeof (struct libwebsocket));
746         new_wsi->count_active_extensions = 0;
747         new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
748
749         /* intialize the instance struct */
750
751         new_wsi->state = WSI_STATE_HTTP;
752         new_wsi->name_buffer_pos = 0;
753         new_wsi->mode = LWS_CONNMODE_WS_SERVING;
754
755         for (n = 0; n < WSI_TOKEN_COUNT; n++) {
756                 new_wsi->utf8_token[n].token = NULL;
757                 new_wsi->utf8_token[n].token_len = 0;
758         }
759
760         /*
761          * these can only be set once the protocol is known
762          * we set an unestablished connection's protocol pointer
763          * to the start of the supported list, so it can look
764          * for matching ones during the handshake
765          */
766         new_wsi->protocol = context->protocols;
767         new_wsi->user_space = NULL;
768
769         /*
770          * Default protocol is 76 / 00
771          * After 76, there's a header specified to inform which
772          * draft the client wants, when that's seen we modify
773          * the individual connection's spec revision accordingly
774          */
775         new_wsi->ietf_spec_revision = 0;
776
777         return new_wsi;
778 }
779
780 char *
781 libwebsockets_generate_client_handshake(struct libwebsocket_context *context,
782                 struct libwebsocket *wsi, char *pkt)
783 {
784         char hash[20];
785         char *p = pkt;
786         int n;
787         struct libwebsocket_extension *ext;
788         struct libwebsocket_extension *ext1;
789         int ext_count = 0;
790         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 + MAX_BROADCAST_PAYLOAD +
791                                                   LWS_SEND_BUFFER_POST_PADDING];
792         static const char magic_websocket_guid[] =
793                                          "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
794
795         /*
796          * create the random key
797          */
798
799         n = libwebsockets_get_random(context, hash, 16);
800         if (n != 16) {
801                 fprintf(stderr, "Unable to read from random dev %s\n",
802                                                 SYSTEM_RANDOM_FILEPATH);
803                 free(wsi->c_path);
804                 free(wsi->c_host);
805                 if (wsi->c_origin)
806                         free(wsi->c_origin);
807                 if (wsi->c_protocol)
808                         free(wsi->c_protocol);
809                 libwebsocket_close_and_free_session(context, wsi,
810                                              LWS_CLOSE_STATUS_NOSTATUS);
811                 return NULL;
812         }
813
814         lws_b64_encode_string(hash, 16, wsi->key_b64,
815                                                    sizeof wsi->key_b64);
816
817         /*
818          * 00 example client handshake
819          *
820          * GET /socket.io/websocket HTTP/1.1
821          * Upgrade: WebSocket
822          * Connection: Upgrade
823          * Host: 127.0.0.1:9999
824          * Origin: http://127.0.0.1
825          * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7  92 ^
826          * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
827          * Cookie: socketio=websocket
828          *
829          * (Á®Ä0¶†≥
830          *
831          * 04 example client handshake
832          *
833          * GET /chat HTTP/1.1
834          * Host: server.example.com
835          * Upgrade: websocket
836          * Connection: Upgrade
837          * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
838          * Sec-WebSocket-Origin: http://example.com
839          * Sec-WebSocket-Protocol: chat, superchat
840          * Sec-WebSocket-Version: 4
841          */
842
843         p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
844
845         if (wsi->ietf_spec_revision == 0) {
846                 unsigned char spaces_1, spaces_2;
847                 unsigned int max_1, max_2;
848                 unsigned int num_1, num_2;
849                 unsigned long product_1, product_2;
850                 char key_1[40];
851                 char key_2[40];
852                 unsigned int seed;
853                 unsigned int count;
854                 char challenge[16];
855
856                 libwebsockets_get_random(context, &spaces_1,
857                                                           sizeof(char));
858                 libwebsockets_get_random(context, &spaces_2,
859                                                           sizeof(char));
860
861                 spaces_1 = (spaces_1 % 12) + 1;
862                 spaces_2 = (spaces_2 % 12) + 1;
863
864                 max_1 = 4294967295 / spaces_1;
865                 max_2 = 4294967295 / spaces_2;
866
867                 libwebsockets_get_random(context, &num_1, sizeof(int));
868                 libwebsockets_get_random(context, &num_2, sizeof(int));
869
870                 num_1 = (num_1 % max_1);
871                 num_2 = (num_2 % max_2);
872
873                 challenge[0] = num_1 >> 24;
874                 challenge[1] = num_1 >> 16;
875                 challenge[2] = num_1 >> 8;
876                 challenge[3] = num_1;
877                 challenge[4] = num_2 >> 24;
878                 challenge[5] = num_2 >> 16;
879                 challenge[6] = num_2 >> 8;
880                 challenge[7] = num_2;
881
882                 product_1 = num_1 * spaces_1;
883                 product_2 = num_2 * spaces_2;
884
885                 sprintf(key_1, "%lu", product_1);
886                 sprintf(key_2, "%lu", product_2);
887
888                 libwebsockets_get_random(context, &seed, sizeof(int));
889                 libwebsockets_get_random(context, &count, sizeof(int));
890
891                 libwebsockets_00_spam(key_1, (count % 12) + 1, seed);
892
893                 libwebsockets_get_random(context, &seed, sizeof(int));
894                 libwebsockets_get_random(context, &count, sizeof(int));
895
896                 libwebsockets_00_spam(key_2, (count % 12) + 1, seed);
897
898                 libwebsockets_get_random(context, &seed, sizeof(int));
899
900                 libwebsockets_00_spaceout(key_1, spaces_1, seed);
901                 libwebsockets_00_spaceout(key_2, spaces_2, seed >> 16);
902
903                 p += sprintf(p, "Upgrade: WebSocket\x0d\x0a"
904                         "Connection: Upgrade\x0d\x0aHost: %s\x0d\x0a",
905                         wsi->c_host);
906                 if (wsi->c_origin)
907                         p += sprintf(p, "Origin: %s\x0d\x0a",
908                         wsi->c_origin);
909
910                 if (wsi->c_protocol)
911                         p += sprintf(p, "Sec-WebSocket-Protocol: %s"
912                                          "\x0d\x0a", wsi->c_protocol);
913
914                 p += sprintf(p, "Sec-WebSocket-Key1: %s\x0d\x0a",
915                         key_1);
916                 p += sprintf(p, "Sec-WebSocket-Key2: %s\x0d\x0a",
917                         key_2);
918
919                 /* give userland a chance to append, eg, cookies */
920
921                 context->protocols[0].callback(context, wsi,
922                         LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
923                                 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
924
925                 p += sprintf(p, "\x0d\x0a");
926
927                 if (libwebsockets_get_random(context, p, 8) != 8)
928                         return NULL;
929                 memcpy(&challenge[8], p, 8);
930                 p += 8;
931
932                 /* precompute what we want to see from the server */
933
934                 MD5((unsigned char *)challenge, 16,
935                    (unsigned char *)wsi->initial_handshake_hash_base64);
936
937                 goto issue_hdr;
938         }
939
940         p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
941         p += sprintf(p, "Upgrade: websocket\x0d\x0a");
942         p += sprintf(p, "Connection: Upgrade\x0d\x0a"
943                                 "Sec-WebSocket-Key: ");
944         strcpy(p, wsi->key_b64);
945         p += strlen(wsi->key_b64);
946         p += sprintf(p, "\x0d\x0a");
947         if (wsi->c_origin)
948                 p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
949                                                          wsi->c_origin);
950         if (wsi->c_protocol)
951                 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
952                                                        wsi->c_protocol);
953
954         /* tell the server what extensions we could support */
955
956         p += sprintf(p, "Sec-WebSocket-Extensions: ");
957
958         ext =context->extensions;
959         while (ext && ext->callback) {
960
961                 n = 0;
962                 ext1 = context->extensions;
963                 while (ext1 && ext1->callback) {
964
965                         n |= ext1->callback(context, ext1, wsi,
966                                 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
967                                         NULL, (char *)ext->name, 0);
968
969                         ext1++;
970                 }
971
972                 if (n) {
973
974                         /* an extension vetos us */
975                         debug("ext %s vetoed\n", (char *)ext->name);
976                         ext++;
977                         continue;
978                 }
979
980                 n = context->protocols[0].callback(context, wsi,
981                         LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
982                                 wsi->user_space, (char *)ext->name, 0);
983
984                 /*
985                  * zero return from callback means
986                  * go ahead and allow the extension,
987                  * it's what we get if the callback is
988                  * unhandled
989                  */
990
991                 if (n) {
992                         ext++;
993                         continue;
994                 }
995
996                 /* apply it */
997
998                 if (ext_count)
999                         *p++ = ',';
1000                 p += sprintf(p, "%s", ext->name);
1001                 ext_count++;
1002
1003                 ext++;
1004         }
1005
1006         p += sprintf(p, "\x0d\x0a");
1007
1008         if (wsi->ietf_spec_revision)
1009                 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
1010                                                wsi->ietf_spec_revision);
1011
1012         /* give userland a chance to append, eg, cookies */
1013
1014         context->protocols[0].callback(context, wsi,
1015                 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
1016                 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
1017
1018         p += sprintf(p, "\x0d\x0a");
1019
1020         /* prepare the expected server accept response */
1021
1022         strcpy((char *)buf, wsi->key_b64);
1023         strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
1024
1025         SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
1026
1027         lws_b64_encode_string(hash, 20,
1028                         wsi->initial_handshake_hash_base64,
1029                              sizeof wsi->initial_handshake_hash_base64);
1030
1031 issue_hdr:
1032
1033 //      puts(pkt);
1034
1035         /* done with these now */
1036
1037         free(wsi->c_path);
1038         free(wsi->c_host);
1039         if (wsi->c_origin)
1040                 free(wsi->c_origin);
1041
1042         return p;
1043 }
1044
1045 int
1046 lws_client_interpret_server_handshake(struct libwebsocket_context *context,
1047                 struct libwebsocket *wsi)
1048 {
1049         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 + MAX_BROADCAST_PAYLOAD +
1050                                                   LWS_SEND_BUFFER_POST_PADDING];
1051         char pkt[1024];
1052         char *p = &pkt[0];
1053         const char *pc;
1054         const char *c;
1055         int more = 1;
1056         int okay = 0;
1057         char ext_name[128];
1058         struct libwebsocket_extension *ext;
1059         void *v;
1060         int len = 0;
1061         int n;
1062         static const char magic_websocket_04_masking_guid[] =
1063                                          "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
1064
1065         /*
1066          * 00 / 76 -->
1067          *
1068          * HTTP/1.1 101 WebSocket Protocol Handshake
1069          * Upgrade: WebSocket
1070          * Connection: Upgrade
1071          * Sec-WebSocket-Origin: http://127.0.0.1
1072          * Sec-WebSocket-Location: ws://127.0.0.1:9999/socket.io/websocket
1073          *
1074          * xxxxxxxxxxxxxxxx
1075          */
1076
1077         if (wsi->ietf_spec_revision == 0) {
1078                 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1079                         !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1080                         !wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
1081                         !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1082                         (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1083                         wsi->c_protocol != NULL)) {
1084                         debug("libwebsocket_client_handshake "
1085                                         "missing required header(s)\n");
1086                         pkt[len] = '\0';
1087                         debug("%s", pkt);
1088                         goto bail3;
1089                 }
1090
1091                 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1092                 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1093                         "101 websocket protocol handshake")) {
1094                         fprintf(stderr, "libwebsocket_client_handshake "
1095                                 "server sent bad HTTP response '%s'\n",
1096                                 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1097                         goto bail3;
1098                 }
1099
1100                 if (wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len <
1101                                                                    16) {
1102                         fprintf(stderr, "libwebsocket_client_handshake "
1103                                 "challenge reply too short %d\n",
1104                                 wsi->utf8_token[
1105                                         WSI_TOKEN_CHALLENGE].token_len);
1106                         pkt[len] = '\0';
1107                         debug("%s", pkt);
1108                         goto bail3;
1109
1110                 }
1111
1112                 goto select_protocol;
1113         }
1114
1115         /*
1116          * well, what the server sent looked reasonable for syntax.
1117          * Now let's confirm it sent all the necessary headers
1118          */
1119 #if 0
1120         fprintf(stderr, "WSI_TOKEN_HTTP: %d\n", wsi->utf8_token[WSI_TOKEN_HTTP].token_len);
1121         fprintf(stderr, "WSI_TOKEN_UPGRADE: %d\n", wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len);
1122         fprintf(stderr, "WSI_TOKEN_CONNECTION: %d\n", wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len);
1123         fprintf(stderr, "WSI_TOKEN_ACCEPT: %d\n", wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len);
1124         fprintf(stderr, "WSI_TOKEN_NONCE: %d\n", wsi->utf8_token[WSI_TOKEN_NONCE].token_len);
1125         fprintf(stderr, "WSI_TOKEN_PROTOCOL: %d\n", wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
1126 #endif
1127          if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1128                 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1129                 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1130                 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
1131                 (!wsi->utf8_token[WSI_TOKEN_NONCE].token_len &&
1132                                    wsi->ietf_spec_revision == 4) ||
1133                 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1134                                                  wsi->c_protocol != NULL)) {
1135                  debug("libwebsocket_client_handshake "
1136                                         "missing required header(s)\n");
1137                 pkt[len] = '\0';
1138                 debug("%s", pkt);
1139                 goto bail3;
1140         }
1141
1142         /*
1143          * Everything seems to be there, now take a closer look at what
1144          * is in each header
1145          */
1146
1147         strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1148         if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1149                                            "101 switching protocols")) {
1150                 fprintf(stderr, "libwebsocket_client_handshake "
1151                                 "server sent bad HTTP response '%s'\n",
1152                                  wsi->utf8_token[WSI_TOKEN_HTTP].token);
1153                 goto bail3;
1154         }
1155
1156         strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1157         if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
1158                                                          "websocket")) {
1159                 fprintf(stderr, "libwebsocket_client_handshake server "
1160                                 "sent bad Upgrade header '%s'\n",
1161                                   wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1162                 goto bail3;
1163         }
1164
1165         strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1166         if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
1167                                                            "upgrade")) {
1168                 fprintf(stderr, "libwebsocket_client_handshake server "
1169                                 "sent bad Connection hdr '%s'\n",
1170                            wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1171                 goto bail3;
1172         }
1173
1174 select_protocol:
1175         pc = wsi->c_protocol;
1176         if (pc == NULL)
1177                 fprintf(stderr, "lws_client_interpret_server_handshake: NULL c_protocol\n");
1178         else
1179                 debug("lws_client_interpret_server_handshake: cPprotocol='%s'\n", pc);
1180
1181         /*
1182          * confirm the protocol the server wants to talk was in the list
1183          * of protocols we offered
1184          */
1185
1186         if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
1187
1188                 fprintf(stderr, "lws_client_interpret_server_handshake WSI_TOKEN_PROTOCOL is null\n");
1189                 /*
1190                  * no protocol name to work from,
1191                  * default to first protocol
1192                  */
1193                 wsi->protocol = &context->protocols[0];
1194
1195                 free(wsi->c_protocol);
1196
1197                 goto check_accept;
1198         }
1199
1200         while (*pc && !okay) {
1201                 if ((!strncmp(pc,
1202                         wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1203                    wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
1204          (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
1205            pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
1206                         okay = 1;
1207                         continue;
1208                 }
1209                 while (*pc && *pc != ',')
1210                         pc++;
1211                 while (*pc && *pc != ' ')
1212                         pc++;
1213         }
1214
1215         /* done with him now */
1216
1217         if (wsi->c_protocol)
1218                 free(wsi->c_protocol);
1219
1220
1221         if (!okay) {
1222                 fprintf(stderr, "libwebsocket_client_handshake server "
1223                                         "sent bad protocol '%s'\n",
1224                                  wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1225                 goto bail2;
1226         }
1227
1228         /*
1229          * identify the selected protocol struct and set it
1230          */
1231         n = 0;
1232         wsi->protocol = NULL;
1233         while (context->protocols[n].callback) {
1234                 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1235                                            context->protocols[n].name) == 0)
1236                         wsi->protocol = &context->protocols[n];
1237                 n++;
1238         }
1239
1240         if (wsi->protocol == NULL) {
1241                 fprintf(stderr, "libwebsocket_client_handshake server "
1242                                 "requested protocol '%s', which we "
1243                                 "said we supported but we don't!\n",
1244                                  wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1245                 goto bail2;
1246         }
1247
1248
1249         /* instantiate the accepted extensions */
1250
1251         if (!wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token_len) {
1252                 debug("no client extenstions allowed by server \n");
1253                 goto check_accept;
1254         }
1255
1256         /*
1257          * break down the list of server accepted extensions
1258          * and go through matching them or identifying bogons
1259          */
1260
1261         c = wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token;
1262         n = 0;
1263         while (more) {
1264
1265                 if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
1266                         ext_name[n] = *c++;
1267                         if (n < sizeof(ext_name) - 1)
1268                                 n++;
1269                         continue;
1270                 }
1271                 ext_name[n] = '\0';
1272                 if (!*c)
1273                         more = 0;
1274                 else {
1275                         c++;
1276                         if (!n)
1277                                 continue;
1278                 }
1279
1280                 /* check we actually support it */
1281
1282                 debug("checking client ext %s\n", ext_name);
1283
1284                 n = 0;
1285                 ext = wsi->protocol->owning_server->extensions;
1286                 while (ext && ext->callback) {
1287
1288                         if (strcmp(ext_name, ext->name)) {
1289                                 ext++;
1290                                 continue;
1291                         }
1292
1293                         n = 1;
1294
1295                         debug("instantiating client ext %s\n", ext_name);
1296
1297                         /* instantiate the extension on this conn */
1298
1299                         wsi->active_extensions_user[
1300                                 wsi->count_active_extensions] =
1301                                          malloc(ext->per_session_data_size);
1302                         memset(wsi->active_extensions_user[
1303                                 wsi->count_active_extensions], 0,
1304                                                     ext->per_session_data_size);
1305                         wsi->active_extensions[
1306                                   wsi->count_active_extensions] = ext;
1307
1308                         /* allow him to construct his context */
1309
1310                         ext->callback(wsi->protocol->owning_server,
1311                                 ext, wsi,
1312                                    LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
1313                                         wsi->active_extensions_user[
1314                                          wsi->count_active_extensions],
1315                                                                    NULL, 0);
1316
1317                         wsi->count_active_extensions++;
1318
1319                         ext++;
1320                 }
1321
1322                 if (n == 0) {
1323                         fprintf(stderr, "Server said we should use"
1324                                   "an unknown extension '%s'!\n", ext_name);
1325                         goto bail2;
1326                 }
1327
1328                 n = 0;
1329         }
1330
1331
1332 check_accept:
1333
1334         if (wsi->ietf_spec_revision == 0) {
1335
1336                 if (memcmp(wsi->initial_handshake_hash_base64,
1337                           wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 16)) {
1338                         fprintf(stderr, "libwebsocket_client_handshake "
1339                                            "failed 00 challenge compare\n");
1340                                 pkt[len] = '\0';
1341                                 fprintf(stderr, "%s", pkt);
1342                                 goto bail2;
1343                 }
1344
1345                 goto accept_ok;
1346         }
1347
1348         /*
1349          * Confirm his accept token is the one we precomputed
1350          */
1351
1352         if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1353                                   wsi->initial_handshake_hash_base64)) {
1354                 fprintf(stderr, "libwebsocket_client_handshake server "
1355                         "sent bad ACCEPT '%s' vs computed '%s'\n",
1356                         wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1357                                         wsi->initial_handshake_hash_base64);
1358                 goto bail2;
1359         }
1360
1361         if (wsi->ietf_spec_revision == 4) {
1362                 /*
1363                  * Calculate the 04 masking key to use when
1364                  * sending data to server
1365                  */
1366
1367                 strcpy((char *)buf, wsi->key_b64);
1368                 p = (char *)buf + strlen(wsi->key_b64);
1369                 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1370                 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1371                 strcpy(p, magic_websocket_04_masking_guid);
1372                 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1373         }
1374         accept_ok:
1375
1376         /* allocate the per-connection user memory (if any) */
1377         if (wsi->protocol->per_session_data_size && !libwebsocket_ensure_user_space(wsi))
1378           goto bail2;
1379
1380         /* clear his proxy connection timeout */
1381
1382         libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1383
1384         /* mark him as being alive */
1385
1386         wsi->state = WSI_STATE_ESTABLISHED;
1387         wsi->mode = LWS_CONNMODE_WS_CLIENT;
1388
1389         fprintf(stderr, "handshake OK for protocol %s\n",
1390                                                    wsi->protocol->name);
1391
1392         /* call him back to inform him he is up */
1393
1394         wsi->protocol->callback(context, wsi,
1395                          LWS_CALLBACK_CLIENT_ESTABLISHED,
1396                          wsi->user_space,
1397                          NULL, 0);
1398
1399         /*
1400          * inform all extensions, not just active ones since they
1401          * already know
1402          */
1403
1404         ext = context->extensions;
1405
1406         while (ext && ext->callback) {
1407                 v = NULL;
1408                 for (n = 0; n < wsi->count_active_extensions; n++)
1409                         if (wsi->active_extensions[n] == ext)
1410                                 v = wsi->active_extensions_user[n];
1411
1412                 ext->callback(context, ext, wsi,
1413                           LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0);
1414                 ext++;
1415         }
1416
1417         return 0;
1418
1419 bail3:
1420         if (wsi->c_protocol)
1421                 free(wsi->c_protocol);
1422
1423 bail2:
1424         libwebsocket_close_and_free_session(context, wsi,
1425                                                  LWS_CLOSE_STATUS_NOSTATUS);
1426         return 1;
1427 }
1428
1429
1430
1431 /**
1432  * libwebsocket_service_fd() - Service polled socket with something waiting
1433  * @context:    Websocket context
1434  * @pollfd:     The pollfd entry describing the socket fd and which events
1435  *              happened.
1436  *
1437  *      This function closes any active connections and then frees the
1438  *      context.  After calling this, any further use of the context is
1439  *      undefined.
1440  */
1441
1442 int
1443 libwebsocket_service_fd(struct libwebsocket_context *context,
1444                                                           struct pollfd *pollfd)
1445 {
1446         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 + MAX_BROADCAST_PAYLOAD +
1447                                                   LWS_SEND_BUFFER_POST_PADDING];
1448         struct libwebsocket *wsi;
1449         struct libwebsocket *new_wsi;
1450         int n;
1451         int m;
1452         size_t len;
1453         int accept_fd;
1454         unsigned int clilen;
1455         struct sockaddr_in cli_addr;
1456         struct timeval tv;
1457         char pkt[1024];
1458         char *p = &pkt[0];
1459         int more = 1;
1460         struct lws_tokens eff_buf;
1461         int opt = 1;
1462
1463 #ifdef LWS_OPENSSL_SUPPORT
1464         char ssl_err_buf[512];
1465 #endif
1466         /*
1467          * you can call us with pollfd = NULL to just allow the once-per-second
1468          * global timeout checks; if less than a second since the last check
1469          * it returns immediately then.
1470          */
1471
1472         gettimeofday(&tv, NULL);
1473
1474         if (context->last_timeout_check_s != tv.tv_sec) {
1475                 context->last_timeout_check_s = tv.tv_sec;
1476
1477                 /* global timeout check once per second */
1478
1479                 for (n = 0; n < context->fds_count; n++) {
1480                         wsi = wsi_from_fd(context, context->fds[n].fd);
1481
1482                         libwebsocket_service_timeout_check(context, wsi,
1483                                                                      tv.tv_sec);
1484                 }
1485         }
1486
1487         /* just here for timeout management? */
1488
1489         if (pollfd == NULL)
1490                 return 0;
1491
1492         /* no, here to service a socket descriptor */
1493
1494         wsi = wsi_from_fd(context, pollfd->fd);
1495
1496         if (wsi == NULL)
1497                 return 1;
1498
1499         switch (wsi->mode) {
1500         case LWS_CONNMODE_SERVER_LISTENER:
1501
1502                 /* pollin means a client has connected to us then */
1503
1504                 if (!pollfd->revents & POLLIN)
1505                         break;
1506
1507                 if (context->fds_count >= MAX_CLIENTS) {
1508                         fprintf(stderr, "too busy to accept new client\n");
1509                         break;
1510                 }
1511
1512                 /* listen socket got an unencrypted connection... */
1513
1514                 clilen = sizeof(cli_addr);
1515                 accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1516                                                                        &clilen);
1517                 if (accept_fd < 0) {
1518                         fprintf(stderr, "ERROR on accept");
1519                         break;
1520                 }
1521
1522                 /* Disable Nagle */
1523                 opt = 1;
1524         setsockopt(accept_fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&opt,
1525                                 sizeof(opt));
1526
1527                 /*
1528                  * look at who we connected to and give user code a chance
1529                  * to reject based on client IP.  There's no protocol selected
1530                  * yet so we issue this to protocols[0]
1531                  */
1532
1533                 if ((context->protocols[0].callback)(context, wsi,
1534                                 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1535                                              (void*)(long)accept_fd, NULL, 0)) {
1536                         debug("Callback denied network connection\n");
1537 #ifdef WIN32
1538                         closesocket(accept_fd);
1539 #else
1540                         close(accept_fd);
1541 #endif
1542                         break;
1543                 }
1544
1545                 /* accepting connection to main listener */
1546
1547                 new_wsi = libwebsocket_create_new_server_wsi(context);
1548                 if (new_wsi == NULL)
1549                         break;
1550
1551                 new_wsi->sock = accept_fd;
1552
1553
1554 #ifdef LWS_OPENSSL_SUPPORT
1555                 new_wsi->ssl = NULL;
1556
1557                 if (context->use_ssl) {
1558
1559                         new_wsi->ssl = SSL_new(context->ssl_ctx);
1560                         if (new_wsi->ssl == NULL) {
1561                                 fprintf(stderr, "SSL_new failed: %s\n",
1562                                     ERR_error_string(SSL_get_error(
1563                                     new_wsi->ssl, 0), NULL));
1564                                     libwebsockets_decode_ssl_error();
1565                                 free(new_wsi);
1566                                 break;
1567                         }
1568
1569                         SSL_set_fd(new_wsi->ssl, accept_fd);
1570
1571                         n = SSL_accept(new_wsi->ssl);
1572                         if (n != 1) {
1573                                 /*
1574                                  * browsers seem to probe with various
1575                                  * ssl params which fail then retry
1576                                  * and succeed
1577                                  */
1578                                 debug("SSL_accept failed skt %u: %s\n",
1579                                       pollfd->fd,
1580                                       ERR_error_string(SSL_get_error(
1581                                       new_wsi->ssl, n), NULL));
1582                                 SSL_free(
1583                                        new_wsi->ssl);
1584                                 free(new_wsi);
1585                                 break;
1586                         }
1587                         
1588                         debug("accepted new SSL conn  "
1589                               "port %u on fd=%d SSL ver %s\n",
1590                                 ntohs(cli_addr.sin_port), accept_fd,
1591                                   SSL_get_version(new_wsi->ssl));
1592
1593                 } else
1594 #endif
1595                         debug("accepted new conn  port %u on fd=%d\n",
1596                                           ntohs(cli_addr.sin_port), accept_fd);
1597
1598                 insert_wsi(context, new_wsi);
1599
1600                 /*
1601                  * make sure NO events are seen yet on this new socket
1602                  * (otherwise we inherit old fds[client].revents from
1603                  * previous socket there and die mysteriously! )
1604                  */
1605                 context->fds[context->fds_count].revents = 0;
1606
1607                 context->fds[context->fds_count].events = POLLIN;
1608                 context->fds[context->fds_count++].fd = accept_fd;
1609
1610                 /* external POLL support via protocol 0 */
1611                 context->protocols[0].callback(context, new_wsi,
1612                         LWS_CALLBACK_ADD_POLL_FD,
1613                         (void *)(long)accept_fd, NULL, POLLIN);
1614
1615                 break;
1616
1617         case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
1618
1619                 /* as we are listening, POLLIN means accept() is needed */
1620         
1621                 if (!pollfd->revents & POLLIN)
1622                         break;
1623
1624                 /* listen socket got an unencrypted connection... */
1625
1626                 clilen = sizeof(cli_addr);
1627                 accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1628                                                                        &clilen);
1629                 if (accept_fd < 0) {
1630                         fprintf(stderr, "ERROR on accept");
1631                         break;
1632                 }
1633
1634                 if (context->fds_count >= MAX_CLIENTS) {
1635                         fprintf(stderr, "too busy to accept new broadcast "
1636                                                               "proxy client\n");
1637 #ifdef WIN32
1638                         closesocket(accept_fd);
1639 #else
1640                         close(accept_fd);
1641 #endif
1642                         break;
1643                 }
1644
1645                 /* create a dummy wsi for the connection and add it */
1646
1647                 new_wsi = malloc(sizeof(struct libwebsocket));
1648                 memset(new_wsi, 0, sizeof (struct libwebsocket));
1649                 new_wsi->sock = accept_fd;
1650                 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
1651                 new_wsi->state = WSI_STATE_ESTABLISHED;
1652                 new_wsi->count_active_extensions = 0;
1653                 /* note which protocol we are proxying */
1654                 new_wsi->protocol_index_for_broadcast_proxy =
1655                                         wsi->protocol_index_for_broadcast_proxy;
1656                 insert_wsi(context, new_wsi);
1657
1658                 /* add connected socket to internal poll array */
1659
1660                 context->fds[context->fds_count].revents = 0;
1661                 context->fds[context->fds_count].events = POLLIN;
1662                 context->fds[context->fds_count++].fd = accept_fd;
1663
1664                 /* external POLL support via protocol 0 */
1665                 context->protocols[0].callback(context, new_wsi,
1666                         LWS_CALLBACK_ADD_POLL_FD,
1667                         (void *)(long)accept_fd, NULL, POLLIN);
1668
1669                 break;
1670
1671         case LWS_CONNMODE_BROADCAST_PROXY:
1672
1673                 /* handle session socket closed */
1674
1675                 if (pollfd->revents & (POLLERR | POLLHUP)) {
1676
1677                         debug("Session Socket %p (fd=%d) dead\n",
1678                                 (void *)wsi, pollfd->fd);
1679
1680                         libwebsocket_close_and_free_session(context, wsi,
1681                                                        LWS_CLOSE_STATUS_NORMAL);
1682                         return 1;
1683                 }
1684
1685                 /*
1686                  * either extension code with stuff to spill, or the user code,
1687                  * requested a callback when it was OK to write
1688                  */
1689
1690                 if (pollfd->revents & POLLOUT)
1691                         if (lws_handle_POLLOUT_event(context, wsi, pollfd) < 0) {
1692                                 libwebsocket_close_and_free_session(context, wsi,
1693                                                        LWS_CLOSE_STATUS_NORMAL);
1694                                 return 1;
1695                         }
1696
1697                 /* any incoming data ready? */
1698
1699                 if (!(pollfd->revents & POLLIN))
1700                         break;
1701
1702                 /* get the issued broadcast payload from the socket */
1703
1704                 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
1705                                                          MAX_BROADCAST_PAYLOAD);
1706                 if (len < 0) {
1707                         fprintf(stderr, "Error reading broadcast payload\n");
1708                         break;
1709                 }
1710
1711                 /* broadcast it to all guys with this protocol index */
1712
1713                 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1714
1715                         for (m = 0; m < context->fd_hashtable[n].length; m++) {
1716
1717                                 new_wsi = context->fd_hashtable[n].wsi[m];
1718
1719                                 /* only to clients we are serving to */
1720
1721                                 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
1722                                         continue;
1723
1724                                 /*
1725                                  * never broadcast to non-established
1726                                  * connection
1727                                  */
1728
1729                                 if (new_wsi->state != WSI_STATE_ESTABLISHED)
1730                                         continue;
1731
1732                                 /*
1733                                  * only broadcast to connections using
1734                                  * the requested protocol
1735                                  */
1736
1737                                 if (new_wsi->protocol->protocol_index !=
1738                                         wsi->protocol_index_for_broadcast_proxy)
1739                                         continue;
1740
1741                                 /* broadcast it to this connection */
1742
1743                                 new_wsi->protocol->callback(context, new_wsi,
1744                                         LWS_CALLBACK_BROADCAST,
1745                                         new_wsi->user_space,
1746                                         buf + LWS_SEND_BUFFER_PRE_PADDING, len);
1747                         }
1748                 }
1749                 break;
1750
1751         case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
1752
1753                 /* handle proxy hung up on us */
1754
1755                 if (pollfd->revents & (POLLERR | POLLHUP)) {
1756
1757                         fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
1758                                 (void *)wsi, pollfd->fd);
1759
1760                         libwebsocket_close_and_free_session(context, wsi,
1761                                                      LWS_CLOSE_STATUS_NOSTATUS);
1762                         return 1;
1763                 }
1764
1765                 n = recv(wsi->sock, pkt, sizeof pkt, 0);
1766                 if (n < 0) {
1767                         libwebsocket_close_and_free_session(context, wsi,
1768                                                      LWS_CLOSE_STATUS_NOSTATUS);
1769                         fprintf(stderr, "ERROR reading from proxy socket\n");
1770                         return 1;
1771                 }
1772
1773                 pkt[13] = '\0';
1774                 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
1775                         libwebsocket_close_and_free_session(context, wsi,
1776                                                      LWS_CLOSE_STATUS_NOSTATUS);
1777                         fprintf(stderr, "ERROR from proxy: %s\n", pkt);
1778                         return 1;
1779                 }
1780
1781                 /* clear his proxy connection timeout */
1782
1783                 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1784
1785                 /* fallthru */
1786
1787         case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
1788
1789         #ifdef LWS_OPENSSL_SUPPORT
1790                 if (wsi->use_ssl) {
1791
1792                         wsi->ssl = SSL_new(context->ssl_client_ctx);
1793                         wsi->client_bio = BIO_new_socket(wsi->sock,
1794                                                                    BIO_NOCLOSE);
1795                         SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
1796
1797                         SSL_set_ex_data(wsi->ssl,
1798                                         openssl_websocket_private_data_index,
1799                                                                        context);
1800
1801                         if (SSL_connect(wsi->ssl) <= 0) {
1802                                 fprintf(stderr, "SSL connect error %s\n",
1803                                         ERR_error_string(ERR_get_error(),
1804                                                                   ssl_err_buf));
1805                                 libwebsocket_close_and_free_session(context, wsi,
1806                                                      LWS_CLOSE_STATUS_NOSTATUS);
1807                                 return 1;
1808                         }
1809
1810                         n = SSL_get_verify_result(wsi->ssl);
1811                         if ((n != X509_V_OK) && (
1812                                 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
1813                                                            wsi->use_ssl != 2)) {
1814
1815                                 fprintf(stderr, "server's cert didn't "
1816                                                            "look good %d\n", n);
1817                                 libwebsocket_close_and_free_session(context,
1818                                                 wsi, LWS_CLOSE_STATUS_NOSTATUS);
1819                                 return 1;
1820                         }
1821                 } else {
1822                         wsi->ssl = NULL;
1823         #endif
1824
1825
1826         #ifdef LWS_OPENSSL_SUPPORT
1827                 }
1828         #endif
1829
1830                 p = libwebsockets_generate_client_handshake(context, wsi, p);
1831                 if (p ==NULL)
1832                         return 1;
1833
1834                 /* send our request to the server */
1835
1836         #ifdef LWS_OPENSSL_SUPPORT
1837                 if (wsi->use_ssl)
1838                         n = SSL_write(wsi->ssl, pkt, p - pkt);
1839                 else
1840         #endif
1841                         n = send(wsi->sock, pkt, p - pkt, 0);
1842
1843                 if (n < 0) {
1844                         fprintf(stderr, "ERROR writing to client socket\n");
1845                         libwebsocket_close_and_free_session(context, wsi,
1846                                                      LWS_CLOSE_STATUS_NOSTATUS);
1847                         return 1;
1848                 }
1849
1850                 wsi->parser_state = WSI_TOKEN_NAME_PART;
1851                 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
1852                 libwebsocket_set_timeout(wsi,
1853                                 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
1854
1855                 break;
1856
1857         case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
1858
1859                 /* handle server hung up on us */
1860
1861                 if (pollfd->revents & (POLLERR | POLLHUP)) {
1862
1863                         fprintf(stderr, "Server connection %p (fd=%d) dead\n",
1864                                 (void *)wsi, pollfd->fd);
1865
1866                         goto bail3;
1867                 }
1868
1869
1870                 /* interpret the server response */
1871
1872                 /*
1873                  *  HTTP/1.1 101 Switching Protocols
1874                  *  Upgrade: websocket
1875                  *  Connection: Upgrade
1876                  *  Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
1877                  *  Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
1878                  *  Sec-WebSocket-Protocol: chat
1879                  */
1880
1881         #ifdef LWS_OPENSSL_SUPPORT
1882                 if (wsi->use_ssl)
1883                         len = SSL_read(wsi->ssl, pkt, sizeof pkt);
1884                 else
1885         #endif
1886                         len = recv(wsi->sock, pkt, sizeof pkt, 0);
1887
1888                 if (len < 0) {
1889                         fprintf(stderr,
1890                                   "libwebsocket_client_handshake read error\n");
1891                         goto bail3;
1892                 }
1893
1894                 p = pkt;
1895                 for (n = 0; n < len; n++)
1896                         libwebsocket_parse(wsi, *p++);
1897
1898                 /*
1899                  * may be coming in multiple packets, there is a 5-second
1900                  * libwebsocket timeout still active here too, so if parsing did
1901                  * not complete just wait for next packet coming in this state
1902                  */
1903
1904                 if (wsi->parser_state != WSI_PARSING_COMPLETE)
1905                         break;
1906
1907                 return lws_client_interpret_server_handshake(context, wsi);
1908
1909 bail3:
1910                 if (wsi->c_protocol)
1911                         free(wsi->c_protocol);
1912                 libwebsocket_close_and_free_session(context, wsi,
1913                                                                  LWS_CLOSE_STATUS_NOSTATUS);
1914                 return 1;
1915
1916         case LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT:
1917                 fprintf(stderr, "LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT\n");
1918                 break;
1919
1920         case LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD:
1921                 fprintf(stderr, "LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD\n");
1922                 break;
1923
1924
1925         case LWS_CONNMODE_WS_SERVING:
1926         case LWS_CONNMODE_WS_CLIENT:
1927
1928                 /* handle session socket closed */
1929
1930                 if (pollfd->revents & (POLLERR | POLLHUP)) {
1931
1932                         fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
1933                                 (void *)wsi, pollfd->fd);
1934
1935                         libwebsocket_close_and_free_session(context, wsi,
1936                                                      LWS_CLOSE_STATUS_NOSTATUS);
1937                         return 1;
1938                 }
1939
1940                 /* the guy requested a callback when it was OK to write */
1941
1942                 if ((pollfd->revents & POLLOUT) &&
1943                                             wsi->state == WSI_STATE_ESTABLISHED)
1944                         if (lws_handle_POLLOUT_event(context, wsi,
1945                                                                   pollfd) < 0) {
1946                                 libwebsocket_close_and_free_session(
1947                                          context, wsi, LWS_CLOSE_STATUS_NORMAL);
1948                                 return 1;
1949                         }
1950
1951
1952                 /* any incoming data ready? */
1953
1954                 if (!(pollfd->revents & POLLIN))
1955                         break;
1956
1957 #ifdef LWS_OPENSSL_SUPPORT
1958                 if (wsi->ssl)
1959                         eff_buf.token_len = SSL_read(wsi->ssl, buf, sizeof buf);
1960                 else
1961 #endif
1962                         eff_buf.token_len =
1963                                            recv(pollfd->fd, buf, sizeof buf, 0);
1964
1965                 if (eff_buf.token_len < 0) {
1966                         fprintf(stderr, "Socket read returned %d\n",
1967                                                             eff_buf.token_len);
1968                         break;
1969                 }
1970                 if (!eff_buf.token_len) {
1971                         libwebsocket_close_and_free_session(context, wsi,
1972                                                      LWS_CLOSE_STATUS_NOSTATUS);
1973                         return 1;
1974                 }
1975
1976                 /*
1977                  * give any active extensions a chance to munge the buffer
1978                  * before parse.  We pass in a pointer to an lws_tokens struct
1979                  * prepared with the default buffer and content length that's in
1980                  * there.  Rather than rewrite the default buffer, extensions
1981                  * that expect to grow the buffer can adapt .token to
1982                  * point to their own per-connection buffer in the extension
1983                  * user allocation.  By default with no extensions or no
1984                  * extension callback handling, just the normal input buffer is
1985                  * used then so it is efficient.
1986                  */
1987
1988                 eff_buf.token = (char *)buf;
1989
1990                 more = 1;
1991                 while (more) {
1992
1993                         more = 0;
1994
1995                         for (n = 0; n < wsi->count_active_extensions; n++) {
1996                                 m = wsi->active_extensions[n]->callback(context,
1997                                         wsi->active_extensions[n], wsi,
1998                                         LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
1999                                         wsi->active_extensions_user[n],
2000                                                                    &eff_buf, 0);
2001                                 if (m < 0) {
2002                                         fprintf(stderr, "Extension reports fatal error\n");
2003                                         libwebsocket_close_and_free_session(context, wsi,
2004                                                              LWS_CLOSE_STATUS_NOSTATUS);
2005                                         return 1;
2006                                 }
2007                                 if (m)
2008                                         more = 1;
2009                         }
2010
2011                         /* service incoming data */
2012
2013                         if (eff_buf.token_len) {
2014                                 n = libwebsocket_read(context, wsi,
2015                                      (unsigned char *)eff_buf.token, eff_buf.token_len);
2016                                 if (n < 0)
2017                                         /* we closed wsi */
2018                                         return 1;
2019                         }
2020
2021                         eff_buf.token = NULL;
2022                         eff_buf.token_len = 0;
2023                 }
2024                 break;
2025         }
2026
2027         return 0;
2028 }
2029
2030
2031 /**
2032  * libwebsocket_context_destroy() - Destroy the websocket context
2033  * @context:    Websocket context
2034  *
2035  *      This function closes any active connections and then frees the
2036  *      context.  After calling this, any further use of the context is
2037  *      undefined.
2038  */
2039 void
2040 libwebsocket_context_destroy(struct libwebsocket_context *context)
2041 {
2042         int n;
2043         int m;
2044         struct libwebsocket *wsi;
2045         struct libwebsocket_extension *ext;
2046
2047         for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
2048                 for (m = 0; m < context->fd_hashtable[n].length; m++) {
2049                         wsi = context->fd_hashtable[n].wsi[m];
2050                         libwebsocket_close_and_free_session(context, wsi,
2051                                                     LWS_CLOSE_STATUS_GOINGAWAY);
2052                 }
2053
2054         /*
2055          * give all extensions a chance to clean up any per-context
2056          * allocations they might have made
2057          */
2058
2059         ext = context->extensions;
2060         m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
2061         if (context->listen_port)
2062                 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
2063         while (ext->callback) {
2064                 ext->callback(context, ext, NULL, m, NULL, NULL, 0);
2065                 ext++;
2066         }
2067
2068 #ifdef WIN32
2069 #else
2070         close(context->fd_random);
2071 #endif
2072
2073 #ifdef LWS_OPENSSL_SUPPORT
2074         if (context->ssl_ctx)
2075                 SSL_CTX_free(context->ssl_ctx);
2076         if (context->ssl_client_ctx)
2077                 SSL_CTX_free(context->ssl_client_ctx);
2078 #endif
2079
2080         free(context);
2081
2082 #ifdef WIN32
2083         WSACleanup();
2084 #endif
2085 }
2086
2087 /**
2088  * libwebsocket_service() - Service any pending websocket activity
2089  * @context:    Websocket context
2090  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2091  *              service otherwise block and service immediately, returning
2092  *              after the timeout if nothing needed service.
2093  *
2094  *      This function deals with any pending websocket traffic, for three
2095  *      kinds of event.  It handles these events on both server and client
2096  *      types of connection the same.
2097  *
2098  *      1) Accept new connections to our context's server
2099  *
2100  *      2) Perform pending broadcast writes initiated from other forked
2101  *         processes (effectively serializing asynchronous broadcasts)
2102  *
2103  *      3) Call the receive callback for incoming frame data received by
2104  *          server or client connections.
2105  *
2106  *      You need to call this service function periodically to all the above
2107  *      functions to happen; if your application is single-threaded you can
2108  *      just call it in your main event loop.
2109  *
2110  *      Alternatively you can fork a new process that asynchronously handles
2111  *      calling this service in a loop.  In that case you are happy if this
2112  *      call blocks your thread until it needs to take care of something and
2113  *      would call it with a large nonzero timeout.  Your loop then takes no
2114  *      CPU while there is nothing happening.
2115  *
2116  *      If you are calling it in a single-threaded app, you don't want it to
2117  *      wait around blocking other things in your loop from happening, so you
2118  *      would call it with a timeout_ms of 0, so it returns immediately if
2119  *      nothing is pending, or as soon as it services whatever was pending.
2120  */
2121
2122
2123 int
2124 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
2125 {
2126         int n;
2127
2128         /* stay dead once we are dead */
2129
2130         if (context == NULL)
2131                 return 1;
2132
2133         /* wait for something to need service */
2134
2135         n = poll(context->fds, context->fds_count, timeout_ms);
2136         if (n == 0) /* poll timeout */
2137                 return 0;
2138
2139         if (n < 0) {
2140                 /*
2141                 fprintf(stderr, "Listen Socket dead\n");
2142                 */
2143                 return 1;
2144         }
2145
2146         /* handle accept on listening socket? */
2147
2148         for (n = 0; n < context->fds_count; n++)
2149                 if (context->fds[n].revents)
2150                         libwebsocket_service_fd(context, &context->fds[n]);
2151
2152         return 0;
2153 }
2154
2155 int
2156 lws_any_extension_handled(struct libwebsocket_context *context,
2157                                                        struct libwebsocket *wsi,
2158                                                        enum libwebsocket_extension_callback_reasons r,
2159                                                        void *v, size_t len)
2160 {
2161         int n;
2162         int handled = 0;
2163
2164         /* maybe an extension will take care of it for us */
2165
2166         for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
2167                 if (!wsi->active_extensions[n]->callback)
2168                         continue;
2169
2170                 handled |= wsi->active_extensions[n]->callback(context,
2171                         wsi->active_extensions[n], wsi,
2172                         r, wsi->active_extensions_user[n], v, len);
2173         }
2174
2175         return handled;
2176 }
2177
2178
2179 void *
2180 lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
2181                                                         struct libwebsocket_extension * ext)
2182 {
2183         int n = 0;
2184
2185         if (wsi == NULL)
2186                 return NULL;
2187
2188         while (n < wsi->count_active_extensions) {
2189                 if (wsi->active_extensions[n] != ext) {
2190                         n++;
2191                         continue;
2192                 }
2193                 return wsi->active_extensions_user[n];
2194         }
2195
2196         return NULL;
2197 }
2198
2199 /**
2200  * libwebsocket_callback_on_writable() - Request a callback when this socket
2201  *                                       becomes able to be written to without
2202  *                                       blocking
2203  *
2204  * @context:    libwebsockets context
2205  * @wsi:        Websocket connection instance to get callback for
2206  */
2207
2208 int
2209 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
2210                                                        struct libwebsocket *wsi)
2211 {
2212         int n;
2213         int handled = 0;
2214
2215         /* maybe an extension will take care of it for us */
2216
2217         for (n = 0; n < wsi->count_active_extensions; n++) {
2218                 if (!wsi->active_extensions[n]->callback)
2219                         continue;
2220
2221                 handled |= wsi->active_extensions[n]->callback(context,
2222                         wsi->active_extensions[n], wsi,
2223                         LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
2224                                        wsi->active_extensions_user[n], NULL, 0);
2225         }
2226
2227         if (handled)
2228                 return 1;
2229
2230         for (n = 0; n < context->fds_count; n++)
2231                 if (context->fds[n].fd == wsi->sock) {
2232                         context->fds[n].events |= POLLOUT;
2233                         n = context->fds_count + 1;
2234                 }
2235
2236         if (n == context->fds_count)
2237                 fprintf(stderr, "libwebsocket_callback_on_writable: failed to find socket %d\n", wsi->sock);
2238
2239         /* external POLL support via protocol 0 */
2240         context->protocols[0].callback(context, wsi,
2241                 LWS_CALLBACK_SET_MODE_POLL_FD,
2242                 (void *)(long)wsi->sock, NULL, POLLOUT);
2243
2244         return 1;
2245 }
2246
2247 /**
2248  * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
2249  *                      all connections using the given protocol when it
2250  *                      becomes possible to write to each socket without
2251  *                      blocking in turn.
2252  *
2253  * @protocol:   Protocol whose connections will get callbacks
2254  */
2255
2256 int
2257 libwebsocket_callback_on_writable_all_protocol(
2258                                   const struct libwebsocket_protocols *protocol)
2259 {
2260         struct libwebsocket_context *context = protocol->owning_server;
2261         int n;
2262         int m;
2263         struct libwebsocket *wsi;
2264
2265         for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
2266
2267                 for (m = 0; m < context->fd_hashtable[n].length; m++) {
2268
2269                         wsi = context->fd_hashtable[n].wsi[m];
2270
2271                         if (wsi->protocol == protocol)
2272                                 libwebsocket_callback_on_writable(context, wsi);
2273                 }
2274         }
2275
2276         return 0;
2277 }
2278
2279 /**
2280  * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
2281  *
2282  * You will not need this unless you are doing something special
2283  *
2284  * @wsi:        Websocket connection instance
2285  * @reason:     timeout reason
2286  * @secs:       how many seconds
2287  */
2288
2289 void
2290 libwebsocket_set_timeout(struct libwebsocket *wsi,
2291                                           enum pending_timeout reason, int secs)
2292 {
2293         struct timeval tv;
2294
2295         gettimeofday(&tv, NULL);
2296
2297         wsi->pending_timeout_limit = tv.tv_sec + secs;
2298         wsi->pending_timeout = reason;
2299 }
2300
2301
2302 /**
2303  * libwebsocket_get_socket_fd() - returns the socket file descriptor
2304  *
2305  * You will not need this unless you are doing something special
2306  *
2307  * @wsi:        Websocket connection instance
2308  */
2309
2310 int
2311 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
2312 {
2313         return wsi->sock;
2314 }
2315
2316 /**
2317  * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
2318  *                              receieved packets.
2319  *
2320  * If the output side of a server process becomes choked, this allows flow
2321  * control for the input side.
2322  *
2323  * @wsi:        Websocket connection instance to get callback for
2324  * @enable:     0 = disable read servicing for this connection, 1 = enable
2325  */
2326
2327 int
2328 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
2329 {
2330         struct libwebsocket_context *context = wsi->protocol->owning_server;
2331         int n;
2332
2333         for (n = 0; n < context->fds_count; n++)
2334                 if (context->fds[n].fd == wsi->sock) {
2335                         if (enable)
2336                                 context->fds[n].events |= POLLIN;
2337                         else
2338                                 context->fds[n].events &= ~POLLIN;
2339
2340                         return 0;
2341                 }
2342
2343         if (enable)
2344                 /* external POLL support via protocol 0 */
2345                 context->protocols[0].callback(context, wsi,
2346                         LWS_CALLBACK_SET_MODE_POLL_FD,
2347                         (void *)(long)wsi->sock, NULL, POLLIN);
2348         else
2349                 /* external POLL support via protocol 0 */
2350                 context->protocols[0].callback(context, wsi,
2351                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
2352                         (void *)(long)wsi->sock, NULL, POLLIN);
2353
2354 #if 0
2355         fprintf(stderr, "libwebsocket_rx_flow_control "
2356                                                      "unable to find socket\n");
2357 #endif
2358         return 1;
2359 }
2360
2361 /**
2362  * libwebsocket_canonical_hostname() - returns this host's hostname
2363  *
2364  * This is typically used by client code to fill in the host parameter
2365  * when making a client connection.  You can only call it after the context
2366  * has been created.
2367  *
2368  * @context:    Websocket context
2369  */
2370
2371
2372 extern const char *
2373 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
2374 {
2375         return (const char *)context->canonical_hostname;
2376 }
2377
2378
2379 static void sigpipe_handler(int x)
2380 {
2381 }
2382
2383 #ifdef LWS_OPENSSL_SUPPORT
2384 static int
2385 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
2386 {
2387
2388         SSL *ssl;
2389         int n;
2390         struct libwebsocket_context *context;
2391
2392         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
2393                 SSL_get_ex_data_X509_STORE_CTX_idx());
2394
2395         /*
2396          * !!! nasty openssl requires the index to come as a library-scope
2397          * static
2398          */
2399         context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
2400         
2401         n = context->protocols[0].callback(NULL, NULL,
2402                 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
2403                                                    x509_ctx, ssl, preverify_ok);
2404
2405         /* convert return code from 0 = OK to 1 = OK */
2406
2407         if (!n)
2408                 n = 1;
2409         else
2410                 n = 0;
2411
2412         return n;
2413 }
2414 #endif
2415
2416
2417 /**
2418  * libwebsocket_create_context() - Create the websocket handler
2419  * @port:       Port to listen on... you can use 0 to suppress listening on
2420  *              any port, that's what you want if you are not running a
2421  *              websocket server at all but just using it as a client
2422  * @interf:  NULL to bind the listen socket to all interfaces, or the
2423  *              interface name, eg, "eth2"
2424  * @protocols:  Array of structures listing supported protocols and a protocol-
2425  *              specific callback for each one.  The list is ended with an
2426  *              entry that has a NULL callback pointer.
2427  *              It's not const because we write the owning_server member
2428  * @extensions: NULL or array of libwebsocket_extension structs listing the
2429  *              extensions this context supports
2430  * @ssl_cert_filepath:  If libwebsockets was compiled to use ssl, and you want
2431  *                      to listen using SSL, set to the filepath to fetch the
2432  *                      server cert from, otherwise NULL for unencrypted
2433  * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
2434  *                      else ignored
2435  * @gid:        group id to change to after setting listen socket, or -1.
2436  * @uid:        user id to change to after setting listen socket, or -1.
2437  * @options:    0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
2438  *
2439  *      This function creates the listening socket and takes care
2440  *      of all initialization in one step.
2441  *
2442  *      After initialization, it returns a struct libwebsocket_context * that
2443  *      represents this server.  After calling, user code needs to take care
2444  *      of calling libwebsocket_service() with the context pointer to get the
2445  *      server's sockets serviced.  This can be done in the same process context
2446  *      or a forked process, or another thread,
2447  *
2448  *      The protocol callback functions are called for a handful of events
2449  *      including http requests coming in, websocket connections becoming
2450  *      established, and data arriving; it's also called periodically to allow
2451  *      async transmission.
2452  *
2453  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
2454  *      at that time websocket protocol has not been negotiated.  Other
2455  *      protocols after the first one never see any HTTP callack activity.
2456  *
2457  *      The server created is a simple http server by default; part of the
2458  *      websocket standard is upgrading this http connection to a websocket one.
2459  *
2460  *      This allows the same server to provide files like scripts and favicon /
2461  *      images or whatever over http and dynamic data over websockets all in
2462  *      one place; they're all handled in the user callback.
2463  */
2464
2465 struct libwebsocket_context *
2466 libwebsocket_create_context(int port, const char *interf,
2467                                struct libwebsocket_protocols *protocols,
2468                                struct libwebsocket_extension *extensions,
2469                                const char *ssl_cert_filepath,
2470                                const char *ssl_private_key_filepath,
2471                                int gid, int uid, unsigned int options)
2472 {
2473         int n;
2474         int m;
2475         int sockfd = 0;
2476         int fd;
2477         struct sockaddr_in serv_addr, cli_addr;
2478         int opt = 1;
2479         struct libwebsocket_context *context = NULL;
2480         unsigned int slen;
2481         char *p;
2482         char hostname[1024];
2483         struct hostent *he;
2484         struct libwebsocket *wsi;
2485
2486 #ifdef LWS_OPENSSL_SUPPORT
2487         SSL_METHOD *method;
2488         char ssl_err_buf[512];
2489 #endif
2490
2491 #ifdef _WIN32
2492         {
2493                 WORD wVersionRequested;
2494                 WSADATA wsaData;
2495                 int err;
2496         HMODULE wsdll;
2497
2498                 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
2499                 wVersionRequested = MAKEWORD(2, 2);
2500
2501                 err = WSAStartup(wVersionRequested, &wsaData);
2502                 if (err != 0) {
2503                         /* Tell the user that we could not find a usable */
2504                         /* Winsock DLL.                                  */
2505                         fprintf(stderr, "WSAStartup failed with error: %d\n",
2506                                                                            err);
2507                         return NULL;
2508                 }
2509
2510         wsdll = GetModuleHandle("Ws2_32.dll");
2511         if (wsdll)
2512         {
2513             poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
2514         }
2515
2516         if (!poll)
2517         {
2518             poll = emulated_poll;
2519         }
2520         }
2521 #endif
2522
2523
2524         context = malloc(sizeof(struct libwebsocket_context));
2525         if (!context) {
2526                 fprintf(stderr, "No memory for websocket context\n");
2527                 return NULL;
2528         }
2529         context->protocols = protocols;
2530         context->listen_port = port;
2531         context->http_proxy_port = 0;
2532         context->http_proxy_address[0] = '\0';
2533         context->options = options;
2534         context->fds_count = 0;
2535         context->extensions = extensions;
2536
2537 #ifdef WIN32
2538         context->fd_random = 0;
2539 #else
2540         context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
2541         if (context->fd_random < 0) {
2542                 fprintf(stderr, "Unable to open random device %s %d\n",
2543                                     SYSTEM_RANDOM_FILEPATH, context->fd_random);
2544                 return NULL;
2545         }
2546 #endif
2547
2548 #ifdef LWS_OPENSSL_SUPPORT
2549         context->use_ssl = 0;
2550         context->ssl_ctx = NULL;
2551         context->ssl_client_ctx = NULL;
2552         openssl_websocket_private_data_index = 0;
2553 #endif
2554         /* find canonical hostname */
2555
2556         hostname[(sizeof hostname) - 1] = '\0';
2557         gethostname(hostname, (sizeof hostname) - 1);
2558         he = gethostbyname(hostname);
2559         if (he) {
2560                 strncpy(context->canonical_hostname, he->h_name,
2561                                         sizeof context->canonical_hostname - 1);
2562                 context->canonical_hostname[
2563                                 sizeof context->canonical_hostname - 1] = '\0';
2564         } else
2565                 strncpy(context->canonical_hostname, hostname,
2566                                         sizeof context->canonical_hostname - 1);
2567
2568         /* split the proxy ads:port if given */
2569
2570         p = getenv("http_proxy");
2571         if (p) {
2572                 strncpy(context->http_proxy_address, p,
2573                                         sizeof context->http_proxy_address - 1);
2574                 context->http_proxy_address[
2575                                  sizeof context->http_proxy_address - 1] = '\0';
2576
2577                 p = strchr(context->http_proxy_address, ':');
2578                 if (p == NULL) {
2579                         fprintf(stderr, "http_proxy needs to be ads:port\n");
2580                         return NULL;
2581                 }
2582                 *p = '\0';
2583                 context->http_proxy_port = atoi(p + 1);
2584
2585                 fprintf(stderr, "Using proxy %s:%u\n",
2586                                 context->http_proxy_address,
2587                                                       context->http_proxy_port);
2588         }
2589
2590         if (port) {
2591
2592 #ifdef LWS_OPENSSL_SUPPORT
2593                 context->use_ssl = ssl_cert_filepath != NULL &&
2594                                                ssl_private_key_filepath != NULL;
2595                 if (context->use_ssl)
2596                         fprintf(stderr, " Compiled with SSL support, "
2597                                                                   "using it\n");
2598                 else
2599                         fprintf(stderr, " Compiled with SSL support, "
2600                                                               "not using it\n");
2601
2602 #else
2603                 if (ssl_cert_filepath != NULL &&
2604                                              ssl_private_key_filepath != NULL) {
2605                         fprintf(stderr, " Not compiled for OpenSSl support!\n");
2606                         return NULL;
2607                 }
2608                 fprintf(stderr, " Compiled without SSL support, "
2609                                                        "serving unencrypted\n");
2610 #endif
2611         }
2612
2613         /* ignore SIGPIPE */
2614 #ifdef WIN32
2615 #else
2616         signal(SIGPIPE, sigpipe_handler);
2617 #endif
2618
2619
2620 #ifdef LWS_OPENSSL_SUPPORT
2621
2622         /* basic openssl init */
2623
2624         SSL_library_init();
2625
2626         OpenSSL_add_all_algorithms();
2627         SSL_load_error_strings();
2628
2629         openssl_websocket_private_data_index =
2630                 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
2631
2632         /*
2633          * Firefox insists on SSLv23 not SSLv3
2634          * Konq disables SSLv2 by default now, SSLv23 works
2635          */
2636
2637         method = (SSL_METHOD *)SSLv23_server_method();
2638         if (!method) {
2639                 fprintf(stderr, "problem creating ssl method: %s\n",
2640                         ERR_error_string(ERR_get_error(), ssl_err_buf));
2641                 return NULL;
2642         }
2643         context->ssl_ctx = SSL_CTX_new(method); /* create context */
2644         if (!context->ssl_ctx) {
2645                 fprintf(stderr, "problem creating ssl context: %s\n",
2646                         ERR_error_string(ERR_get_error(), ssl_err_buf));
2647                 return NULL;
2648         }
2649
2650         /* client context */
2651         if (port == CONTEXT_PORT_NO_LISTEN)
2652         {
2653                 method = (SSL_METHOD *)SSLv23_client_method();
2654                 if (!method) {
2655                         fprintf(stderr, "problem creating ssl method: %s\n",
2656                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
2657                         return NULL;
2658                 }
2659                 /* create context */
2660                 context->ssl_client_ctx = SSL_CTX_new(method);
2661                 if (!context->ssl_client_ctx) {
2662                         fprintf(stderr, "problem creating ssl context: %s\n",
2663                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
2664                         return NULL;
2665                 }
2666
2667                 /* openssl init for cert verification (for client sockets) */
2668
2669                 if (!SSL_CTX_load_verify_locations(
2670                                         context->ssl_client_ctx, NULL,
2671                                                       LWS_OPENSSL_CLIENT_CERTS))
2672                         fprintf(stderr,
2673                             "Unable to load SSL Client certs from %s "
2674                             "(set by --with-client-cert-dir= in configure) -- "
2675                                 " client ssl isn't going to work",
2676                                                       LWS_OPENSSL_CLIENT_CERTS);
2677
2678                 /*
2679                  * callback allowing user code to load extra verification certs
2680                  * helping the client to verify server identity
2681                  */
2682
2683                 context->protocols[0].callback(context, NULL,
2684                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
2685                         context->ssl_client_ctx, NULL, 0);
2686         }
2687         /* as a server, are we requiring clients to identify themselves? */
2688
2689         if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
2690
2691                 /* absolutely require the client cert */
2692                 
2693                 SSL_CTX_set_verify(context->ssl_ctx,
2694                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2695                                                        OpenSSL_verify_callback);
2696
2697                 /*
2698                  * give user code a chance to load certs into the server
2699                  * allowing it to verify incoming client certs
2700                  */
2701
2702                 context->protocols[0].callback(context, NULL,
2703                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
2704                                                      context->ssl_ctx, NULL, 0);
2705         }
2706
2707         if (context->use_ssl) {
2708
2709                 /* openssl init for server sockets */
2710
2711                 /* set the local certificate from CertFile */
2712                 n = SSL_CTX_use_certificate_file(context->ssl_ctx,
2713                                         ssl_cert_filepath, SSL_FILETYPE_PEM);
2714                 if (n != 1) {
2715                         fprintf(stderr, "problem getting cert '%s': %s\n",
2716                                 ssl_cert_filepath,
2717                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
2718                         return NULL;
2719                 }
2720                 /* set the private key from KeyFile */
2721                 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2722                              ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
2723                         fprintf(stderr, "ssl problem getting key '%s': %s\n",
2724                                                 ssl_private_key_filepath,
2725                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
2726                         return NULL;
2727                 }
2728                 /* verify private key */
2729                 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
2730                         fprintf(stderr, "Private SSL key doesn't match cert\n");
2731                         return NULL;
2732                 }
2733
2734                 /* SSL is happy and has a cert it's content with */
2735         }
2736 #endif
2737
2738         /* selftest */
2739
2740         if (lws_b64_selftest())
2741                 return NULL;
2742
2743         /* fd hashtable init */
2744
2745         for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
2746                 context->fd_hashtable[n].length = 0;
2747
2748         /* set up our external listening socket we serve on */
2749
2750         if (port) {
2751
2752                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2753                 if (sockfd < 0) {
2754                         fprintf(stderr, "ERROR opening socket");
2755                         return NULL;
2756                 }
2757
2758                 /* allow us to restart even if old sockets in TIME_WAIT */
2759                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(opt));
2760
2761
2762                 /* Disable Nagle */
2763                 opt = 1;
2764                 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (const void *)&opt, sizeof(opt));
2765
2766                 bzero((char *) &serv_addr, sizeof(serv_addr));
2767                 serv_addr.sin_family = AF_INET;
2768                 if (interf == NULL)
2769                         serv_addr.sin_addr.s_addr = INADDR_ANY;
2770                 else
2771                         interface_to_sa(interf, &serv_addr,
2772                                                 sizeof(serv_addr));
2773                 serv_addr.sin_port = htons(port);
2774
2775                 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2776                                                              sizeof(serv_addr));
2777                 if (n < 0) {
2778                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2779                                                                 port, n, errno);
2780                         return NULL;
2781                 }
2782
2783                 wsi = malloc(sizeof(struct libwebsocket));
2784                 memset(wsi, 0, sizeof (struct libwebsocket));
2785                 wsi->sock = sockfd;
2786                 wsi->count_active_extensions = 0;
2787                 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
2788                 insert_wsi(context, wsi);
2789
2790                 listen(sockfd, 5);
2791                 fprintf(stderr, " Listening on port %d\n", port);
2792
2793                 /* list in the internal poll array */
2794                 
2795                 context->fds[context->fds_count].fd = sockfd;
2796                 context->fds[context->fds_count++].events = POLLIN;
2797
2798                 /* external POLL support via protocol 0 */
2799                 context->protocols[0].callback(context, wsi,
2800                         LWS_CALLBACK_ADD_POLL_FD,
2801                         (void *)(long)sockfd, NULL, POLLIN);
2802
2803         }
2804
2805         /* drop any root privs for this process */
2806 #ifdef WIN32
2807 #else
2808         if (gid != -1)
2809                 if (setgid(gid))
2810                         fprintf(stderr, "setgid: %s\n", strerror(errno));
2811         if (uid != -1)
2812                 if (setuid(uid))
2813                         fprintf(stderr, "setuid: %s\n", strerror(errno));
2814 #endif
2815
2816         /* set up our internal broadcast trigger sockets per-protocol */
2817
2818         for (context->count_protocols = 0;
2819                         protocols[context->count_protocols].callback;
2820                                                    context->count_protocols++) {
2821
2822                 fprintf(stderr, "  Protocol: %s\n", protocols[context->count_protocols].name);
2823
2824                 protocols[context->count_protocols].owning_server = context;
2825                 protocols[context->count_protocols].protocol_index =
2826                                                        context->count_protocols;
2827
2828                 fd = socket(AF_INET, SOCK_STREAM, 0);
2829                 if (fd < 0) {
2830                         fprintf(stderr, "ERROR opening socket");
2831                         return NULL;
2832                 }
2833
2834                 /* allow us to restart even if old sockets in TIME_WAIT */
2835                 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(opt));
2836
2837                 bzero((char *) &serv_addr, sizeof(serv_addr));
2838                 serv_addr.sin_family = AF_INET;
2839                 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2840                 serv_addr.sin_port = 0; /* pick the port for us */
2841
2842                 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2843                 if (n < 0) {
2844                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2845                                                                 port, n, errno);
2846                         return NULL;
2847                 }
2848
2849                 slen = sizeof cli_addr;
2850                 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2851                 if (n < 0) {
2852                         fprintf(stderr, "getsockname failed\n");
2853                         return NULL;
2854                 }
2855                 protocols[context->count_protocols].broadcast_socket_port =
2856                                                        ntohs(cli_addr.sin_port);
2857                 listen(fd, 5);
2858
2859                 debug("  Protocol %s broadcast socket %d\n",
2860                                 protocols[context->count_protocols].name,
2861                                                       ntohs(cli_addr.sin_port));
2862
2863                 /* dummy wsi per broadcast proxy socket */
2864
2865                 wsi = malloc(sizeof(struct libwebsocket));
2866                 memset(wsi, 0, sizeof (struct libwebsocket));
2867                 wsi->sock = fd;
2868                 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
2869                 wsi->count_active_extensions = 0;
2870                 /* note which protocol we are proxying */
2871                 wsi->protocol_index_for_broadcast_proxy =
2872                                                        context->count_protocols;
2873                 insert_wsi(context, wsi);
2874
2875                 /* list in internal poll array */
2876
2877                 context->fds[context->fds_count].fd = fd;
2878                 context->fds[context->fds_count].events = POLLIN;
2879                 context->fds[context->fds_count].revents = 0;
2880                 context->fds_count++;
2881
2882                 /* external POLL support via protocol 0 */
2883                 context->protocols[0].callback(context, wsi,
2884                         LWS_CALLBACK_ADD_POLL_FD,
2885                         (void *)(long)fd, NULL, POLLIN);
2886         }
2887
2888         /*
2889          * give all extensions a chance to create any per-context
2890          * allocations they need
2891          */
2892
2893         m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
2894         if (port)
2895                 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
2896         while (extensions->callback) {
2897                 fprintf(stderr, "  Extension: %s\n", extensions->name);
2898                 extensions->callback(context, extensions,
2899                                                         NULL, m, NULL, NULL, 0);
2900                 extensions++;
2901         }
2902
2903         return context;
2904 }
2905
2906
2907 #ifndef LWS_NO_FORK
2908
2909 /**
2910  * libwebsockets_fork_service_loop() - Optional helper function forks off
2911  *                                a process for the websocket server loop.
2912  *                              You don't have to use this but if not, you
2913  *                              have to make sure you are calling
2914  *                              libwebsocket_service periodically to service
2915  *                              the websocket traffic
2916  * @context:    server context returned by creation function
2917  */
2918
2919 int
2920 libwebsockets_fork_service_loop(struct libwebsocket_context *context)
2921 {
2922         int fd;
2923         struct sockaddr_in cli_addr;
2924         int n;
2925         int p;
2926
2927         n = fork();
2928         if (n < 0)
2929                 return n;
2930
2931         if (!n) {
2932
2933                 /* main process context */
2934
2935                 /*
2936                  * set up the proxy sockets to allow broadcast from
2937                  * service process context
2938                  */
2939
2940                 for (p = 0; p < context->count_protocols; p++) {
2941                         fd = socket(AF_INET, SOCK_STREAM, 0);
2942                         if (fd < 0) {
2943                                 fprintf(stderr, "Unable to create socket\n");
2944                                 return -1;
2945                         }
2946                         cli_addr.sin_family = AF_INET;
2947                         cli_addr.sin_port = htons(
2948                              context->protocols[p].broadcast_socket_port);
2949                         cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2950                         n = connect(fd, (struct sockaddr *)&cli_addr,
2951                                                                sizeof cli_addr);
2952                         if (n < 0) {
2953                                 fprintf(stderr, "Unable to connect to "
2954                                                 "broadcast socket %d, %s\n",
2955                                                 n, strerror(errno));
2956                                 return -1;
2957                         }
2958
2959                         context->protocols[p].broadcast_socket_user_fd = fd;
2960                 }
2961
2962                 return 0;
2963         }
2964
2965         /* we want a SIGHUP when our parent goes down */
2966         prctl(PR_SET_PDEATHSIG, SIGHUP);
2967
2968         /* in this forked process, sit and service websocket connections */
2969
2970         while (1)
2971                 if (libwebsocket_service(context, 1000))
2972                         return -1;
2973
2974         return 0;
2975 }
2976
2977 #endif
2978
2979 /**
2980  * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2981  *                                connection.
2982  * @wsi:        pointer to struct websocket you want to know the protocol of
2983  *
2984  *
2985  *      This is useful to get the protocol to broadcast back to from inside
2986  * the callback.
2987  */
2988
2989 const struct libwebsocket_protocols *
2990 libwebsockets_get_protocol(struct libwebsocket *wsi)
2991 {
2992         return wsi->protocol;
2993 }
2994
2995 /**
2996  * libwebsockets_broadcast() - Sends a buffer to the callback for all active
2997  *                                connections of the given protocol.
2998  * @protocol:   pointer to the protocol you will broadcast to all members of
2999  * @buf:  buffer containing the data to be broadcase.  NOTE: this has to be
3000  *              allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
3001  *              the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
3002  *              case you are calling this function from callback context.
3003  * @len:        length of payload data in buf, starting from buf.
3004  *
3005  *      This function allows bulk sending of a packet to every connection using
3006  * the given protocol.  It does not send the data directly; instead it calls
3007  * the callback with a reason type of LWS_CALLBACK_BROADCAST.  If the callback
3008  * wants to actually send the data for that connection, the callback itself
3009  * should call libwebsocket_write().
3010  *
3011  * libwebsockets_broadcast() can be called from another fork context without
3012  * having to take any care about data visibility between the processes, it'll
3013  * "just work".
3014  */
3015
3016
3017 int
3018 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
3019                                                  unsigned char *buf, size_t len)
3020 {
3021         struct libwebsocket_context *context = protocol->owning_server;
3022         int n;
3023         int m;
3024         struct libwebsocket * wsi;
3025
3026         if (!protocol->broadcast_socket_user_fd) {
3027                 /*
3028                  * We are either running unforked / flat, or we are being
3029                  * called from poll thread context
3030                  * eg, from a callback.  In that case don't use sockets for
3031                  * broadcast IPC (since we can't open a socket connection to
3032                  * a socket listening on our own thread) but directly do the
3033                  * send action.
3034                  *
3035                  * Locking is not needed because we are by definition being
3036                  * called in the poll thread context and are serialized.
3037                  */
3038
3039                 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
3040
3041                         for (m = 0; m < context->fd_hashtable[n].length; m++) {
3042
3043                                 wsi = context->fd_hashtable[n].wsi[m];
3044
3045                                 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
3046                                         continue;
3047
3048                                 /*
3049                                  * never broadcast to
3050                                  * non-established connections
3051                                  */
3052                                 if (wsi->state != WSI_STATE_ESTABLISHED)
3053                                         continue;
3054
3055                                 /* only broadcast to guys using
3056                                  * requested protocol
3057                                  */
3058                                 if (wsi->protocol != protocol)
3059                                         continue;
3060
3061                                 wsi->protocol->callback(context, wsi,
3062                                          LWS_CALLBACK_BROADCAST,
3063                                          wsi->user_space,
3064                                          buf, len);
3065                         }
3066                 }
3067
3068                 return 0;
3069         }
3070
3071         /*
3072          * We're being called from a different process context than the server
3073          * loop.  Instead of broadcasting directly, we send our
3074          * payload on a socket to do the IPC; the server process will serialize
3075          * the broadcast action in its main poll() loop.
3076          *
3077          * There's one broadcast socket listening for each protocol supported
3078          * set up when the websocket server initializes
3079          */
3080
3081         n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
3082
3083         return n;
3084 }
3085
3086 int
3087 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
3088 {
3089         return wsi->final;
3090 }
3091
3092 void *
3093 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
3094 {
3095         /* allocate the per-connection user memory (if any) */
3096
3097         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
3098                 wsi->user_space = malloc(
3099                                   wsi->protocol->per_session_data_size);
3100                 if (wsi->user_space  == NULL) {
3101                         fprintf(stderr, "Out of memory for "
3102                                                    "conn user space\n");
3103                         return NULL;
3104                 }
3105                 memset(wsi->user_space, 0, wsi->protocol->per_session_data_size);
3106         }
3107         return wsi->user_space;
3108 }