introduce 76 00 client support
[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 #include <ifaddrs.h>
24
25 /*
26  * In-place str to lower case
27  */
28
29 static void
30 strtolower(char *s)
31 {
32         while (*s) {
33                 *s = tolower(*s);
34                 s++;
35         }
36 }
37
38 /* file descriptor hash management */
39
40 struct libwebsocket *
41 wsi_from_fd(struct libwebsocket_context *this, int fd)
42 {
43         int h = LWS_FD_HASH(fd);
44         int n = 0;
45
46         for (n = 0; n < this->fd_hashtable[h].length; n++)
47                 if (this->fd_hashtable[h].wsi[n]->sock == fd)
48                         return this->fd_hashtable[h].wsi[n];
49
50         return NULL;
51 }
52
53 int
54 insert_wsi(struct libwebsocket_context *this, struct libwebsocket *wsi)
55 {
56         int h = LWS_FD_HASH(wsi->sock);
57
58         if (this->fd_hashtable[h].length == MAX_CLIENTS - 1) {
59                 fprintf(stderr, "hash table overflow\n");
60                 return 1;
61         }
62
63         this->fd_hashtable[h].wsi[this->fd_hashtable[h].length++] = wsi;
64
65         return 0;
66 }
67
68 int
69 delete_from_fd(struct libwebsocket_context *this, int fd)
70 {
71         int h = LWS_FD_HASH(fd);
72         int n = 0;
73
74         for (n = 0; n < this->fd_hashtable[h].length; n++)
75                 if (this->fd_hashtable[h].wsi[n]->sock == fd) {
76                         while (n < this->fd_hashtable[h].length) {
77                                 this->fd_hashtable[h].wsi[n] =
78                                                this->fd_hashtable[h].wsi[n + 1];
79                                 n++;
80                         }
81                         this->fd_hashtable[h].length--;
82
83                         return 0;
84                 }
85
86         fprintf(stderr, "Failed to find fd %d requested for "
87                                                    "delete in hashtable\n", fd);
88         return 1;
89 }
90
91 #ifdef LWS_OPENSSL_SUPPORT
92 static void
93 libwebsockets_decode_ssl_error(void)
94 {
95         char buf[256];
96         u_long err;
97
98         while ((err = ERR_get_error()) != 0) {
99                 ERR_error_string_n(err, buf, sizeof(buf));
100                 fprintf(stderr, "*** %s\n", buf);
101         }
102 }
103 #endif
104
105
106 static int
107 interface_to_sa(const char* ifname, struct sockaddr_in *addr, size_t addrlen)
108 {
109         int rc = -1;
110         struct ifaddrs *ifr;
111         struct ifaddrs *ifc;
112         struct sockaddr_in *sin;
113
114         getifaddrs(&ifr);
115         for (ifc = ifr; ifc != NULL; ifc = ifc->ifa_next) {
116                 if (strcmp(ifc->ifa_name, ifname))
117                         continue;
118                 if (ifc->ifa_addr == NULL)
119                         continue;
120                 sin = (struct sockaddr_in *)ifc->ifa_addr;
121                 if (sin->sin_family != AF_INET)
122                         continue;
123                 memcpy(addr, sin, addrlen);
124                 rc = 0; 
125         }
126
127         freeifaddrs(ifr);
128
129         return rc;
130 }
131
132 void
133 libwebsocket_close_and_free_session(struct libwebsocket_context *this,
134                          struct libwebsocket *wsi, enum lws_close_status reason)
135 {
136         int n;
137         int old_state;
138         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
139                                                   LWS_SEND_BUFFER_POST_PADDING];
140
141         if (!wsi)
142                 return;
143
144         old_state = wsi->state;
145
146         if (old_state == WSI_STATE_DEAD_SOCKET)
147                 return;
148
149         /* remove this fd from wsi mapping hashtable */
150
151         delete_from_fd(this, wsi->sock);
152
153         /* delete it from the internal poll list if still present */
154
155         for (n = 0; n < this->fds_count; n++) {
156                 if (this->fds[n].fd != wsi->sock)
157                         continue;
158                 while (n < this->fds_count - 1) {
159                         this->fds[n] = this->fds[n + 1];
160                         n++;
161                 }
162                 this->fds_count--;
163                 /* we only have to deal with one */
164                 n = this->fds_count;
165         }
166
167         /* remove also from external POLL support via protocol 0 */
168
169         this->protocols[0].callback(this, wsi,
170                     LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
171
172         wsi->close_reason = reason;
173
174         /*
175          * signal we are closing, libsocket_write will
176          * add any necessary version-specific stuff.  If the write fails,
177          * no worries we are closing anyway.  If we didn't initiate this
178          * close, then our state has been changed to
179          * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this
180          */
181
182         if (old_state == WSI_STATE_ESTABLISHED)
183                 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
184                                                                LWS_WRITE_CLOSE);
185
186         wsi->state = WSI_STATE_DEAD_SOCKET;
187
188         /* tell the user it's all over for this guy */
189
190         if (wsi->protocol && wsi->protocol->callback &&
191                                              old_state == WSI_STATE_ESTABLISHED)
192                 wsi->protocol->callback(this, wsi, LWS_CALLBACK_CLOSED,
193                                                       wsi->user_space, NULL, 0);
194
195         /* free up his allocations */
196
197         for (n = 0; n < WSI_TOKEN_COUNT; n++)
198                 if (wsi->utf8_token[n].token)
199                         free(wsi->utf8_token[n].token);
200
201 /*      fprintf(stderr, "closing fd=%d\n", wsi->sock); */
202
203 #ifdef LWS_OPENSSL_SUPPORT
204         if (wsi->ssl) {
205                 n = SSL_get_fd(wsi->ssl);
206                 SSL_shutdown(wsi->ssl);
207                 close(n);
208                 SSL_free(wsi->ssl);
209         } else {
210 #endif
211                 shutdown(wsi->sock, SHUT_RDWR);
212                 close(wsi->sock);
213 #ifdef LWS_OPENSSL_SUPPORT
214         }
215 #endif
216         if (wsi->user_space)
217                 free(wsi->user_space);
218
219         free(wsi);
220 }
221
222 /**
223  * libwebsockets_hangup_on_client() - Server calls to terminate client
224  *                                      connection
225  * @this:       libwebsockets context
226  * @fd:         Connection socket descriptor
227  */
228
229 void
230 libwebsockets_hangup_on_client(struct libwebsocket_context *this, int fd)
231 {
232         struct libwebsocket *wsi = wsi_from_fd(this, fd);
233
234         if (wsi == NULL)
235                 return;
236
237         libwebsocket_close_and_free_session(this, wsi,
238                                                      LWS_CLOSE_STATUS_NOSTATUS);
239 }
240
241
242 /**
243  * libwebsockets_get_peer_addresses() - Get client address information
244  * @fd:         Connection socket descriptor
245  * @name:       Buffer to take client address name
246  * @name_len:   Length of client address name buffer
247  * @rip:        Buffer to take client address IP qotted quad
248  * @rip_len:    Length of client address IP buffer
249  *
250  *      This function fills in @name and @rip with the name and IP of
251  *      the client connected with socket descriptor @fd.  Names may be
252  *      truncated if there is not enough room.  If either cannot be
253  *      determined, they will be returned as valid zero-length strings.
254  */
255
256 void
257 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
258                                         char *rip, int rip_len)
259 {
260         unsigned int len;
261         struct sockaddr_in sin;
262         struct hostent *host;
263         struct hostent *host1;
264         char ip[128];
265         char *p;
266         int n;
267
268         rip[0] = '\0';
269         name[0] = '\0';
270
271         len = sizeof sin;
272         if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
273                 perror("getpeername");
274                 return;
275         }
276                 
277         host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
278                                                                        AF_INET);
279         if (host == NULL) {
280                 perror("gethostbyaddr");
281                 return;
282         }
283
284         strncpy(name, host->h_name, name_len);
285         name[name_len - 1] = '\0';
286
287         host1 = gethostbyname(host->h_name);
288         if (host1 == NULL)
289                 return;
290         p = (char *)host1;
291         n = 0;
292         while (p != NULL) {
293                 p = host1->h_addr_list[n++];
294                 if (p == NULL)
295                         continue;
296                 if (host1->h_addrtype != AF_INET)
297                         continue;
298
299                 sprintf(ip, "%d.%d.%d.%d",
300                                 p[0], p[1], p[2], p[3]);
301                 p = NULL;
302                 strncpy(rip, ip, rip_len);
303                 rip[rip_len - 1] = '\0';
304         }
305 }
306
307 void libwebsockets_00_spaceout(char *key, int spaces, int seed)
308 {
309         char *p;
310
311         key++;
312         while (spaces--) {
313                 if (*key && (seed & 1))
314                         key++;
315                 seed >>= 1;
316
317                 p = key + strlen(key);
318                 while (p >= key) {
319                         p[1] = p[0];
320                         p--;
321                 }
322                 *key++ = ' ';
323         }
324 }
325
326 void libwebsockets_00_spam(char *key, int count, int seed)
327 {
328         char *p;
329
330         key++;
331         while (count--) {
332                 
333                 if (*key && (seed & 1))
334                         key++;
335                 seed >>= 1;
336
337                 p = key + strlen(key);
338                 while (p >= key) {
339                         p[1] = p[0];
340                         p--;
341                 }
342                 *key++ = 0x21 + ((seed & 0xffff) % 15);
343                 /* 4 would use it up too fast.. not like it matters */
344                 seed >>= 1;
345         }
346 }
347
348 /**
349  * libwebsocket_service_fd() - Service polled socket with something waiting
350  * @this:       Websocket context
351  * @pollfd:     The pollfd entry describing the socket fd and which events
352  *              happened.
353  *
354  *      This function closes any active connections and then frees the
355  *      context.  After calling this, any further use of the context is
356  *      undefined.
357  */
358
359 int
360 libwebsocket_service_fd(struct libwebsocket_context *this,
361                                                           struct pollfd *pollfd)
362 {
363         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
364                                                   LWS_SEND_BUFFER_POST_PADDING];
365         struct libwebsocket *wsi;
366         struct libwebsocket *new_wsi;
367         int n;
368         int m;
369         size_t len;
370         int accept_fd;
371         unsigned int clilen;
372         struct sockaddr_in cli_addr;
373         struct timeval tv;
374         static const char magic_websocket_guid[] =
375                                          "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
376         static const char magic_websocket_04_masking_guid[] =
377                                          "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
378         char hash[20];
379         char pkt[1024];
380         char *p = &pkt[0];
381         const char *pc;
382         int okay = 0;
383 #ifdef LWS_OPENSSL_SUPPORT
384         char ssl_err_buf[512];
385 #endif
386         /*
387          * you can call us with pollfd = NULL to just allow the once-per-second
388          * global timeout checks; if less than a second since the last check
389          * it returns immediately then.
390          */
391
392         gettimeofday(&tv, NULL);
393
394         if (this->last_timeout_check_s != tv.tv_sec) {
395                 this->last_timeout_check_s = tv.tv_sec;
396
397                 /* global timeout check once per second */
398
399                 for (n = 0; n < this->fds_count; n++) {
400                         wsi = wsi_from_fd(this, this->fds[n].fd);
401                         if (!wsi->pending_timeout)
402                                 continue;
403
404                         /*
405                          * if we went beyond the allowed time, kill the
406                          * connection
407                          */
408
409                         if (tv.tv_sec > wsi->pending_timeout_limit)
410                                 libwebsocket_close_and_free_session(this, wsi,
411                                                      LWS_CLOSE_STATUS_NOSTATUS);
412                 }
413         }
414
415         /* just here for timeout management? */
416
417         if (pollfd == NULL)
418                 return 0;
419
420         /* no, here to service a socket descriptor */
421
422         wsi = wsi_from_fd(this, pollfd->fd);
423
424         if (wsi == NULL)
425                 return 1;
426
427         switch (wsi->mode) {
428         case LWS_CONNMODE_SERVER_LISTENER:
429
430                 /* pollin means a client has connected to us then */
431
432                 if (!pollfd->revents & POLLIN)
433                         break;
434
435                 /* listen socket got an unencrypted connection... */
436
437                 clilen = sizeof(cli_addr);
438                 accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
439                                                                        &clilen);
440                 if (accept_fd < 0) {
441                         fprintf(stderr, "ERROR on accept");
442                         break;
443                 }
444
445                 if (this->fds_count >= MAX_CLIENTS) {
446                         fprintf(stderr, "too busy to accept new client\n");
447                         close(accept_fd);
448                         break;
449                 }
450
451                 /*
452                  * look at who we connected to and give user code a chance
453                  * to reject based on client IP.  There's no protocol selected
454                  * yet so we issue this to protocols[0]
455                  */
456
457                 if ((this->protocols[0].callback)(this, wsi,
458                                 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
459                                              (void*)(long)accept_fd, NULL, 0)) {
460                         fprintf(stderr, "Callback denied network connection\n");
461                         close(accept_fd);
462                         break;
463                 }
464
465                 /* accepting connection to main listener */
466
467                 new_wsi = malloc(sizeof(struct libwebsocket));
468                 if (new_wsi == NULL) {
469                         fprintf(stderr, "Out of memory for new connection\n");
470                         break;
471                 }
472
473                 memset(new_wsi, 0, sizeof (struct libwebsocket));
474                 new_wsi->sock = accept_fd;
475                 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
476
477 #ifdef LWS_OPENSSL_SUPPORT
478                 new_wsi->ssl = NULL;
479
480                 if (this->use_ssl) {
481
482                         new_wsi->ssl = SSL_new(this->ssl_ctx);
483                         if (new_wsi->ssl == NULL) {
484                                 fprintf(stderr, "SSL_new failed: %s\n",
485                                     ERR_error_string(SSL_get_error(
486                                     new_wsi->ssl, 0), NULL));
487                                     libwebsockets_decode_ssl_error();
488                                 free(new_wsi);
489                                 break;
490                         }
491
492                         SSL_set_fd(new_wsi->ssl, accept_fd);
493
494                         n = SSL_accept(new_wsi->ssl);
495                         if (n != 1) {
496                                 /*
497                                  * browsers seem to probe with various
498                                  * ssl params which fail then retry
499                                  * and succeed
500                                  */
501                                 debug("SSL_accept failed skt %u: %s\n",
502                                       pollfd->fd,
503                                       ERR_error_string(SSL_get_error(
504                                       new_wsi->ssl, n), NULL));
505                                 SSL_free(
506                                        new_wsi->ssl);
507                                 free(new_wsi);
508                                 break;
509                         }
510                         
511                         debug("accepted new SSL conn  "
512                               "port %u on fd=%d SSL ver %s\n",
513                                 ntohs(cli_addr.sin_port), accept_fd,
514                                   SSL_get_version(new_wsi->ssl));
515
516                 } else
517 #endif
518                         debug("accepted new conn  port %u on fd=%d\n",
519                                           ntohs(cli_addr.sin_port), accept_fd);
520
521                 /* intialize the instance struct */
522
523                 new_wsi->state = WSI_STATE_HTTP;
524                 new_wsi->name_buffer_pos = 0;
525                 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
526
527                 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
528                         new_wsi->utf8_token[n].token = NULL;
529                         new_wsi->utf8_token[n].token_len = 0;
530                 }
531
532                 /*
533                  * these can only be set once the protocol is known
534                  * we set an unestablished connection's protocol pointer
535                  * to the start of the supported list, so it can look
536                  * for matching ones during the handshake
537                  */
538                 new_wsi->protocol = this->protocols;
539                 new_wsi->user_space = NULL;
540
541                 /*
542                  * Default protocol is 76 / 00
543                  * After 76, there's a header specified to inform which
544                  * draft the client wants, when that's seen we modify
545                  * the individual connection's spec revision accordingly
546                  */
547                 new_wsi->ietf_spec_revision = 0;
548
549                 insert_wsi(this, new_wsi);
550
551                 /*
552                  * make sure NO events are seen yet on this new socket
553                  * (otherwise we inherit old fds[client].revents from
554                  * previous socket there and die mysteriously! )
555                  */
556                 this->fds[this->fds_count].revents = 0;
557
558                 this->fds[this->fds_count].events = POLLIN;
559                 this->fds[this->fds_count++].fd = accept_fd;
560
561                 /* external POLL support via protocol 0 */
562                 this->protocols[0].callback(this, new_wsi,
563                         LWS_CALLBACK_ADD_POLL_FD,
564                         (void *)(long)accept_fd, NULL, POLLIN);
565
566                 break;
567
568         case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
569
570                 /* as we are listening, POLLIN means accept() is needed */
571         
572                 if (!pollfd->revents & POLLIN)
573                         break;
574
575                 /* listen socket got an unencrypted connection... */
576
577                 clilen = sizeof(cli_addr);
578                 accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
579                                                                        &clilen);
580                 if (accept_fd < 0) {
581                         fprintf(stderr, "ERROR on accept");
582                         break;
583                 }
584
585                 if (this->fds_count >= MAX_CLIENTS) {
586                         fprintf(stderr, "too busy to accept new broadcast "
587                                                               "proxy client\n");
588                         close(accept_fd);
589                         break;
590                 }
591
592                 /* create a dummy wsi for the connection and add it */
593
594                 new_wsi = malloc(sizeof(struct libwebsocket));
595                 memset(new_wsi, 0, sizeof (struct libwebsocket));
596                 new_wsi->sock = accept_fd;
597                 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
598                 new_wsi->state = WSI_STATE_ESTABLISHED;
599                 /* note which protocol we are proxying */
600                 new_wsi->protocol_index_for_broadcast_proxy =
601                                         wsi->protocol_index_for_broadcast_proxy;
602                 insert_wsi(this, new_wsi);
603
604                 /* add connected socket to internal poll array */
605
606                 this->fds[this->fds_count].revents = 0;
607                 this->fds[this->fds_count].events = POLLIN;
608                 this->fds[this->fds_count++].fd = accept_fd;
609
610                 /* external POLL support via protocol 0 */
611                 this->protocols[0].callback(this, new_wsi,
612                         LWS_CALLBACK_ADD_POLL_FD,
613                         (void *)(long)accept_fd, NULL, POLLIN);
614
615                 break;
616
617         case LWS_CONNMODE_BROADCAST_PROXY:
618
619                 /* handle session socket closed */
620
621                 if (pollfd->revents & (POLLERR | POLLHUP)) {
622
623                         debug("Session Socket %p (fd=%d) dead\n",
624                                 (void *)wsi, pollfd->fd);
625
626                         libwebsocket_close_and_free_session(this, wsi,
627                                                        LWS_CLOSE_STATUS_NORMAL);
628                         return 1;
629                 }
630
631                 /* the guy requested a callback when it was OK to write */
632
633                 if (pollfd->revents & POLLOUT) {
634
635                         /* one shot */
636
637                         pollfd->events &= ~POLLOUT;
638
639                         /* external POLL support via protocol 0 */
640                         this->protocols[0].callback(this, wsi,
641                                 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
642                                 (void *)(long)wsi->sock, NULL, POLLOUT);
643
644                         wsi->protocol->callback(this, wsi,
645                                 LWS_CALLBACK_CLIENT_WRITEABLE,
646                                 wsi->user_space,
647                                 NULL, 0);
648                 }
649
650                 /* any incoming data ready? */
651
652                 if (!(pollfd->revents & POLLIN))
653                         break;
654
655                 /* get the issued broadcast payload from the socket */
656
657                 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
658                                                          MAX_BROADCAST_PAYLOAD);
659                 if (len < 0) {
660                         fprintf(stderr, "Error reading broadcast payload\n");
661                         break;
662                 }
663
664                 /* broadcast it to all guys with this protocol index */
665
666                 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
667
668                         for (m = 0; m < this->fd_hashtable[n].length; m++) {
669
670                                 new_wsi = this->fd_hashtable[n].wsi[m];
671
672                                 /* only to clients we are serving to */
673
674                                 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
675                                         continue;
676
677                                 /*
678                                  * never broadcast to non-established
679                                  * connection
680                                  */
681
682                                 if (new_wsi->state != WSI_STATE_ESTABLISHED)
683                                         continue;
684
685                                 /*
686                                  * only broadcast to connections using
687                                  * the requested protocol
688                                  */
689
690                                 if (new_wsi->protocol->protocol_index !=
691                                         wsi->protocol_index_for_broadcast_proxy)
692                                         continue;
693
694                                 /* broadcast it to this connection */
695
696                                 new_wsi->protocol->callback(this, new_wsi,
697                                         LWS_CALLBACK_BROADCAST,
698                                         new_wsi->user_space,
699                                         buf + LWS_SEND_BUFFER_PRE_PADDING, len);
700                         }
701                 }
702                 break;
703
704         case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
705
706                 /* handle proxy hung up on us */
707
708                 if (pollfd->revents & (POLLERR | POLLHUP)) {
709
710                         fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
711                                 (void *)wsi, pollfd->fd);
712
713                         libwebsocket_close_and_free_session(this, wsi,
714                                                      LWS_CLOSE_STATUS_NOSTATUS);
715                         return 1;
716                 }
717
718                 n = recv(wsi->sock, pkt, sizeof pkt, 0);
719                 if (n < 0) {
720                         libwebsocket_close_and_free_session(this, wsi,
721                                                      LWS_CLOSE_STATUS_NOSTATUS);
722                         fprintf(stderr, "ERROR reading from proxy socket\n");
723                         return 1;
724                 }
725
726                 pkt[13] = '\0';
727                 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
728                         libwebsocket_close_and_free_session(this, wsi,
729                                                      LWS_CLOSE_STATUS_NOSTATUS);
730                         fprintf(stderr, "ERROR from proxy: %s\n", pkt);
731                         return 1;
732                 }
733
734                 /* clear his proxy connection timeout */
735
736                 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
737
738                 /* fallthru */
739
740         case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
741
742         #ifdef LWS_OPENSSL_SUPPORT
743                 if (wsi->use_ssl) {
744
745                         wsi->ssl = SSL_new(this->ssl_client_ctx);
746                         wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE);
747                         SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
748
749                         SSL_set_ex_data(wsi->ssl,
750                               this->openssl_websocket_private_data_index, this);
751
752                         if (SSL_connect(wsi->ssl) <= 0) {
753                                 fprintf(stderr, "SSL connect error %s\n",
754                                         ERR_error_string(ERR_get_error(),
755                                                                   ssl_err_buf));
756                                 libwebsocket_close_and_free_session(this, wsi,
757                                                      LWS_CLOSE_STATUS_NOSTATUS);
758                                 return 1;
759                         }
760
761                         n = SSL_get_verify_result(wsi->ssl);
762                         if (n != X509_V_OK) && (
763                                 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
764                                                            wsi->use_ssl != 2)) {
765
766                                 fprintf(stderr, "server's cert didn't "
767                                                            "look good %d\n", n);
768                                 libwebsocket_close_and_free_session(this, wsi,
769                                                      LWS_CLOSE_STATUS_NOSTATUS);
770                                 return 1;
771                         }
772                 } else {
773                         wsi->ssl = NULL;
774         #endif
775
776
777         #ifdef LWS_OPENSSL_SUPPORT
778                 }
779         #endif
780
781                 /*
782                  * create the random key
783                  */
784
785                 n = read(this->fd_random, hash, 16);
786                 if (n != 16) {
787                         fprintf(stderr, "Unable to read from random dev %s\n",
788                                                         SYSTEM_RANDOM_FILEPATH);
789                         free(wsi->c_path);
790                         free(wsi->c_host);
791                         if (wsi->c_origin)
792                                 free(wsi->c_origin);
793                         if (wsi->c_protocol)
794                                 free(wsi->c_protocol);
795                         libwebsocket_close_and_free_session(this, wsi,
796                                                      LWS_CLOSE_STATUS_NOSTATUS);
797                         return 1;
798                 }
799
800                 lws_b64_encode_string(hash, 16, wsi->key_b64,
801                                                            sizeof wsi->key_b64);
802
803                 /*
804                  * 00 example client handshake
805                  *
806                  * GET /socket.io/websocket HTTP/1.1
807                  * Upgrade: WebSocket
808                  * Connection: Upgrade
809                  * Host: 127.0.0.1:9999
810                  * Origin: http://127.0.0.1
811                  * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7  92 ^
812                  * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
813                  * Cookie: socketio=websocket
814                  * 
815                  * (Á®Ä0¶†≥
816                  * 
817                  * 04 example client handshake
818                  *
819                  * GET /chat HTTP/1.1
820                  * Host: server.example.com
821                  * Upgrade: websocket
822                  * Connection: Upgrade
823                  * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
824                  * Sec-WebSocket-Origin: http://example.com
825                  * Sec-WebSocket-Protocol: chat, superchat
826                  * Sec-WebSocket-Version: 4
827                  */
828
829                 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
830
831                 if (wsi->ietf_spec_revision == 0) {
832                         unsigned char spaces_1, spaces_2;
833                         unsigned int max_1, max_2;
834                         unsigned int num_1, num_2;
835                         unsigned long product_1, product_2;
836                         char key_1[40];
837                         char key_2[40];
838                         unsigned int seed;
839                         unsigned int count;
840                         char challenge[16];
841
842                         read(this->fd_random, &spaces_1, sizeof(char));
843                         read(this->fd_random, &spaces_2, sizeof(char));
844
845                         spaces_1 = (spaces_1 % 12) + 1;
846                         spaces_2 = (spaces_2 % 12) + 1;
847
848                         max_1 = 4294967295 / spaces_1;
849                         max_2 = 4294967295 / spaces_2;
850
851                         read(this->fd_random, &num_1, sizeof(int));
852                         read(this->fd_random, &num_2, sizeof(int));
853
854                         num_1 = (num_1 % max_1);
855                         num_2 = (num_2 % max_2);
856
857                         challenge[0] = num_1 >> 24;
858                         challenge[1] = num_1 >> 16;
859                         challenge[2] = num_1 >> 8;
860                         challenge[3] = num_1;
861                         challenge[4] = num_2 >> 24;
862                         challenge[5] = num_2 >> 16;
863                         challenge[6] = num_2 >> 8;
864                         challenge[7] = num_2;
865
866                         product_1 = num_1 * spaces_1;
867                         product_2 = num_2 * spaces_2;
868
869                         sprintf(key_1, "%lu", product_1);
870                         sprintf(key_2, "%lu", product_2);
871
872                         read(this->fd_random, &seed, sizeof(int));
873                         read(this->fd_random, &count, sizeof(int));
874
875                         libwebsockets_00_spam(key_1, (count % 12) + 1, seed);
876
877                         read(this->fd_random, &seed, sizeof(int));
878                         read(this->fd_random, &count, sizeof(int));
879
880                         libwebsockets_00_spam(key_2, (count % 12) + 1, seed);
881
882                         read(this->fd_random, &seed, sizeof(int));
883
884                         libwebsockets_00_spaceout(key_1, spaces_1, seed);
885                         libwebsockets_00_spaceout(key_2, spaces_2, seed >> 16);
886
887                         p += sprintf(p, "Upgrade: websocket\x0d\x0a"
888                                 "Connection: Upgrade\x0d\x0aHost: %s\x0d\x0a",
889                                         wsi->c_host);
890                         if (wsi->c_origin)
891                                 p += sprintf(p, "Origin: %s\x0d\x0a",
892                                                                  wsi->c_origin);
893
894                         if (wsi->c_protocol)
895                                 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
896                                                                wsi->c_protocol);
897
898                         p += sprintf(p, "Sec-WebSocket-Key1: %s\x0d\x0a",
899                                                                          key_1);
900                         p += sprintf(p, "Sec-WebSocket-Key2: %s\x0d\x0a",
901                                                                          key_2);
902
903                         p += sprintf(p, "\x0d\x0a");
904
905                         read(this->fd_random, p, 8);
906                         memcpy(&challenge[8], p, 8);
907                         p += 8;
908
909                         /* precompute what we want to see from the server */
910
911                         MD5((unsigned char *)challenge, 16,
912                            (unsigned char *)wsi->initial_handshake_hash_base64);
913
914                         goto issue_hdr;
915                 }
916
917                 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
918                 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
919                 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
920                                         "Sec-WebSocket-Key: ");
921                 strcpy(p, wsi->key_b64);
922                 p += strlen(wsi->key_b64);
923                 p += sprintf(p, "\x0d\x0a");
924                 if (wsi->c_origin)
925                         p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
926                                                                  wsi->c_origin);
927                 if (wsi->c_protocol)
928                         p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
929                                                                wsi->c_protocol);
930                 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a\x0d\x0a",
931                                                        wsi->ietf_spec_revision);
932
933                 /* prepare the expected server accept response */
934
935                 strcpy((char *)buf, wsi->key_b64);
936                 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
937
938                 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
939
940                 lws_b64_encode_string(hash, 20,
941                                 wsi->initial_handshake_hash_base64,
942                                      sizeof wsi->initial_handshake_hash_base64);
943 issue_hdr:
944
945                 /* done with these now */
946
947                 free(wsi->c_path);
948                 free(wsi->c_host);
949                 if (wsi->c_origin)
950                         free(wsi->c_origin);
951
952
953                 /* send our request to the server */
954
955         #ifdef LWS_OPENSSL_SUPPORT
956                 if (wsi->use_ssl)
957                         n = SSL_write(wsi->ssl, pkt, p - pkt);
958                 else
959         #endif
960                         n = send(wsi->sock, pkt, p - pkt, 0);
961
962                 if (n < 0) {
963                         fprintf(stderr, "ERROR writing to client socket\n");
964                         libwebsocket_close_and_free_session(this, wsi,
965                                                      LWS_CLOSE_STATUS_NOSTATUS);
966                         return 1;
967                 }
968
969                 wsi->parser_state = WSI_TOKEN_NAME_PART;
970                 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
971                 libwebsocket_set_timeout(wsi,
972                                 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
973
974                 break;
975
976         case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
977
978                 /* handle server hung up on us */
979
980                 if (pollfd->revents & (POLLERR | POLLHUP)) {
981
982                         fprintf(stderr, "Server connection %p (fd=%d) dead\n",
983                                 (void *)wsi, pollfd->fd);
984
985                         goto bail3;
986                 }
987
988
989                 /* interpret the server response */
990
991                 /*
992                  *  HTTP/1.1 101 Switching Protocols
993                  *  Upgrade: websocket
994                  *  Connection: Upgrade
995                  *  Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
996                  *  Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
997                  *  Sec-WebSocket-Protocol: chat
998                  */
999
1000         #ifdef LWS_OPENSSL_SUPPORT
1001                 if (wsi->use_ssl)
1002                         len = SSL_read(wsi->ssl, pkt, sizeof pkt);
1003                 else
1004         #endif
1005                         len = recv(wsi->sock, pkt, sizeof pkt, 0);
1006
1007                 if (len < 0) {
1008                         fprintf(stderr,
1009                                   "libwebsocket_client_handshake read error\n");
1010                         goto bail3;
1011                 }
1012
1013                 p = pkt;
1014                 for (n = 0; n < len; n++)
1015                         libwebsocket_parse(wsi, *p++);
1016
1017                 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
1018                         fprintf(stderr, "libwebsocket_client_handshake "
1019                                         "server response ailed parsing\n");
1020                         goto bail3;
1021                 }
1022
1023                 /*
1024                  * 00 / 76 -->
1025                  *
1026                  * HTTP/1.1 101 WebSocket Protocol Handshake
1027                  * Upgrade: WebSocket
1028                  * Connection: Upgrade
1029                  * Sec-WebSocket-Origin: http://127.0.0.1
1030                  * Sec-WebSocket-Location: ws://127.0.0.1:9999/socket.io/websocket
1031                  *
1032                  * xxxxxxxxxxxxxxxx
1033                  */
1034
1035                 if (wsi->ietf_spec_revision == 0) {
1036                         if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1037                                 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1038                                 !wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
1039                                 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1040                                 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1041                                                              wsi->c_protocol != NULL)) {
1042                                 fprintf(stderr, "libwebsocket_client_handshake "
1043                                                         "missing required header(s)\n");
1044                                 pkt[len] = '\0';
1045                                 fprintf(stderr, "%s", pkt);
1046                                 goto bail3;
1047                         }
1048
1049                         strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1050                         if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1051                                           "101 websocket protocol handshake")) {
1052                                 fprintf(stderr, "libwebsocket_client_handshake "
1053                                                 "server sent bad HTTP response '%s'\n",
1054                                                  wsi->utf8_token[WSI_TOKEN_HTTP].token);
1055                                 goto bail3;
1056                         }
1057                         
1058                         if (wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len < 16) {
1059                                 fprintf(stderr, "libwebsocket_client_handshake "
1060                                                  "challenge reply too short %d\n",
1061                                 wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len);
1062                                 pkt[len] = '\0';
1063                                 fprintf(stderr, "%s", pkt);
1064                                 goto bail3;
1065
1066                         }
1067
1068                         goto select_protocol;
1069                 }
1070
1071                 /*
1072                  * well, what the server sent looked reasonable for syntax.
1073                  * Now let's confirm it sent all the necessary headers
1074                  */
1075
1076                  if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1077                         !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1078                         !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1079                         !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
1080                         (!wsi->utf8_token[WSI_TOKEN_NONCE].token_len &&
1081                                            wsi->ietf_spec_revision == 4) ||
1082                         (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1083                                                      wsi->c_protocol != NULL)) {
1084                         fprintf(stderr, "libwebsocket_client_handshake "
1085                                                 "missing required header(s)\n");
1086                         pkt[len] = '\0';
1087                         fprintf(stderr, "%s", pkt);
1088                         goto bail3;
1089                 }
1090
1091                 /*
1092                  * Everything seems to be there, now take a closer look at what
1093                  * is in each header
1094                  */
1095
1096                 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1097                 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1098                                                    "101 switching protocols")) {
1099                         fprintf(stderr, "libwebsocket_client_handshake "
1100                                         "server sent bad HTTP response '%s'\n",
1101                                          wsi->utf8_token[WSI_TOKEN_HTTP].token);
1102                         goto bail3;
1103                 }
1104
1105                 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1106                 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
1107                                                                  "websocket")) {
1108                         fprintf(stderr, "libwebsocket_client_handshake server "
1109                                         "sent bad Upgrade header '%s'\n",
1110                                       wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1111                         goto bail3;
1112                 }
1113
1114                 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1115                 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
1116                                                                    "upgrade")) {
1117                         fprintf(stderr, "libwebsocket_client_handshake server "
1118                                         "sent bad Connection hdr '%s'\n",
1119                                    wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1120                         goto bail3;
1121                 }
1122
1123 select_protocol:
1124
1125                 pc = wsi->c_protocol;
1126
1127                 /*
1128                  * confirm the protocol the server wants to talk was in the list
1129                  * of protocols we offered
1130                  */
1131
1132                 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
1133
1134                         /*
1135                          * no protocol name to work from,
1136                          * default to first protocol
1137                          */
1138                         wsi->protocol = &this->protocols[0];
1139
1140                         free(wsi->c_protocol);
1141
1142                         goto check_accept;
1143                 }
1144
1145                 while (*pc && !okay) {
1146                         if ((!strncmp(pc,
1147                                 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1148                            wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
1149                  (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
1150                    pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
1151                                 okay = 1;
1152                                 continue;
1153                         }
1154                         while (*pc && *pc != ',')
1155                                 pc++;
1156                         while (*pc && *pc != ' ')
1157                                 pc++;
1158                 }
1159
1160                 /* done with him now */
1161
1162                 if (wsi->c_protocol)
1163                         free(wsi->c_protocol);
1164
1165
1166                 if (!okay) {
1167                         fprintf(stderr, "libwebsocket_client_handshake server "
1168                                                 "sent bad protocol '%s'\n",
1169                                      wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1170                         goto bail2;
1171                 }
1172
1173                 /*
1174                  * identify the selected protocol struct and set it
1175                  */
1176                 n = 0;
1177                 wsi->protocol = NULL;
1178                 while (this->protocols[n].callback) {
1179                         if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1180                                                this->protocols[n].name) == 0)
1181                                 wsi->protocol = &this->protocols[n];
1182                         n++;
1183                 }
1184
1185                 if (wsi->protocol == NULL) {
1186                         fprintf(stderr, "libwebsocket_client_handshake server "
1187                                         "requested protocol '%s', which we "
1188                                         "said we supported but we don't!\n",
1189                                      wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1190                         goto bail2;
1191                 }
1192
1193         check_accept:
1194
1195                 if (wsi->ietf_spec_revision == 0) {
1196
1197                         if (memcmp(wsi->initial_handshake_hash_base64,
1198                                 wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 16)) {
1199                                 fprintf(stderr, "libwebsocket_client_handshake "
1200                                                "failed 00 challenge compare\n");
1201
1202                                 pkt[len] = '\0';
1203                                 fprintf(stderr, "%s", pkt);
1204                                 goto bail2;
1205                         }
1206
1207                         goto accept_ok;
1208                 }
1209         
1210                 /*
1211                  * Confirm his accept token is the one we precomputed
1212                  */
1213
1214                 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1215                                           wsi->initial_handshake_hash_base64)) {
1216                         fprintf(stderr, "libwebsocket_client_handshake server "
1217                                 "sent bad ACCEPT '%s' vs computed '%s'\n",
1218                                 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1219                                             wsi->initial_handshake_hash_base64);
1220                         goto bail2;
1221                 }
1222
1223                 if (wsi->ietf_spec_revision == 4) {
1224                         /*
1225                          * Calculate the 04 masking key to use when
1226                          * sending data to server
1227                          */
1228
1229                         strcpy((char *)buf, wsi->key_b64);
1230                         p = (char *)buf + strlen(wsi->key_b64);
1231                         strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1232                         p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1233                         strcpy(p, magic_websocket_04_masking_guid);
1234                         SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1235                 }
1236
1237 accept_ok:
1238
1239                 /* allocate the per-connection user memory (if any) */
1240
1241                 if (wsi->protocol->per_session_data_size) {
1242                         wsi->user_space = malloc(
1243                                           wsi->protocol->per_session_data_size);
1244                         if (wsi->user_space  == NULL) {
1245                                 fprintf(stderr, "Out of memory for "
1246                                                            "conn user space\n");
1247                                 goto bail2;
1248                         }
1249                 } else
1250                         wsi->user_space = NULL;
1251
1252                 /* clear his proxy connection timeout */
1253
1254                 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1255
1256                 /* mark him as being alive */
1257
1258                 wsi->state = WSI_STATE_ESTABLISHED;
1259                 wsi->mode = LWS_CONNMODE_WS_CLIENT;
1260
1261                 fprintf(stderr, "handshake OK for protocol %s\n",
1262                                                            wsi->protocol->name);
1263
1264                 /* call him back to inform him he is up */
1265
1266                 wsi->protocol->callback(this, wsi,
1267                                  LWS_CALLBACK_CLIENT_ESTABLISHED,
1268                                  wsi->user_space,
1269                                  NULL, 0);
1270
1271                 break;
1272
1273 bail3:
1274                 if (wsi->c_protocol)
1275                         free(wsi->c_protocol);
1276
1277 bail2:
1278                 libwebsocket_close_and_free_session(this, wsi,
1279                                                      LWS_CLOSE_STATUS_NOSTATUS);
1280                 return 1;
1281                 
1282
1283         case LWS_CONNMODE_WS_SERVING:
1284         case LWS_CONNMODE_WS_CLIENT:
1285
1286                 /* handle session socket closed */
1287
1288                 if (pollfd->revents & (POLLERR | POLLHUP)) {
1289
1290                         fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
1291                                 (void *)wsi, pollfd->fd);
1292
1293                         libwebsocket_close_and_free_session(this, wsi,
1294                                                      LWS_CLOSE_STATUS_NOSTATUS);
1295                         return 1;
1296                 }
1297
1298                 /* the guy requested a callback when it was OK to write */
1299
1300                 if (pollfd->revents & POLLOUT) {
1301
1302                         pollfd->events &= ~POLLOUT;
1303
1304                         /* external POLL support via protocol 0 */
1305                         this->protocols[0].callback(this, wsi,
1306                                 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1307                                 (void *)(long)wsi->sock, NULL, POLLOUT);
1308
1309                         wsi->protocol->callback(this, wsi,
1310                                 LWS_CALLBACK_CLIENT_WRITEABLE,
1311                                 wsi->user_space,
1312                                 NULL, 0);
1313                 }
1314
1315                 /* any incoming data ready? */
1316
1317                 if (!(pollfd->revents & POLLIN))
1318                         break;
1319
1320 #ifdef LWS_OPENSSL_SUPPORT
1321                 if (wsi->ssl)
1322                         n = SSL_read(wsi->ssl, buf, sizeof buf);
1323                 else
1324 #endif
1325                         n = recv(pollfd->fd, buf, sizeof buf, 0);
1326
1327                 if (n < 0) {
1328                         fprintf(stderr, "Socket read returned %d\n", n);
1329                         break;
1330                 }
1331                 if (!n) {
1332                         libwebsocket_close_and_free_session(this, wsi,
1333                                                      LWS_CLOSE_STATUS_NOSTATUS);
1334                         return 1;
1335                 }
1336
1337                 /* service incoming data */
1338
1339                 n = libwebsocket_read(this, wsi, buf, n);
1340                 if (n >= 0)
1341                         break;
1342
1343                 /* we closed wsi */
1344
1345                 return 1;
1346         }
1347
1348         return 0;
1349 }
1350
1351
1352 /**
1353  * libwebsocket_context_destroy() - Destroy the websocket context
1354  * @this:       Websocket context
1355  *
1356  *      This function closes any active connections and then frees the
1357  *      context.  After calling this, any further use of the context is
1358  *      undefined.
1359  */
1360 void
1361 libwebsocket_context_destroy(struct libwebsocket_context *this)
1362 {
1363         int n;
1364         int m;
1365         struct libwebsocket *wsi;
1366
1367         for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1368                 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1369                         wsi = this->fd_hashtable[n].wsi[m];
1370                         libwebsocket_close_and_free_session(this, wsi,
1371                                                     LWS_CLOSE_STATUS_GOINGAWAY);
1372                 }
1373
1374         close(this->fd_random);
1375
1376 #ifdef LWS_OPENSSL_SUPPORT
1377         if (this->ssl_ctx)
1378                 SSL_CTX_free(this->ssl_ctx);
1379         if (this->ssl_client_ctx)
1380                 SSL_CTX_free(this->ssl_client_ctx);
1381 #endif
1382
1383         free(this);
1384 }
1385
1386 /**
1387  * libwebsocket_service() - Service any pending websocket activity
1388  * @this:       Websocket context
1389  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1390  *              service otherwise block and service immediately, returning
1391  *              after the timeout if nothing needed service.
1392  *
1393  *      This function deals with any pending websocket traffic, for three
1394  *      kinds of event.  It handles these events on both server and client
1395  *      types of connection the same.
1396  *
1397  *      1) Accept new connections to our context's server
1398  *
1399  *      2) Perform pending broadcast writes initiated from other forked
1400  *         processes (effectively serializing asynchronous broadcasts)
1401  *
1402  *      3) Call the receive callback for incoming frame data received by
1403  *          server or client connections.
1404  *
1405  *      You need to call this service function periodically to all the above
1406  *      functions to happen; if your application is single-threaded you can
1407  *      just call it in your main event loop.
1408  *
1409  *      Alternatively you can fork a new process that asynchronously handles
1410  *      calling this service in a loop.  In that case you are happy if this
1411  *      call blocks your thread until it needs to take care of something and
1412  *      would call it with a large nonzero timeout.  Your loop then takes no
1413  *      CPU while there is nothing happening.
1414  *
1415  *      If you are calling it in a single-threaded app, you don't want it to
1416  *      wait around blocking other things in your loop from happening, so you
1417  *      would call it with a timeout_ms of 0, so it returns immediately if
1418  *      nothing is pending, or as soon as it services whatever was pending.
1419  */
1420
1421
1422 int
1423 libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
1424 {
1425         int n;
1426
1427         /* stay dead once we are dead */
1428
1429         if (this == NULL)
1430                 return 1;
1431
1432         /* wait for something to need service */
1433
1434         n = poll(this->fds, this->fds_count, timeout_ms);
1435         if (n == 0) /* poll timeout */
1436                 return 0;
1437
1438         if (n < 0) {
1439                 /*
1440                 fprintf(stderr, "Listen Socket dead\n");
1441                 */
1442                 return 1;
1443         }
1444
1445         /* handle accept on listening socket? */
1446
1447         for (n = 0; n < this->fds_count; n++)
1448                 if (this->fds[n].revents)
1449                         libwebsocket_service_fd(this, &this->fds[n]);
1450
1451         return 0;
1452 }
1453
1454 /**
1455  * libwebsocket_callback_on_writable() - Request a callback when this socket
1456  *                                       becomes able to be written to without
1457  *                                       blocking
1458  *
1459  * @this:       libwebsockets context
1460  * @wsi:        Websocket connection instance to get callback for
1461  */
1462
1463 int
1464 libwebsocket_callback_on_writable(struct libwebsocket_context *this,
1465                                                        struct libwebsocket *wsi)
1466 {
1467         int n;
1468
1469         for (n = 0; n < this->fds_count; n++)
1470                 if (this->fds[n].fd == wsi->sock) {
1471                         this->fds[n].events |= POLLOUT;
1472                         n = this->fds_count;
1473                 }
1474
1475         /* external POLL support via protocol 0 */
1476         this->protocols[0].callback(this, wsi,
1477                 LWS_CALLBACK_SET_MODE_POLL_FD,
1478                 (void *)(long)wsi->sock, NULL, POLLOUT);
1479
1480         return 1;
1481 }
1482
1483 /**
1484  * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1485  *                      all connections using the given protocol when it
1486  *                      becomes possible to write to each socket without
1487  *                      blocking in turn.
1488  *
1489  * @protocol:   Protocol whose connections will get callbacks
1490  */
1491
1492 int
1493 libwebsocket_callback_on_writable_all_protocol(
1494                                   const struct libwebsocket_protocols *protocol)
1495 {
1496         struct libwebsocket_context *this = protocol->owning_server;
1497         int n;
1498         int m;
1499         struct libwebsocket *wsi;
1500
1501         for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1502
1503                 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1504
1505                         wsi = this->fd_hashtable[n].wsi[m];
1506
1507                         if (wsi->protocol == protocol)
1508                                 libwebsocket_callback_on_writable(this, wsi);
1509                 }
1510         }
1511
1512         return 0;
1513 }
1514
1515 /**
1516  * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1517  *
1518  * You will not need this unless you are doing something special
1519  *
1520  * @wsi:        Websocket connection instance
1521  * @reason:     timeout reason
1522  * @secs:       how many seconds
1523  */
1524
1525 void
1526 libwebsocket_set_timeout(struct libwebsocket *wsi,
1527                                           enum pending_timeout reason, int secs)
1528 {
1529         struct timeval tv;
1530
1531         gettimeofday(&tv, NULL);
1532
1533         wsi->pending_timeout_limit = tv.tv_sec + secs;
1534         wsi->pending_timeout = reason;
1535 }
1536
1537
1538 /**
1539  * libwebsocket_get_socket_fd() - returns the socket file descriptor
1540  *
1541  * You will not need this unless you are doing something special
1542  *
1543  * @wsi:        Websocket connection instance
1544  */
1545
1546 int
1547 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1548 {
1549         return wsi->sock;
1550 }
1551
1552 /**
1553  * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1554  *                              receieved packets.
1555  *
1556  * If the output side of a server process becomes choked, this allows flow
1557  * control for the input side.
1558  *
1559  * @wsi:        Websocket connection instance to get callback for
1560  * @enable:     0 = disable read servicing for this connection, 1 = enable
1561  */
1562
1563 int
1564 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1565 {
1566         struct libwebsocket_context *this = wsi->protocol->owning_server;
1567         int n;
1568
1569         for (n = 0; n < this->fds_count; n++)
1570                 if (this->fds[n].fd == wsi->sock) {
1571                         if (enable)
1572                                 this->fds[n].events |= POLLIN;
1573                         else
1574                                 this->fds[n].events &= ~POLLIN;
1575
1576                         return 0;
1577                 }
1578
1579         if (enable)
1580                 /* external POLL support via protocol 0 */
1581                 this->protocols[0].callback(this, wsi,
1582                         LWS_CALLBACK_SET_MODE_POLL_FD,
1583                         (void *)(long)wsi->sock, NULL, POLLIN);
1584         else
1585                 /* external POLL support via protocol 0 */
1586                 this->protocols[0].callback(this, wsi,
1587                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1588                         (void *)(long)wsi->sock, NULL, POLLIN);
1589
1590
1591         fprintf(stderr, "libwebsocket_callback_on_writable "
1592                                                      "unable to find socket\n");
1593         return 1;
1594 }
1595
1596 /**
1597  * libwebsocket_canonical_hostname() - returns this host's hostname
1598  *
1599  * This is typically used by client code to fill in the host parameter
1600  * when making a client connection.  You can only call it after the context
1601  * has been created.
1602  *
1603  * @this:       Websocket context
1604  */
1605
1606
1607 extern const char *
1608 libwebsocket_canonical_hostname(struct libwebsocket_context *this)
1609 {
1610         return (const char *)this->canonical_hostname;
1611 }
1612
1613
1614 static void sigpipe_handler(int x)
1615 {
1616 }
1617
1618 #ifdef LWS_OPENSSL_SUPPORT
1619 static int
1620 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1621 {
1622
1623         SSL *ssl;
1624         int n;
1625 //      struct libwebsocket_context *this;
1626
1627         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1628                 SSL_get_ex_data_X509_STORE_CTX_idx());
1629
1630         /*
1631          * !!! can't get this->openssl_websocket_private_data_index
1632          * can't store as a static either
1633          */
1634 //      this = SSL_get_ex_data(ssl, this->openssl_websocket_private_data_index);
1635         
1636         n = this->protocols[0].callback(NULL, NULL,
1637                 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1638                                                    x509_ctx, ssl, preverify_ok);
1639
1640         /* convert return code from 0 = OK to 1 = OK */
1641
1642         if (!n)
1643                 n = 1;
1644         else
1645                 n = 0;
1646
1647         return n;
1648 }
1649 #endif
1650
1651
1652 /**
1653  * libwebsocket_create_context() - Create the websocket handler
1654  * @port:       Port to listen on... you can use 0 to suppress listening on
1655  *              any port, that's what you want if you are not running a
1656  *              websocket server at all but just using it as a client
1657  * @interface:  NULL to bind the listen socket to all interfaces, or the
1658  *              interface name, eg, "eth2"
1659  * @protocols:  Array of structures listing supported protocols and a protocol-
1660  *              specific callback for each one.  The list is ended with an
1661  *              entry that has a NULL callback pointer.
1662  *              It's not const because we write the owning_server member
1663  * @ssl_cert_filepath:  If libwebsockets was compiled to use ssl, and you want
1664  *                      to listen using SSL, set to the filepath to fetch the
1665  *                      server cert from, otherwise NULL for unencrypted
1666  * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
1667  *                      else ignored
1668  * @gid:        group id to change to after setting listen socket, or -1.
1669  * @uid:        user id to change to after setting listen socket, or -1.
1670  * @options:    0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
1671  *
1672  *      This function creates the listening socket and takes care
1673  *      of all initialization in one step.
1674  *
1675  *      After initialization, it returns a struct libwebsocket_context * that
1676  *      represents this server.  After calling, user code needs to take care
1677  *      of calling libwebsocket_service() with the context pointer to get the
1678  *      server's sockets serviced.  This can be done in the same process context
1679  *      or a forked process, or another thread,
1680  *
1681  *      The protocol callback functions are called for a handful of events
1682  *      including http requests coming in, websocket connections becoming
1683  *      established, and data arriving; it's also called periodically to allow
1684  *      async transmission.
1685  *
1686  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
1687  *      at that time websocket protocol has not been negotiated.  Other
1688  *      protocols after the first one never see any HTTP callack activity.
1689  *
1690  *      The server created is a simple http server by default; part of the
1691  *      websocket standard is upgrading this http connection to a websocket one.
1692  *
1693  *      This allows the same server to provide files like scripts and favicon /
1694  *      images or whatever over http and dynamic data over websockets all in
1695  *      one place; they're all handled in the user callback.
1696  */
1697
1698 struct libwebsocket_context *
1699 libwebsocket_create_context(int port, const char *interface,
1700                                struct libwebsocket_protocols *protocols,
1701                                const char *ssl_cert_filepath,
1702                                const char *ssl_private_key_filepath,
1703                                int gid, int uid, unsigned int options)
1704 {
1705         int n;
1706         int sockfd = 0;
1707         int fd;
1708         struct sockaddr_in serv_addr, cli_addr;
1709         int opt = 1;
1710         struct libwebsocket_context *this = NULL;
1711         unsigned int slen;
1712         char *p;
1713         char hostname[1024];
1714         struct hostent *he;
1715         struct libwebsocket *wsi;
1716
1717 #ifdef LWS_OPENSSL_SUPPORT
1718         SSL_METHOD *method;
1719         char ssl_err_buf[512];
1720 #endif
1721
1722         this = malloc(sizeof(struct libwebsocket_context));
1723         if (!this) {
1724                 fprintf(stderr, "No memory for websocket context\n");
1725                 return NULL;
1726         }
1727         this->protocols = protocols;
1728         this->listen_port = port;
1729         this->http_proxy_port = 0;
1730         this->http_proxy_address[0] = '\0';
1731         this->options = options;
1732         this->fds_count = 0;
1733
1734         this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1735         if (this->fd_random < 0) {
1736                 fprintf(stderr, "Unable to open random device %s %d\n",
1737                                        SYSTEM_RANDOM_FILEPATH, this->fd_random);
1738                 return NULL;
1739         }
1740
1741         /* find canonical hostname */
1742
1743         hostname[(sizeof hostname) - 1] = '\0';
1744         gethostname(hostname, (sizeof hostname) - 1);
1745         he = gethostbyname(hostname);
1746         if (he) {
1747                 strncpy(this->canonical_hostname, he->h_name,
1748                                            sizeof this->canonical_hostname - 1);
1749                 this->canonical_hostname[sizeof this->canonical_hostname - 1] =
1750                                                                            '\0';
1751         } else
1752                 strncpy(this->canonical_hostname, hostname,
1753                                            sizeof this->canonical_hostname - 1);
1754
1755         /* split the proxy ads:port if given */
1756
1757         p = getenv("http_proxy");
1758         if (p) {
1759                 strncpy(this->http_proxy_address, p,
1760                                            sizeof this->http_proxy_address - 1);
1761                 this->http_proxy_address[
1762                                     sizeof this->http_proxy_address - 1] = '\0';
1763
1764                 p = strchr(this->http_proxy_address, ':');
1765                 if (p == NULL) {
1766                         fprintf(stderr, "http_proxy needs to be ads:port\n");
1767                         return NULL;
1768                 }
1769                 *p = '\0';
1770                 this->http_proxy_port = atoi(p + 1);
1771
1772                 fprintf(stderr, "Using proxy %s:%u\n",
1773                                 this->http_proxy_address,
1774                                                         this->http_proxy_port);
1775         }
1776
1777         if (port) {
1778
1779 #ifdef LWS_OPENSSL_SUPPORT
1780                 this->use_ssl = ssl_cert_filepath != NULL &&
1781                                                ssl_private_key_filepath != NULL;
1782                 if (this->use_ssl)
1783                         fprintf(stderr, " Compiled with SSL support, "
1784                                                                   "using it\n");
1785                 else
1786                         fprintf(stderr, " Compiled with SSL support, "
1787                                                               "not using it\n");
1788
1789 #else
1790                 if (ssl_cert_filepath != NULL &&
1791                                              ssl_private_key_filepath != NULL) {
1792                         fprintf(stderr, " Not compiled for OpenSSl support!\n");
1793                         return NULL;
1794                 }
1795                 fprintf(stderr, " Compiled without SSL support, "
1796                                                        "serving unencrypted\n");
1797 #endif
1798         }
1799
1800         /* ignore SIGPIPE */
1801
1802         signal(SIGPIPE, sigpipe_handler);
1803
1804
1805 #ifdef LWS_OPENSSL_SUPPORT
1806
1807         /* basic openssl init */
1808
1809         SSL_library_init();
1810
1811         OpenSSL_add_all_algorithms();
1812         SSL_load_error_strings();
1813
1814         this->openssl_websocket_private_data_index =
1815                 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1816
1817         /*
1818          * Firefox insists on SSLv23 not SSLv3
1819          * Konq disables SSLv2 by default now, SSLv23 works
1820          */
1821
1822         method = (SSL_METHOD *)SSLv23_server_method();
1823         if (!method) {
1824                 fprintf(stderr, "problem creating ssl method: %s\n",
1825                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1826                 return NULL;
1827         }
1828         this->ssl_ctx = SSL_CTX_new(method);    /* create context */
1829         if (!this->ssl_ctx) {
1830                 fprintf(stderr, "problem creating ssl context: %s\n",
1831                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1832                 return NULL;
1833         }
1834
1835         /* client context */
1836
1837         method = (SSL_METHOD *)SSLv23_client_method();
1838         if (!method) {
1839                 fprintf(stderr, "problem creating ssl method: %s\n",
1840                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1841                 return NULL;
1842         }
1843         this->ssl_client_ctx = SSL_CTX_new(method);     /* create context */
1844         if (!this->ssl_client_ctx) {
1845                 fprintf(stderr, "problem creating ssl context: %s\n",
1846                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1847                 return NULL;
1848         }
1849
1850
1851         /* openssl init for cert verification (used with client sockets) */
1852
1853         if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
1854                                                     LWS_OPENSSL_CLIENT_CERTS)) {
1855                 fprintf(stderr, "Unable to load SSL Client certs from %s "
1856                         "(set by --with-client-cert-dir= in configure) -- "
1857                         " client ssl isn't going to work",
1858                                                       LWS_OPENSSL_CLIENT_CERTS);
1859         }
1860
1861         /*
1862          * callback allowing user code to load extra verification certs
1863          * helping the client to verify server identity
1864          */
1865
1866         this->protocols[0].callback(this, NULL,
1867                 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1868                 this->ssl_client_ctx, NULL, 0);
1869
1870         /* as a server, are we requiring clients to identify themselves? */
1871
1872         if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1873
1874                 /* absolutely require the client cert */
1875                 
1876                 SSL_CTX_set_verify(this->ssl_ctx,
1877                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1878                                                        OpenSSL_verify_callback);
1879
1880                 /*
1881                  * give user code a chance to load certs into the server
1882                  * allowing it to verify incoming client certs
1883                  */
1884
1885                 this->protocols[0].callback(this, NULL,
1886                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
1887                                                         this->ssl_ctx, NULL, 0);
1888         }
1889
1890         if (this->use_ssl) {
1891
1892                 /* openssl init for server sockets */
1893
1894                 /* set the local certificate from CertFile */
1895                 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
1896                                         ssl_cert_filepath, SSL_FILETYPE_PEM);
1897                 if (n != 1) {
1898                         fprintf(stderr, "problem getting cert '%s': %s\n",
1899                                 ssl_cert_filepath,
1900                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
1901                         return NULL;
1902                 }
1903                 /* set the private key from KeyFile */
1904                 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
1905                                                 ssl_private_key_filepath,
1906                                                        SSL_FILETYPE_PEM) != 1) {
1907                         fprintf(stderr, "ssl problem getting key '%s': %s\n",
1908                                                 ssl_private_key_filepath,
1909                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
1910                         return NULL;
1911                 }
1912                 /* verify private key */
1913                 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
1914                         fprintf(stderr, "Private SSL key doesn't match cert\n");
1915                         return NULL;
1916                 }
1917
1918                 /* SSL is happy and has a cert it's content with */
1919         }
1920 #endif
1921
1922         /* selftest */
1923
1924         if (lws_b64_selftest())
1925                 return NULL;
1926
1927         /* fd hashtable init */
1928
1929         for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1930                 this->fd_hashtable[n].length = 0;
1931
1932         /* set up our external listening socket we serve on */
1933
1934         if (port) {
1935
1936                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1937                 if (sockfd < 0) {
1938                         fprintf(stderr, "ERROR opening socket");
1939                         return NULL;
1940                 }
1941
1942                 /* allow us to restart even if old sockets in TIME_WAIT */
1943                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1944
1945                 bzero((char *) &serv_addr, sizeof(serv_addr));
1946                 serv_addr.sin_family = AF_INET;
1947                 if (interface == NULL)
1948                         serv_addr.sin_addr.s_addr = INADDR_ANY;
1949                 else
1950                         interface_to_sa(interface, &serv_addr,
1951                                                 sizeof(serv_addr));
1952                 serv_addr.sin_port = htons(port);
1953
1954                 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1955                                                              sizeof(serv_addr));
1956                 if (n < 0) {
1957                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1958                                                                 port, n, errno);
1959                         return NULL;
1960                 }
1961
1962                 wsi = malloc(sizeof(struct libwebsocket));
1963                 memset(wsi, 0, sizeof (struct libwebsocket));
1964                 wsi->sock = sockfd;
1965                 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1966                 insert_wsi(this, wsi);
1967
1968                 listen(sockfd, 5);
1969                 fprintf(stderr, " Listening on port %d\n", port);
1970
1971                 /* list in the internal poll array */
1972                 
1973                 this->fds[this->fds_count].fd = sockfd;
1974                 this->fds[this->fds_count++].events = POLLIN;
1975
1976                 /* external POLL support via protocol 0 */
1977                 this->protocols[0].callback(this, wsi,
1978                         LWS_CALLBACK_ADD_POLL_FD,
1979                         (void *)(long)sockfd, NULL, POLLIN);
1980
1981         }
1982
1983         /* drop any root privs for this process */
1984
1985         if (gid != -1)
1986                 if (setgid(gid))
1987                         fprintf(stderr, "setgid: %s\n", strerror(errno));
1988         if (uid != -1)
1989                 if (setuid(uid))
1990                         fprintf(stderr, "setuid: %s\n", strerror(errno));
1991
1992
1993         /* set up our internal broadcast trigger sockets per-protocol */
1994
1995         for (this->count_protocols = 0;
1996                         protocols[this->count_protocols].callback;
1997                                                       this->count_protocols++) {
1998                 protocols[this->count_protocols].owning_server = this;
1999                 protocols[this->count_protocols].protocol_index =
2000                                                           this->count_protocols;
2001
2002                 fd = socket(AF_INET, SOCK_STREAM, 0);
2003                 if (fd < 0) {
2004                         fprintf(stderr, "ERROR opening socket");
2005                         return NULL;
2006                 }
2007
2008                 /* allow us to restart even if old sockets in TIME_WAIT */
2009                 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
2010
2011                 bzero((char *) &serv_addr, sizeof(serv_addr));
2012                 serv_addr.sin_family = AF_INET;
2013                 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2014                 serv_addr.sin_port = 0; /* pick the port for us */
2015
2016                 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2017                 if (n < 0) {
2018                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2019                                                                 port, n, errno);
2020                         return NULL;
2021                 }
2022
2023                 slen = sizeof cli_addr;
2024                 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2025                 if (n < 0) {
2026                         fprintf(stderr, "getsockname failed\n");
2027                         return NULL;
2028                 }
2029                 protocols[this->count_protocols].broadcast_socket_port =
2030                                                        ntohs(cli_addr.sin_port);
2031                 listen(fd, 5);
2032
2033                 debug("  Protocol %s broadcast socket %d\n",
2034                                 protocols[this->count_protocols].name,
2035                                                       ntohs(cli_addr.sin_port));
2036
2037                 /* dummy wsi per broadcast proxy socket */
2038
2039                 wsi = malloc(sizeof(struct libwebsocket));
2040                 memset(wsi, 0, sizeof (struct libwebsocket));
2041                 wsi->sock = fd;
2042                 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
2043                 /* note which protocol we are proxying */
2044                 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
2045                 insert_wsi(this, wsi);
2046
2047                 /* list in internal poll array */
2048
2049                 this->fds[this->fds_count].fd = fd;
2050                 this->fds[this->fds_count].events = POLLIN;
2051                 this->fds[this->fds_count].revents = 0;
2052                 this->fds_count++;
2053
2054                 /* external POLL support via protocol 0 */
2055                 this->protocols[0].callback(this, wsi,
2056                         LWS_CALLBACK_ADD_POLL_FD,
2057                         (void *)(long)fd, NULL, POLLIN);
2058         }
2059
2060         return this;
2061 }
2062
2063
2064 #ifndef LWS_NO_FORK
2065
2066 /**
2067  * libwebsockets_fork_service_loop() - Optional helper function forks off
2068  *                                a process for the websocket server loop.
2069  *                              You don't have to use this but if not, you
2070  *                              have to make sure you are calling
2071  *                              libwebsocket_service periodically to service
2072  *                              the websocket traffic
2073  * @this:       server context returned by creation function
2074  */
2075
2076 int
2077 libwebsockets_fork_service_loop(struct libwebsocket_context *this)
2078 {
2079         int fd;
2080         struct sockaddr_in cli_addr;
2081         int n;
2082         int p;
2083
2084         n = fork();
2085         if (n < 0)
2086                 return n;
2087
2088         if (!n) {
2089
2090                 /* main process context */
2091
2092                 /*
2093                  * set up the proxy sockets to allow broadcast from
2094                  * service process context
2095                  */
2096
2097                 for (p = 0; p < this->count_protocols; p++) {
2098                         fd = socket(AF_INET, SOCK_STREAM, 0);
2099                         if (fd < 0) {
2100                                 fprintf(stderr, "Unable to create socket\n");
2101                                 return -1;
2102                         }
2103                         cli_addr.sin_family = AF_INET;
2104                         cli_addr.sin_port = htons(
2105                              this->protocols[p].broadcast_socket_port);
2106                         cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2107                         n = connect(fd, (struct sockaddr *)&cli_addr,
2108                                                                sizeof cli_addr);
2109                         if (n < 0) {
2110                                 fprintf(stderr, "Unable to connect to "
2111                                                 "broadcast socket %d, %s\n",
2112                                                 n, strerror(errno));
2113                                 return -1;
2114                         }
2115
2116                         this->protocols[p].broadcast_socket_user_fd = fd;
2117                 }
2118
2119                 return 0;
2120         }
2121
2122         /* we want a SIGHUP when our parent goes down */
2123         prctl(PR_SET_PDEATHSIG, SIGHUP);
2124
2125         /* in this forked process, sit and service websocket connections */
2126
2127         while (1)
2128                 if (libwebsocket_service(this, 1000))
2129                         return -1;
2130
2131         return 0;
2132 }
2133
2134 #endif
2135
2136 /**
2137  * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2138  *                                connection.
2139  * @wsi:        pointer to struct websocket you want to know the protocol of
2140  *
2141  *
2142  *      This is useful to get the protocol to broadcast back to from inside
2143  * the callback.
2144  */
2145
2146 const struct libwebsocket_protocols *
2147 libwebsockets_get_protocol(struct libwebsocket *wsi)
2148 {
2149         return wsi->protocol;
2150 }
2151
2152 /**
2153  * libwebsockets_broadcast() - Sends a buffer to the callback for all active
2154  *                                connections of the given protocol.
2155  * @protocol:   pointer to the protocol you will broadcast to all members of
2156  * @buf:  buffer containing the data to be broadcase.  NOTE: this has to be
2157  *              allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
2158  *              the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
2159  *              case you are calling this function from callback context.
2160  * @len:        length of payload data in buf, starting from buf.
2161  *
2162  *      This function allows bulk sending of a packet to every connection using
2163  * the given protocol.  It does not send the data directly; instead it calls
2164  * the callback with a reason type of LWS_CALLBACK_BROADCAST.  If the callback
2165  * wants to actually send the data for that connection, the callback itself
2166  * should call libwebsocket_write().
2167  *
2168  * libwebsockets_broadcast() can be called from another fork context without
2169  * having to take any care about data visibility between the processes, it'll
2170  * "just work".
2171  */
2172
2173
2174 int
2175 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
2176                                                  unsigned char *buf, size_t len)
2177 {
2178         struct libwebsocket_context *this = protocol->owning_server;
2179         int n;
2180         int m;
2181         struct libwebsocket * wsi;
2182
2183         if (!protocol->broadcast_socket_user_fd) {
2184                 /*
2185                  * We are either running unforked / flat, or we are being
2186                  * called from poll thread context
2187                  * eg, from a callback.  In that case don't use sockets for
2188                  * broadcast IPC (since we can't open a socket connection to
2189                  * a socket listening on our own thread) but directly do the
2190                  * send action.
2191                  *
2192                  * Locking is not needed because we are by definition being
2193                  * called in the poll thread context and are serialized.
2194                  */
2195
2196                 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
2197
2198                         for (m = 0; m < this->fd_hashtable[n].length; m++) {
2199
2200                                 wsi = this->fd_hashtable[n].wsi[m];
2201
2202                                 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
2203                                         continue;
2204
2205                                 /*
2206                                  * never broadcast to
2207                                  * non-established connections
2208                                  */
2209                                 if (wsi->state != WSI_STATE_ESTABLISHED)
2210                                         continue;
2211
2212                                 /* only broadcast to guys using
2213                                  * requested protocol
2214                                  */
2215                                 if (wsi->protocol != protocol)
2216                                         continue;
2217
2218                                 wsi->protocol->callback(this, wsi,
2219                                          LWS_CALLBACK_BROADCAST,
2220                                          wsi->user_space,
2221                                          buf, len);
2222                         }
2223                 }
2224
2225                 return 0;
2226         }
2227
2228         /*
2229          * We're being called from a different process context than the server
2230          * loop.  Instead of broadcasting directly, we send our
2231          * payload on a socket to do the IPC; the server process will serialize
2232          * the broadcast action in its main poll() loop.
2233          *
2234          * There's one broadcast socket listening for each protocol supported
2235          * set up when the websocket server initializes
2236          */
2237
2238         n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
2239
2240         return n;
2241 }