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