introduce LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER
[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                         /* give userland a chance to append, eg, cookies */
904
905                         this->protocols[0].callback(this, wsi,
906                                  LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
907                                         NULL, &p, (pkt + sizeof(pkt)) - p - 12);
908
909                         p += sprintf(p, "\x0d\x0a");
910
911                         read(this->fd_random, p, 8);
912                         memcpy(&challenge[8], p, 8);
913                         p += 8;
914
915                         /* precompute what we want to see from the server */
916
917                         MD5((unsigned char *)challenge, 16,
918                            (unsigned char *)wsi->initial_handshake_hash_base64);
919
920                         goto issue_hdr;
921                 }
922
923                 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
924                 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
925                 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
926                                         "Sec-WebSocket-Key: ");
927                 strcpy(p, wsi->key_b64);
928                 p += strlen(wsi->key_b64);
929                 p += sprintf(p, "\x0d\x0a");
930                 if (wsi->c_origin)
931                         p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
932                                                                  wsi->c_origin);
933                 if (wsi->c_protocol)
934                         p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
935                                                                wsi->c_protocol);
936                 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
937                                                        wsi->ietf_spec_revision);
938
939                 /* give userland a chance to append, eg, cookies */
940
941                 this->protocols[0].callback(this, wsi,
942                          LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
943                                         NULL, &p, (pkt + sizeof(pkt)) - p - 12);
944
945                 p += sprintf(p, "\x0d\x0a");
946
947                 /* prepare the expected server accept response */
948
949                 strcpy((char *)buf, wsi->key_b64);
950                 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
951
952                 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
953
954                 lws_b64_encode_string(hash, 20,
955                                 wsi->initial_handshake_hash_base64,
956                                      sizeof wsi->initial_handshake_hash_base64);
957 issue_hdr:
958
959                 /* done with these now */
960
961                 free(wsi->c_path);
962                 free(wsi->c_host);
963                 if (wsi->c_origin)
964                         free(wsi->c_origin);
965
966
967                 /* send our request to the server */
968
969         #ifdef LWS_OPENSSL_SUPPORT
970                 if (wsi->use_ssl)
971                         n = SSL_write(wsi->ssl, pkt, p - pkt);
972                 else
973         #endif
974                         n = send(wsi->sock, pkt, p - pkt, 0);
975
976                 if (n < 0) {
977                         fprintf(stderr, "ERROR writing to client socket\n");
978                         libwebsocket_close_and_free_session(this, wsi,
979                                                      LWS_CLOSE_STATUS_NOSTATUS);
980                         return 1;
981                 }
982
983                 wsi->parser_state = WSI_TOKEN_NAME_PART;
984                 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
985                 libwebsocket_set_timeout(wsi,
986                                 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
987
988                 break;
989
990         case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
991
992                 /* handle server hung up on us */
993
994                 if (pollfd->revents & (POLLERR | POLLHUP)) {
995
996                         fprintf(stderr, "Server connection %p (fd=%d) dead\n",
997                                 (void *)wsi, pollfd->fd);
998
999                         goto bail3;
1000                 }
1001
1002
1003                 /* interpret the server response */
1004
1005                 /*
1006                  *  HTTP/1.1 101 Switching Protocols
1007                  *  Upgrade: websocket
1008                  *  Connection: Upgrade
1009                  *  Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
1010                  *  Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
1011                  *  Sec-WebSocket-Protocol: chat
1012                  */
1013
1014         #ifdef LWS_OPENSSL_SUPPORT
1015                 if (wsi->use_ssl)
1016                         len = SSL_read(wsi->ssl, pkt, sizeof pkt);
1017                 else
1018         #endif
1019                         len = recv(wsi->sock, pkt, sizeof pkt, 0);
1020
1021                 if (len < 0) {
1022                         fprintf(stderr,
1023                                   "libwebsocket_client_handshake read error\n");
1024                         goto bail3;
1025                 }
1026
1027                 p = pkt;
1028                 for (n = 0; n < len; n++)
1029                         libwebsocket_parse(wsi, *p++);
1030
1031                 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
1032                         fprintf(stderr, "libwebsocket_client_handshake "
1033                                         "server response ailed parsing\n");
1034                         goto bail3;
1035                 }
1036
1037                 /*
1038                  * 00 / 76 -->
1039                  *
1040                  * HTTP/1.1 101 WebSocket Protocol Handshake
1041                  * Upgrade: WebSocket
1042                  * Connection: Upgrade
1043                  * Sec-WebSocket-Origin: http://127.0.0.1
1044                  * Sec-WebSocket-Location: ws://127.0.0.1:9999/socket.io/websocket
1045                  *
1046                  * xxxxxxxxxxxxxxxx
1047                  */
1048
1049                 if (wsi->ietf_spec_revision == 0) {
1050                         if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1051                                 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1052                                 !wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
1053                                 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1054                                 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1055                                                              wsi->c_protocol != NULL)) {
1056                                 fprintf(stderr, "libwebsocket_client_handshake "
1057                                                         "missing required header(s)\n");
1058                                 pkt[len] = '\0';
1059                                 fprintf(stderr, "%s", pkt);
1060                                 goto bail3;
1061                         }
1062
1063                         strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1064                         if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1065                                           "101 websocket protocol handshake")) {
1066                                 fprintf(stderr, "libwebsocket_client_handshake "
1067                                                 "server sent bad HTTP response '%s'\n",
1068                                                  wsi->utf8_token[WSI_TOKEN_HTTP].token);
1069                                 goto bail3;
1070                         }
1071                         
1072                         if (wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len < 16) {
1073                                 fprintf(stderr, "libwebsocket_client_handshake "
1074                                                  "challenge reply too short %d\n",
1075                                 wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len);
1076                                 pkt[len] = '\0';
1077                                 fprintf(stderr, "%s", pkt);
1078                                 goto bail3;
1079
1080                         }
1081
1082                         goto select_protocol;
1083                 }
1084
1085                 /*
1086                  * well, what the server sent looked reasonable for syntax.
1087                  * Now let's confirm it sent all the necessary headers
1088                  */
1089
1090                  if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1091                         !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1092                         !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1093                         !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
1094                         (!wsi->utf8_token[WSI_TOKEN_NONCE].token_len &&
1095                                            wsi->ietf_spec_revision == 4) ||
1096                         (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1097                                                      wsi->c_protocol != NULL)) {
1098                         fprintf(stderr, "libwebsocket_client_handshake "
1099                                                 "missing required header(s)\n");
1100                         pkt[len] = '\0';
1101                         fprintf(stderr, "%s", pkt);
1102                         goto bail3;
1103                 }
1104
1105                 /*
1106                  * Everything seems to be there, now take a closer look at what
1107                  * is in each header
1108                  */
1109
1110                 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1111                 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1112                                                    "101 switching protocols")) {
1113                         fprintf(stderr, "libwebsocket_client_handshake "
1114                                         "server sent bad HTTP response '%s'\n",
1115                                          wsi->utf8_token[WSI_TOKEN_HTTP].token);
1116                         goto bail3;
1117                 }
1118
1119                 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1120                 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
1121                                                                  "websocket")) {
1122                         fprintf(stderr, "libwebsocket_client_handshake server "
1123                                         "sent bad Upgrade header '%s'\n",
1124                                       wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1125                         goto bail3;
1126                 }
1127
1128                 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1129                 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
1130                                                                    "upgrade")) {
1131                         fprintf(stderr, "libwebsocket_client_handshake server "
1132                                         "sent bad Connection hdr '%s'\n",
1133                                    wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1134                         goto bail3;
1135                 }
1136
1137 select_protocol:
1138
1139                 pc = wsi->c_protocol;
1140
1141                 /*
1142                  * confirm the protocol the server wants to talk was in the list
1143                  * of protocols we offered
1144                  */
1145
1146                 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
1147
1148                         /*
1149                          * no protocol name to work from,
1150                          * default to first protocol
1151                          */
1152                         wsi->protocol = &this->protocols[0];
1153
1154                         free(wsi->c_protocol);
1155
1156                         goto check_accept;
1157                 }
1158
1159                 while (*pc && !okay) {
1160                         if ((!strncmp(pc,
1161                                 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1162                            wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
1163                  (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
1164                    pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
1165                                 okay = 1;
1166                                 continue;
1167                         }
1168                         while (*pc && *pc != ',')
1169                                 pc++;
1170                         while (*pc && *pc != ' ')
1171                                 pc++;
1172                 }
1173
1174                 /* done with him now */
1175
1176                 if (wsi->c_protocol)
1177                         free(wsi->c_protocol);
1178
1179
1180                 if (!okay) {
1181                         fprintf(stderr, "libwebsocket_client_handshake server "
1182                                                 "sent bad protocol '%s'\n",
1183                                      wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1184                         goto bail2;
1185                 }
1186
1187                 /*
1188                  * identify the selected protocol struct and set it
1189                  */
1190                 n = 0;
1191                 wsi->protocol = NULL;
1192                 while (this->protocols[n].callback) {
1193                         if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1194                                                this->protocols[n].name) == 0)
1195                                 wsi->protocol = &this->protocols[n];
1196                         n++;
1197                 }
1198
1199                 if (wsi->protocol == NULL) {
1200                         fprintf(stderr, "libwebsocket_client_handshake server "
1201                                         "requested protocol '%s', which we "
1202                                         "said we supported but we don't!\n",
1203                                      wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1204                         goto bail2;
1205                 }
1206
1207         check_accept:
1208
1209                 if (wsi->ietf_spec_revision == 0) {
1210
1211                         if (memcmp(wsi->initial_handshake_hash_base64,
1212                                 wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 16)) {
1213                                 fprintf(stderr, "libwebsocket_client_handshake "
1214                                                "failed 00 challenge compare\n");
1215
1216                                 pkt[len] = '\0';
1217                                 fprintf(stderr, "%s", pkt);
1218                                 goto bail2;
1219                         }
1220
1221                         goto accept_ok;
1222                 }
1223         
1224                 /*
1225                  * Confirm his accept token is the one we precomputed
1226                  */
1227
1228                 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1229                                           wsi->initial_handshake_hash_base64)) {
1230                         fprintf(stderr, "libwebsocket_client_handshake server "
1231                                 "sent bad ACCEPT '%s' vs computed '%s'\n",
1232                                 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1233                                             wsi->initial_handshake_hash_base64);
1234                         goto bail2;
1235                 }
1236
1237                 if (wsi->ietf_spec_revision == 4) {
1238                         /*
1239                          * Calculate the 04 masking key to use when
1240                          * sending data to server
1241                          */
1242
1243                         strcpy((char *)buf, wsi->key_b64);
1244                         p = (char *)buf + strlen(wsi->key_b64);
1245                         strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1246                         p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1247                         strcpy(p, magic_websocket_04_masking_guid);
1248                         SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1249                 }
1250
1251 accept_ok:
1252
1253                 /* allocate the per-connection user memory (if any) */
1254
1255                 if (wsi->protocol->per_session_data_size) {
1256                         wsi->user_space = malloc(
1257                                           wsi->protocol->per_session_data_size);
1258                         if (wsi->user_space  == NULL) {
1259                                 fprintf(stderr, "Out of memory for "
1260                                                            "conn user space\n");
1261                                 goto bail2;
1262                         }
1263                 } else
1264                         wsi->user_space = NULL;
1265
1266                 /* clear his proxy connection timeout */
1267
1268                 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1269
1270                 /* mark him as being alive */
1271
1272                 wsi->state = WSI_STATE_ESTABLISHED;
1273                 wsi->mode = LWS_CONNMODE_WS_CLIENT;
1274
1275                 fprintf(stderr, "handshake OK for protocol %s\n",
1276                                                            wsi->protocol->name);
1277
1278                 /* call him back to inform him he is up */
1279
1280                 wsi->protocol->callback(this, wsi,
1281                                  LWS_CALLBACK_CLIENT_ESTABLISHED,
1282                                  wsi->user_space,
1283                                  NULL, 0);
1284
1285                 break;
1286
1287 bail3:
1288                 if (wsi->c_protocol)
1289                         free(wsi->c_protocol);
1290
1291 bail2:
1292                 libwebsocket_close_and_free_session(this, wsi,
1293                                                      LWS_CLOSE_STATUS_NOSTATUS);
1294                 return 1;
1295                 
1296
1297         case LWS_CONNMODE_WS_SERVING:
1298         case LWS_CONNMODE_WS_CLIENT:
1299
1300                 /* handle session socket closed */
1301
1302                 if (pollfd->revents & (POLLERR | POLLHUP)) {
1303
1304                         fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
1305                                 (void *)wsi, pollfd->fd);
1306
1307                         libwebsocket_close_and_free_session(this, wsi,
1308                                                      LWS_CLOSE_STATUS_NOSTATUS);
1309                         return 1;
1310                 }
1311
1312                 /* the guy requested a callback when it was OK to write */
1313
1314                 if (pollfd->revents & POLLOUT) {
1315
1316                         pollfd->events &= ~POLLOUT;
1317
1318                         /* external POLL support via protocol 0 */
1319                         this->protocols[0].callback(this, wsi,
1320                                 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1321                                 (void *)(long)wsi->sock, NULL, POLLOUT);
1322
1323                         wsi->protocol->callback(this, wsi,
1324                                 LWS_CALLBACK_CLIENT_WRITEABLE,
1325                                 wsi->user_space,
1326                                 NULL, 0);
1327                 }
1328
1329                 /* any incoming data ready? */
1330
1331                 if (!(pollfd->revents & POLLIN))
1332                         break;
1333
1334 #ifdef LWS_OPENSSL_SUPPORT
1335                 if (wsi->ssl)
1336                         n = SSL_read(wsi->ssl, buf, sizeof buf);
1337                 else
1338 #endif
1339                         n = recv(pollfd->fd, buf, sizeof buf, 0);
1340
1341                 if (n < 0) {
1342                         fprintf(stderr, "Socket read returned %d\n", n);
1343                         break;
1344                 }
1345                 if (!n) {
1346                         libwebsocket_close_and_free_session(this, wsi,
1347                                                      LWS_CLOSE_STATUS_NOSTATUS);
1348                         return 1;
1349                 }
1350
1351                 /* service incoming data */
1352
1353                 n = libwebsocket_read(this, wsi, buf, n);
1354                 if (n >= 0)
1355                         break;
1356
1357                 /* we closed wsi */
1358
1359                 return 1;
1360         }
1361
1362         return 0;
1363 }
1364
1365
1366 /**
1367  * libwebsocket_context_destroy() - Destroy the websocket context
1368  * @this:       Websocket context
1369  *
1370  *      This function closes any active connections and then frees the
1371  *      context.  After calling this, any further use of the context is
1372  *      undefined.
1373  */
1374 void
1375 libwebsocket_context_destroy(struct libwebsocket_context *this)
1376 {
1377         int n;
1378         int m;
1379         struct libwebsocket *wsi;
1380
1381         for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1382                 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1383                         wsi = this->fd_hashtable[n].wsi[m];
1384                         libwebsocket_close_and_free_session(this, wsi,
1385                                                     LWS_CLOSE_STATUS_GOINGAWAY);
1386                 }
1387
1388         close(this->fd_random);
1389
1390 #ifdef LWS_OPENSSL_SUPPORT
1391         if (this->ssl_ctx)
1392                 SSL_CTX_free(this->ssl_ctx);
1393         if (this->ssl_client_ctx)
1394                 SSL_CTX_free(this->ssl_client_ctx);
1395 #endif
1396
1397         free(this);
1398 }
1399
1400 /**
1401  * libwebsocket_service() - Service any pending websocket activity
1402  * @this:       Websocket context
1403  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1404  *              service otherwise block and service immediately, returning
1405  *              after the timeout if nothing needed service.
1406  *
1407  *      This function deals with any pending websocket traffic, for three
1408  *      kinds of event.  It handles these events on both server and client
1409  *      types of connection the same.
1410  *
1411  *      1) Accept new connections to our context's server
1412  *
1413  *      2) Perform pending broadcast writes initiated from other forked
1414  *         processes (effectively serializing asynchronous broadcasts)
1415  *
1416  *      3) Call the receive callback for incoming frame data received by
1417  *          server or client connections.
1418  *
1419  *      You need to call this service function periodically to all the above
1420  *      functions to happen; if your application is single-threaded you can
1421  *      just call it in your main event loop.
1422  *
1423  *      Alternatively you can fork a new process that asynchronously handles
1424  *      calling this service in a loop.  In that case you are happy if this
1425  *      call blocks your thread until it needs to take care of something and
1426  *      would call it with a large nonzero timeout.  Your loop then takes no
1427  *      CPU while there is nothing happening.
1428  *
1429  *      If you are calling it in a single-threaded app, you don't want it to
1430  *      wait around blocking other things in your loop from happening, so you
1431  *      would call it with a timeout_ms of 0, so it returns immediately if
1432  *      nothing is pending, or as soon as it services whatever was pending.
1433  */
1434
1435
1436 int
1437 libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
1438 {
1439         int n;
1440
1441         /* stay dead once we are dead */
1442
1443         if (this == NULL)
1444                 return 1;
1445
1446         /* wait for something to need service */
1447
1448         n = poll(this->fds, this->fds_count, timeout_ms);
1449         if (n == 0) /* poll timeout */
1450                 return 0;
1451
1452         if (n < 0) {
1453                 /*
1454                 fprintf(stderr, "Listen Socket dead\n");
1455                 */
1456                 return 1;
1457         }
1458
1459         /* handle accept on listening socket? */
1460
1461         for (n = 0; n < this->fds_count; n++)
1462                 if (this->fds[n].revents)
1463                         libwebsocket_service_fd(this, &this->fds[n]);
1464
1465         return 0;
1466 }
1467
1468 /**
1469  * libwebsocket_callback_on_writable() - Request a callback when this socket
1470  *                                       becomes able to be written to without
1471  *                                       blocking
1472  *
1473  * @this:       libwebsockets context
1474  * @wsi:        Websocket connection instance to get callback for
1475  */
1476
1477 int
1478 libwebsocket_callback_on_writable(struct libwebsocket_context *this,
1479                                                        struct libwebsocket *wsi)
1480 {
1481         int n;
1482
1483         for (n = 0; n < this->fds_count; n++)
1484                 if (this->fds[n].fd == wsi->sock) {
1485                         this->fds[n].events |= POLLOUT;
1486                         n = this->fds_count;
1487                 }
1488
1489         /* external POLL support via protocol 0 */
1490         this->protocols[0].callback(this, wsi,
1491                 LWS_CALLBACK_SET_MODE_POLL_FD,
1492                 (void *)(long)wsi->sock, NULL, POLLOUT);
1493
1494         return 1;
1495 }
1496
1497 /**
1498  * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1499  *                      all connections using the given protocol when it
1500  *                      becomes possible to write to each socket without
1501  *                      blocking in turn.
1502  *
1503  * @protocol:   Protocol whose connections will get callbacks
1504  */
1505
1506 int
1507 libwebsocket_callback_on_writable_all_protocol(
1508                                   const struct libwebsocket_protocols *protocol)
1509 {
1510         struct libwebsocket_context *this = protocol->owning_server;
1511         int n;
1512         int m;
1513         struct libwebsocket *wsi;
1514
1515         for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1516
1517                 for (m = 0; m < this->fd_hashtable[n].length; m++) {
1518
1519                         wsi = this->fd_hashtable[n].wsi[m];
1520
1521                         if (wsi->protocol == protocol)
1522                                 libwebsocket_callback_on_writable(this, wsi);
1523                 }
1524         }
1525
1526         return 0;
1527 }
1528
1529 /**
1530  * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1531  *
1532  * You will not need this unless you are doing something special
1533  *
1534  * @wsi:        Websocket connection instance
1535  * @reason:     timeout reason
1536  * @secs:       how many seconds
1537  */
1538
1539 void
1540 libwebsocket_set_timeout(struct libwebsocket *wsi,
1541                                           enum pending_timeout reason, int secs)
1542 {
1543         struct timeval tv;
1544
1545         gettimeofday(&tv, NULL);
1546
1547         wsi->pending_timeout_limit = tv.tv_sec + secs;
1548         wsi->pending_timeout = reason;
1549 }
1550
1551
1552 /**
1553  * libwebsocket_get_socket_fd() - returns the socket file descriptor
1554  *
1555  * You will not need this unless you are doing something special
1556  *
1557  * @wsi:        Websocket connection instance
1558  */
1559
1560 int
1561 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1562 {
1563         return wsi->sock;
1564 }
1565
1566 /**
1567  * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1568  *                              receieved packets.
1569  *
1570  * If the output side of a server process becomes choked, this allows flow
1571  * control for the input side.
1572  *
1573  * @wsi:        Websocket connection instance to get callback for
1574  * @enable:     0 = disable read servicing for this connection, 1 = enable
1575  */
1576
1577 int
1578 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1579 {
1580         struct libwebsocket_context *this = wsi->protocol->owning_server;
1581         int n;
1582
1583         for (n = 0; n < this->fds_count; n++)
1584                 if (this->fds[n].fd == wsi->sock) {
1585                         if (enable)
1586                                 this->fds[n].events |= POLLIN;
1587                         else
1588                                 this->fds[n].events &= ~POLLIN;
1589
1590                         return 0;
1591                 }
1592
1593         if (enable)
1594                 /* external POLL support via protocol 0 */
1595                 this->protocols[0].callback(this, wsi,
1596                         LWS_CALLBACK_SET_MODE_POLL_FD,
1597                         (void *)(long)wsi->sock, NULL, POLLIN);
1598         else
1599                 /* external POLL support via protocol 0 */
1600                 this->protocols[0].callback(this, wsi,
1601                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1602                         (void *)(long)wsi->sock, NULL, POLLIN);
1603
1604
1605         fprintf(stderr, "libwebsocket_callback_on_writable "
1606                                                      "unable to find socket\n");
1607         return 1;
1608 }
1609
1610 /**
1611  * libwebsocket_canonical_hostname() - returns this host's hostname
1612  *
1613  * This is typically used by client code to fill in the host parameter
1614  * when making a client connection.  You can only call it after the context
1615  * has been created.
1616  *
1617  * @this:       Websocket context
1618  */
1619
1620
1621 extern const char *
1622 libwebsocket_canonical_hostname(struct libwebsocket_context *this)
1623 {
1624         return (const char *)this->canonical_hostname;
1625 }
1626
1627
1628 static void sigpipe_handler(int x)
1629 {
1630 }
1631
1632 #ifdef LWS_OPENSSL_SUPPORT
1633 static int
1634 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1635 {
1636
1637         SSL *ssl;
1638         int n;
1639 //      struct libwebsocket_context *this;
1640
1641         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1642                 SSL_get_ex_data_X509_STORE_CTX_idx());
1643
1644         /*
1645          * !!! can't get this->openssl_websocket_private_data_index
1646          * can't store as a static either
1647          */
1648 //      this = SSL_get_ex_data(ssl, this->openssl_websocket_private_data_index);
1649         
1650         n = this->protocols[0].callback(NULL, NULL,
1651                 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1652                                                    x509_ctx, ssl, preverify_ok);
1653
1654         /* convert return code from 0 = OK to 1 = OK */
1655
1656         if (!n)
1657                 n = 1;
1658         else
1659                 n = 0;
1660
1661         return n;
1662 }
1663 #endif
1664
1665
1666 /**
1667  * libwebsocket_create_context() - Create the websocket handler
1668  * @port:       Port to listen on... you can use 0 to suppress listening on
1669  *              any port, that's what you want if you are not running a
1670  *              websocket server at all but just using it as a client
1671  * @interface:  NULL to bind the listen socket to all interfaces, or the
1672  *              interface name, eg, "eth2"
1673  * @protocols:  Array of structures listing supported protocols and a protocol-
1674  *              specific callback for each one.  The list is ended with an
1675  *              entry that has a NULL callback pointer.
1676  *              It's not const because we write the owning_server member
1677  * @ssl_cert_filepath:  If libwebsockets was compiled to use ssl, and you want
1678  *                      to listen using SSL, set to the filepath to fetch the
1679  *                      server cert from, otherwise NULL for unencrypted
1680  * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
1681  *                      else ignored
1682  * @gid:        group id to change to after setting listen socket, or -1.
1683  * @uid:        user id to change to after setting listen socket, or -1.
1684  * @options:    0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
1685  *
1686  *      This function creates the listening socket and takes care
1687  *      of all initialization in one step.
1688  *
1689  *      After initialization, it returns a struct libwebsocket_context * that
1690  *      represents this server.  After calling, user code needs to take care
1691  *      of calling libwebsocket_service() with the context pointer to get the
1692  *      server's sockets serviced.  This can be done in the same process context
1693  *      or a forked process, or another thread,
1694  *
1695  *      The protocol callback functions are called for a handful of events
1696  *      including http requests coming in, websocket connections becoming
1697  *      established, and data arriving; it's also called periodically to allow
1698  *      async transmission.
1699  *
1700  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
1701  *      at that time websocket protocol has not been negotiated.  Other
1702  *      protocols after the first one never see any HTTP callack activity.
1703  *
1704  *      The server created is a simple http server by default; part of the
1705  *      websocket standard is upgrading this http connection to a websocket one.
1706  *
1707  *      This allows the same server to provide files like scripts and favicon /
1708  *      images or whatever over http and dynamic data over websockets all in
1709  *      one place; they're all handled in the user callback.
1710  */
1711
1712 struct libwebsocket_context *
1713 libwebsocket_create_context(int port, const char *interface,
1714                                struct libwebsocket_protocols *protocols,
1715                                const char *ssl_cert_filepath,
1716                                const char *ssl_private_key_filepath,
1717                                int gid, int uid, unsigned int options)
1718 {
1719         int n;
1720         int sockfd = 0;
1721         int fd;
1722         struct sockaddr_in serv_addr, cli_addr;
1723         int opt = 1;
1724         struct libwebsocket_context *this = NULL;
1725         unsigned int slen;
1726         char *p;
1727         char hostname[1024];
1728         struct hostent *he;
1729         struct libwebsocket *wsi;
1730
1731 #ifdef LWS_OPENSSL_SUPPORT
1732         SSL_METHOD *method;
1733         char ssl_err_buf[512];
1734 #endif
1735
1736         this = malloc(sizeof(struct libwebsocket_context));
1737         if (!this) {
1738                 fprintf(stderr, "No memory for websocket context\n");
1739                 return NULL;
1740         }
1741         this->protocols = protocols;
1742         this->listen_port = port;
1743         this->http_proxy_port = 0;
1744         this->http_proxy_address[0] = '\0';
1745         this->options = options;
1746         this->fds_count = 0;
1747
1748         this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1749         if (this->fd_random < 0) {
1750                 fprintf(stderr, "Unable to open random device %s %d\n",
1751                                        SYSTEM_RANDOM_FILEPATH, this->fd_random);
1752                 return NULL;
1753         }
1754
1755         /* find canonical hostname */
1756
1757         hostname[(sizeof hostname) - 1] = '\0';
1758         gethostname(hostname, (sizeof hostname) - 1);
1759         he = gethostbyname(hostname);
1760         if (he) {
1761                 strncpy(this->canonical_hostname, he->h_name,
1762                                            sizeof this->canonical_hostname - 1);
1763                 this->canonical_hostname[sizeof this->canonical_hostname - 1] =
1764                                                                            '\0';
1765         } else
1766                 strncpy(this->canonical_hostname, hostname,
1767                                            sizeof this->canonical_hostname - 1);
1768
1769         /* split the proxy ads:port if given */
1770
1771         p = getenv("http_proxy");
1772         if (p) {
1773                 strncpy(this->http_proxy_address, p,
1774                                            sizeof this->http_proxy_address - 1);
1775                 this->http_proxy_address[
1776                                     sizeof this->http_proxy_address - 1] = '\0';
1777
1778                 p = strchr(this->http_proxy_address, ':');
1779                 if (p == NULL) {
1780                         fprintf(stderr, "http_proxy needs to be ads:port\n");
1781                         return NULL;
1782                 }
1783                 *p = '\0';
1784                 this->http_proxy_port = atoi(p + 1);
1785
1786                 fprintf(stderr, "Using proxy %s:%u\n",
1787                                 this->http_proxy_address,
1788                                                         this->http_proxy_port);
1789         }
1790
1791         if (port) {
1792
1793 #ifdef LWS_OPENSSL_SUPPORT
1794                 this->use_ssl = ssl_cert_filepath != NULL &&
1795                                                ssl_private_key_filepath != NULL;
1796                 if (this->use_ssl)
1797                         fprintf(stderr, " Compiled with SSL support, "
1798                                                                   "using it\n");
1799                 else
1800                         fprintf(stderr, " Compiled with SSL support, "
1801                                                               "not using it\n");
1802
1803 #else
1804                 if (ssl_cert_filepath != NULL &&
1805                                              ssl_private_key_filepath != NULL) {
1806                         fprintf(stderr, " Not compiled for OpenSSl support!\n");
1807                         return NULL;
1808                 }
1809                 fprintf(stderr, " Compiled without SSL support, "
1810                                                        "serving unencrypted\n");
1811 #endif
1812         }
1813
1814         /* ignore SIGPIPE */
1815
1816         signal(SIGPIPE, sigpipe_handler);
1817
1818
1819 #ifdef LWS_OPENSSL_SUPPORT
1820
1821         /* basic openssl init */
1822
1823         SSL_library_init();
1824
1825         OpenSSL_add_all_algorithms();
1826         SSL_load_error_strings();
1827
1828         this->openssl_websocket_private_data_index =
1829                 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1830
1831         /*
1832          * Firefox insists on SSLv23 not SSLv3
1833          * Konq disables SSLv2 by default now, SSLv23 works
1834          */
1835
1836         method = (SSL_METHOD *)SSLv23_server_method();
1837         if (!method) {
1838                 fprintf(stderr, "problem creating ssl method: %s\n",
1839                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1840                 return NULL;
1841         }
1842         this->ssl_ctx = SSL_CTX_new(method);    /* create context */
1843         if (!this->ssl_ctx) {
1844                 fprintf(stderr, "problem creating ssl context: %s\n",
1845                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1846                 return NULL;
1847         }
1848
1849         /* client context */
1850
1851         method = (SSL_METHOD *)SSLv23_client_method();
1852         if (!method) {
1853                 fprintf(stderr, "problem creating ssl method: %s\n",
1854                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1855                 return NULL;
1856         }
1857         this->ssl_client_ctx = SSL_CTX_new(method);     /* create context */
1858         if (!this->ssl_client_ctx) {
1859                 fprintf(stderr, "problem creating ssl context: %s\n",
1860                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1861                 return NULL;
1862         }
1863
1864
1865         /* openssl init for cert verification (used with client sockets) */
1866
1867         if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
1868                                                     LWS_OPENSSL_CLIENT_CERTS)) {
1869                 fprintf(stderr, "Unable to load SSL Client certs from %s "
1870                         "(set by --with-client-cert-dir= in configure) -- "
1871                         " client ssl isn't going to work",
1872                                                       LWS_OPENSSL_CLIENT_CERTS);
1873         }
1874
1875         /*
1876          * callback allowing user code to load extra verification certs
1877          * helping the client to verify server identity
1878          */
1879
1880         this->protocols[0].callback(this, NULL,
1881                 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1882                 this->ssl_client_ctx, NULL, 0);
1883
1884         /* as a server, are we requiring clients to identify themselves? */
1885
1886         if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1887
1888                 /* absolutely require the client cert */
1889                 
1890                 SSL_CTX_set_verify(this->ssl_ctx,
1891                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1892                                                        OpenSSL_verify_callback);
1893
1894                 /*
1895                  * give user code a chance to load certs into the server
1896                  * allowing it to verify incoming client certs
1897                  */
1898
1899                 this->protocols[0].callback(this, NULL,
1900                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
1901                                                         this->ssl_ctx, NULL, 0);
1902         }
1903
1904         if (this->use_ssl) {
1905
1906                 /* openssl init for server sockets */
1907
1908                 /* set the local certificate from CertFile */
1909                 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
1910                                         ssl_cert_filepath, SSL_FILETYPE_PEM);
1911                 if (n != 1) {
1912                         fprintf(stderr, "problem getting cert '%s': %s\n",
1913                                 ssl_cert_filepath,
1914                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
1915                         return NULL;
1916                 }
1917                 /* set the private key from KeyFile */
1918                 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
1919                                                 ssl_private_key_filepath,
1920                                                        SSL_FILETYPE_PEM) != 1) {
1921                         fprintf(stderr, "ssl problem getting key '%s': %s\n",
1922                                                 ssl_private_key_filepath,
1923                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
1924                         return NULL;
1925                 }
1926                 /* verify private key */
1927                 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
1928                         fprintf(stderr, "Private SSL key doesn't match cert\n");
1929                         return NULL;
1930                 }
1931
1932                 /* SSL is happy and has a cert it's content with */
1933         }
1934 #endif
1935
1936         /* selftest */
1937
1938         if (lws_b64_selftest())
1939                 return NULL;
1940
1941         /* fd hashtable init */
1942
1943         for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1944                 this->fd_hashtable[n].length = 0;
1945
1946         /* set up our external listening socket we serve on */
1947
1948         if (port) {
1949
1950                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1951                 if (sockfd < 0) {
1952                         fprintf(stderr, "ERROR opening socket");
1953                         return NULL;
1954                 }
1955
1956                 /* allow us to restart even if old sockets in TIME_WAIT */
1957                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1958
1959                 bzero((char *) &serv_addr, sizeof(serv_addr));
1960                 serv_addr.sin_family = AF_INET;
1961                 if (interface == NULL)
1962                         serv_addr.sin_addr.s_addr = INADDR_ANY;
1963                 else
1964                         interface_to_sa(interface, &serv_addr,
1965                                                 sizeof(serv_addr));
1966                 serv_addr.sin_port = htons(port);
1967
1968                 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1969                                                              sizeof(serv_addr));
1970                 if (n < 0) {
1971                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1972                                                                 port, n, errno);
1973                         return NULL;
1974                 }
1975
1976                 wsi = malloc(sizeof(struct libwebsocket));
1977                 memset(wsi, 0, sizeof (struct libwebsocket));
1978                 wsi->sock = sockfd;
1979                 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1980                 insert_wsi(this, wsi);
1981
1982                 listen(sockfd, 5);
1983                 fprintf(stderr, " Listening on port %d\n", port);
1984
1985                 /* list in the internal poll array */
1986                 
1987                 this->fds[this->fds_count].fd = sockfd;
1988                 this->fds[this->fds_count++].events = POLLIN;
1989
1990                 /* external POLL support via protocol 0 */
1991                 this->protocols[0].callback(this, wsi,
1992                         LWS_CALLBACK_ADD_POLL_FD,
1993                         (void *)(long)sockfd, NULL, POLLIN);
1994
1995         }
1996
1997         /* drop any root privs for this process */
1998
1999         if (gid != -1)
2000                 if (setgid(gid))
2001                         fprintf(stderr, "setgid: %s\n", strerror(errno));
2002         if (uid != -1)
2003                 if (setuid(uid))
2004                         fprintf(stderr, "setuid: %s\n", strerror(errno));
2005
2006
2007         /* set up our internal broadcast trigger sockets per-protocol */
2008
2009         for (this->count_protocols = 0;
2010                         protocols[this->count_protocols].callback;
2011                                                       this->count_protocols++) {
2012                 protocols[this->count_protocols].owning_server = this;
2013                 protocols[this->count_protocols].protocol_index =
2014                                                           this->count_protocols;
2015
2016                 fd = socket(AF_INET, SOCK_STREAM, 0);
2017                 if (fd < 0) {
2018                         fprintf(stderr, "ERROR opening socket");
2019                         return NULL;
2020                 }
2021
2022                 /* allow us to restart even if old sockets in TIME_WAIT */
2023                 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
2024
2025                 bzero((char *) &serv_addr, sizeof(serv_addr));
2026                 serv_addr.sin_family = AF_INET;
2027                 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2028                 serv_addr.sin_port = 0; /* pick the port for us */
2029
2030                 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2031                 if (n < 0) {
2032                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2033                                                                 port, n, errno);
2034                         return NULL;
2035                 }
2036
2037                 slen = sizeof cli_addr;
2038                 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2039                 if (n < 0) {
2040                         fprintf(stderr, "getsockname failed\n");
2041                         return NULL;
2042                 }
2043                 protocols[this->count_protocols].broadcast_socket_port =
2044                                                        ntohs(cli_addr.sin_port);
2045                 listen(fd, 5);
2046
2047                 debug("  Protocol %s broadcast socket %d\n",
2048                                 protocols[this->count_protocols].name,
2049                                                       ntohs(cli_addr.sin_port));
2050
2051                 /* dummy wsi per broadcast proxy socket */
2052
2053                 wsi = malloc(sizeof(struct libwebsocket));
2054                 memset(wsi, 0, sizeof (struct libwebsocket));
2055                 wsi->sock = fd;
2056                 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
2057                 /* note which protocol we are proxying */
2058                 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
2059                 insert_wsi(this, wsi);
2060
2061                 /* list in internal poll array */
2062
2063                 this->fds[this->fds_count].fd = fd;
2064                 this->fds[this->fds_count].events = POLLIN;
2065                 this->fds[this->fds_count].revents = 0;
2066                 this->fds_count++;
2067
2068                 /* external POLL support via protocol 0 */
2069                 this->protocols[0].callback(this, wsi,
2070                         LWS_CALLBACK_ADD_POLL_FD,
2071                         (void *)(long)fd, NULL, POLLIN);
2072         }
2073
2074         return this;
2075 }
2076
2077
2078 #ifndef LWS_NO_FORK
2079
2080 /**
2081  * libwebsockets_fork_service_loop() - Optional helper function forks off
2082  *                                a process for the websocket server loop.
2083  *                              You don't have to use this but if not, you
2084  *                              have to make sure you are calling
2085  *                              libwebsocket_service periodically to service
2086  *                              the websocket traffic
2087  * @this:       server context returned by creation function
2088  */
2089
2090 int
2091 libwebsockets_fork_service_loop(struct libwebsocket_context *this)
2092 {
2093         int fd;
2094         struct sockaddr_in cli_addr;
2095         int n;
2096         int p;
2097
2098         n = fork();
2099         if (n < 0)
2100                 return n;
2101
2102         if (!n) {
2103
2104                 /* main process context */
2105
2106                 /*
2107                  * set up the proxy sockets to allow broadcast from
2108                  * service process context
2109                  */
2110
2111                 for (p = 0; p < this->count_protocols; p++) {
2112                         fd = socket(AF_INET, SOCK_STREAM, 0);
2113                         if (fd < 0) {
2114                                 fprintf(stderr, "Unable to create socket\n");
2115                                 return -1;
2116                         }
2117                         cli_addr.sin_family = AF_INET;
2118                         cli_addr.sin_port = htons(
2119                              this->protocols[p].broadcast_socket_port);
2120                         cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2121                         n = connect(fd, (struct sockaddr *)&cli_addr,
2122                                                                sizeof cli_addr);
2123                         if (n < 0) {
2124                                 fprintf(stderr, "Unable to connect to "
2125                                                 "broadcast socket %d, %s\n",
2126                                                 n, strerror(errno));
2127                                 return -1;
2128                         }
2129
2130                         this->protocols[p].broadcast_socket_user_fd = fd;
2131                 }
2132
2133                 return 0;
2134         }
2135
2136         /* we want a SIGHUP when our parent goes down */
2137         prctl(PR_SET_PDEATHSIG, SIGHUP);
2138
2139         /* in this forked process, sit and service websocket connections */
2140
2141         while (1)
2142                 if (libwebsocket_service(this, 1000))
2143                         return -1;
2144
2145         return 0;
2146 }
2147
2148 #endif
2149
2150 /**
2151  * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2152  *                                connection.
2153  * @wsi:        pointer to struct websocket you want to know the protocol of
2154  *
2155  *
2156  *      This is useful to get the protocol to broadcast back to from inside
2157  * the callback.
2158  */
2159
2160 const struct libwebsocket_protocols *
2161 libwebsockets_get_protocol(struct libwebsocket *wsi)
2162 {
2163         return wsi->protocol;
2164 }
2165
2166 /**
2167  * libwebsockets_broadcast() - Sends a buffer to the callback for all active
2168  *                                connections of the given protocol.
2169  * @protocol:   pointer to the protocol you will broadcast to all members of
2170  * @buf:  buffer containing the data to be broadcase.  NOTE: this has to be
2171  *              allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
2172  *              the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
2173  *              case you are calling this function from callback context.
2174  * @len:        length of payload data in buf, starting from buf.
2175  *
2176  *      This function allows bulk sending of a packet to every connection using
2177  * the given protocol.  It does not send the data directly; instead it calls
2178  * the callback with a reason type of LWS_CALLBACK_BROADCAST.  If the callback
2179  * wants to actually send the data for that connection, the callback itself
2180  * should call libwebsocket_write().
2181  *
2182  * libwebsockets_broadcast() can be called from another fork context without
2183  * having to take any care about data visibility between the processes, it'll
2184  * "just work".
2185  */
2186
2187
2188 int
2189 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
2190                                                  unsigned char *buf, size_t len)
2191 {
2192         struct libwebsocket_context *this = protocol->owning_server;
2193         int n;
2194         int m;
2195         struct libwebsocket * wsi;
2196
2197         if (!protocol->broadcast_socket_user_fd) {
2198                 /*
2199                  * We are either running unforked / flat, or we are being
2200                  * called from poll thread context
2201                  * eg, from a callback.  In that case don't use sockets for
2202                  * broadcast IPC (since we can't open a socket connection to
2203                  * a socket listening on our own thread) but directly do the
2204                  * send action.
2205                  *
2206                  * Locking is not needed because we are by definition being
2207                  * called in the poll thread context and are serialized.
2208                  */
2209
2210                 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
2211
2212                         for (m = 0; m < this->fd_hashtable[n].length; m++) {
2213
2214                                 wsi = this->fd_hashtable[n].wsi[m];
2215
2216                                 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
2217                                         continue;
2218
2219                                 /*
2220                                  * never broadcast to
2221                                  * non-established connections
2222                                  */
2223                                 if (wsi->state != WSI_STATE_ESTABLISHED)
2224                                         continue;
2225
2226                                 /* only broadcast to guys using
2227                                  * requested protocol
2228                                  */
2229                                 if (wsi->protocol != protocol)
2230                                         continue;
2231
2232                                 wsi->protocol->callback(this, wsi,
2233                                          LWS_CALLBACK_BROADCAST,
2234                                          wsi->user_space,
2235                                          buf, len);
2236                         }
2237                 }
2238
2239                 return 0;
2240         }
2241
2242         /*
2243          * We're being called from a different process context than the server
2244          * loop.  Instead of broadcasting directly, we send our
2245          * payload on a socket to do the IPC; the server process will serialize
2246          * the broadcast action in its main poll() loop.
2247          *
2248          * There's one broadcast socket listening for each protocol supported
2249          * set up when the websocket server initializes
2250          */
2251
2252         n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
2253
2254         return n;
2255 }