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