introduce-libwebsockets_hangup_on_client.patch
[profile/ivi/libwebsockets.git] / lib / libwebsockets.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010 Andy Green <andy@warmcat.com>
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public
8  *  License as published by the Free Software Foundation:
9  *  version 2.1 of the License.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23
24 /* file descriptor hash management */
25
26 struct libwebsocket *
27 wsi_from_fd(struct libwebsocket_context *this, int fd)
28 {
29         int h = LWS_FD_HASH(fd);
30         int n = 0;
31
32         for (n = 0; n < this->fd_hashtable[h].length; n++)
33                 if (this->fd_hashtable[h].wsi[n]->sock == fd)
34                         return this->fd_hashtable[h].wsi[n];
35
36         return NULL;
37 }
38
39 int
40 insert_wsi(struct libwebsocket_context *this, struct libwebsocket *wsi)
41 {
42         int h = LWS_FD_HASH(wsi->sock);
43
44         if (this->fd_hashtable[h].length == MAX_CLIENTS - 1) {
45                 fprintf(stderr, "hash table overflow\n");
46                 return 1;
47         }
48
49         this->fd_hashtable[h].wsi[this->fd_hashtable[h].length++] = wsi;
50
51         return 0;
52 }
53
54 int
55 delete_from_fd(struct libwebsocket_context *this, int fd)
56 {
57         int h = LWS_FD_HASH(fd);
58         int n = 0;
59
60         for (n = 0; n < this->fd_hashtable[h].length; n++)
61                 if (this->fd_hashtable[h].wsi[n]->sock == fd) {
62                         while (n < this->fd_hashtable[h].length) {
63                                 this->fd_hashtable[h].wsi[n] =
64                                                this->fd_hashtable[h].wsi[n + 1];
65                                 n++;
66                         }
67                         this->fd_hashtable[h].length--;
68
69                         return 0;
70                 }
71
72         fprintf(stderr, "Failed to find fd %d requested for "
73                                                    "delete in hashtable\n", fd);
74         return 1;
75 }
76
77
78 void
79 libwebsocket_close_and_free_session(struct libwebsocket *wsi)
80 {
81         int n;
82         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
83                                                   LWS_SEND_BUFFER_POST_PADDING];
84
85         if ((unsigned long)wsi < LWS_MAX_PROTOCOLS)
86                 return;
87
88         n = wsi->state;
89
90         if (n == WSI_STATE_DEAD_SOCKET)
91                 return;
92
93         /*
94          * signal we are closing, libsocket_write will
95          * add any necessary version-specific stuff.  If the write fails,
96          * no worries we are closing anyway.  If we didn't initiate this
97          * close, then our state has been changed to
98          * WSI_STATE_RETURNED_CLOSE_ALREADY and we can skip this
99          */
100
101         if (n == WSI_STATE_ESTABLISHED)
102                 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
103                                                                LWS_WRITE_CLOSE);
104
105         wsi->state = WSI_STATE_DEAD_SOCKET;
106
107         if (wsi->protocol->callback && n == WSI_STATE_ESTABLISHED)
108                 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
109                                                       wsi->user_space, NULL, 0);
110
111         for (n = 0; n < WSI_TOKEN_COUNT; n++)
112                 if (wsi->utf8_token[n].token)
113                         free(wsi->utf8_token[n].token);
114
115 /*      fprintf(stderr, "closing fd=%d\n", wsi->sock); */
116
117 #ifdef LWS_OPENSSL_SUPPORT
118         if (wsi->ssl) {
119                 n = SSL_get_fd(wsi->ssl);
120                 SSL_shutdown(wsi->ssl);
121                 close(n);
122                 SSL_free(wsi->ssl);
123         } else {
124 #endif
125                 shutdown(wsi->sock, SHUT_RDWR);
126                 close(wsi->sock);
127 #ifdef LWS_OPENSSL_SUPPORT
128         }
129 #endif
130         if (wsi->user_space)
131                 free(wsi->user_space);
132
133         free(wsi);
134 }
135
136 /**
137  * libwebsockets_hangup_on_client() - Server calls to terminate client
138  *                                      connection
139  * @this:       libwebsockets context
140  * @fd:         Connection socket descriptor
141  */
142
143 void
144 libwebsockets_hangup_on_client(struct libwebsocket_context *this, int fd)
145 {
146         struct libwebsocket *wsi = wsi_from_fd(this, fd);
147
148         if (wsi == NULL)
149                 return;
150
151         libwebsocket_close_and_free_session(wsi);
152 }
153
154
155 /**
156  * libwebsockets_get_peer_addresses() - Get client address information
157  * @fd:         Connection socket descriptor
158  * @name:       Buffer to take client address name
159  * @name_len:   Length of client address name buffer
160  * @rip:        Buffer to take client address IP qotted quad
161  * @rip_len:    Length of client address IP buffer
162  *
163  *      This function fills in @name and @rip with the name and IP of
164  *      the client connected with socket descriptor @fd.  Names may be
165  *      truncated if there is not enough room.  If either cannot be
166  *      determined, they will be returned as valid zero-length strings.
167  */
168
169 void
170 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
171                                         char *rip, int rip_len)
172 {
173         unsigned int len;
174         struct sockaddr_in sin;
175         struct hostent *host;
176         struct hostent *host1;
177         char ip[128];
178         char *p;
179         int n;
180
181         rip[0] = '\0';
182         name[0] = '\0';
183
184         len = sizeof sin;
185         if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
186                 perror("getpeername");
187                 return;
188         }
189                 
190         host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
191                                                                        AF_INET);
192         if (host == NULL) {
193                 perror("gethostbyaddr");
194                 return;
195         }
196
197         strncpy(name, host->h_name, name_len);
198         name[name_len - 1] = '\0';
199
200         host1 = gethostbyname(host->h_name);
201         if (host1 == NULL)
202                 return;
203         p = (char *)host1;
204         n = 0;
205         while (p != NULL) {
206                 p = host1->h_addr_list[n++];
207                 if (p == NULL)
208                         continue;
209                 if (host1->h_addrtype != AF_INET)
210                         continue;
211
212                 sprintf(ip, "%d.%d.%d.%d",
213                                 p[0], p[1], p[2], p[3]);
214                 p = NULL;
215                 strncpy(rip, ip, rip_len);
216                 rip[rip_len - 1] = '\0';
217         }
218 }
219
220 /**
221  * libwebsocket_service_fd() - Service polled socket with something waiting
222  * @this:       Websocket context
223  * @pollfd:     The pollfd entry describing the socket fd and which events
224  *              happened.
225  *
226  *      This function closes any active connections and then frees the
227  *      context.  After calling this, any further use of the context is
228  *      undefined.
229  */
230
231 int
232 libwebsocket_service_fd(struct libwebsocket_context *this,
233                                                           struct pollfd *pollfd)
234 {
235         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
236                                                   LWS_SEND_BUFFER_POST_PADDING];
237         struct libwebsocket *wsi = wsi_from_fd(this, pollfd->fd);
238         struct libwebsocket *new_wsi;
239         int n;
240         int m;
241         size_t len;
242         int accept_fd;
243         unsigned int clilen;
244         struct sockaddr_in cli_addr;
245
246         if (wsi == NULL)
247                 return 1;
248
249         switch (wsi->mode) {
250         case LWS_CONNMODE_SERVER_LISTENER:
251
252                 /* pollin means a client has connected to us then */
253
254                 if (!pollfd->revents & POLLIN)
255                         break;
256
257                 /* listen socket got an unencrypted connection... */
258
259                 clilen = sizeof(cli_addr);
260                 accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
261                                                                        &clilen);
262                 if (accept_fd < 0) {
263                         fprintf(stderr, "ERROR on accept");
264                         break;
265                 }
266
267                 if (this->fds_count >= MAX_CLIENTS) {
268                         fprintf(stderr, "too busy to accept new client\n");
269                         close(accept_fd);
270                         break;
271                 }
272
273                 /*
274                  * look at who we connected to and give user code a chance
275                  * to reject based on client IP.  There's no protocol selected
276                  * yet so we issue this to protocols[0]
277                  */
278
279                 if ((this->protocols[0].callback)(wsi,
280                                 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
281                                              (void*)(long)accept_fd, NULL, 0)) {
282                         fprintf(stderr, "Callback denied network connection\n");
283                         close(accept_fd);
284                         break;
285                 }
286
287                 /* accepting connection to main listener */
288
289                 new_wsi = malloc(sizeof(struct libwebsocket));
290                 if (new_wsi == NULL) {
291                         fprintf(stderr, "Out of memory for new connection\n");
292                         break;
293                 }
294
295                 memset(new_wsi, 0, sizeof (struct libwebsocket));
296                 new_wsi->sock = accept_fd;
297
298 #ifdef LWS_OPENSSL_SUPPORT
299                 new_wsi->ssl = NULL;
300                 this->ssl_ctx = NULL;
301
302                 if (this->use_ssl) {
303
304                         new_wsi->ssl = SSL_new(this->ssl_ctx);
305                         if (new_wsi->ssl == NULL) {
306                                 fprintf(stderr, "SSL_new failed: %s\n",
307                                     ERR_error_string(SSL_get_error(
308                                     new_wsi->ssl, 0), NULL));
309                                 free(new_wsi);
310                                 break;
311                         }
312
313                         SSL_set_fd(new_wsi->ssl, accept_fd);
314
315                         n = SSL_accept(new_wsi->ssl);
316                         if (n != 1) {
317                                 /*
318                                  * browsers seem to probe with various
319                                  * ssl params which fail then retry
320                                  * and succeed
321                                  */
322                                 debug("SSL_accept failed skt %u: %s\n",
323                                       pollfd->fd,
324                                       ERR_error_string(SSL_get_error(
325                                       new_wsi->ssl, n), NULL));
326                                 SSL_free(
327                                        new_wsi->ssl);
328                                 free(new_wsi);
329                                 break;
330                         }
331                         debug("accepted new SSL conn  "
332                               "port %u on fd=%d SSL ver %s\n",
333                                 ntohs(cli_addr.sin_port), accept_fd,
334                                   SSL_get_version(new_wsi->ssl));
335
336                 } else
337 #endif
338                         debug("accepted new conn  port %u on fd=%d\n",
339                                           ntohs(cli_addr.sin_port), accept_fd);
340
341                 /* intialize the instance struct */
342
343                 new_wsi->state = WSI_STATE_HTTP;
344                 new_wsi->name_buffer_pos = 0;
345                 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
346
347                 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
348                         new_wsi->utf8_token[n].token = NULL;
349                         new_wsi->utf8_token[n].token_len = 0;
350                 }
351
352                 /*
353                  * these can only be set once the protocol is known
354                  * we set an unestablished connection's protocol pointer
355                  * to the start of the supported list, so it can look
356                  * for matching ones during the handshake
357                  */
358                 new_wsi->protocol = this->protocols;
359                 new_wsi->user_space = NULL;
360
361                 /*
362                  * Default protocol is 76 / 00
363                  * After 76, there's a header specified to inform which
364                  * draft the client wants, when that's seen we modify
365                  * the individual connection's spec revision accordingly
366                  */
367                 new_wsi->ietf_spec_revision = 0;
368
369                 insert_wsi(this, new_wsi);
370
371                 /*
372                  * make sure NO events are seen yet on this new socket
373                  * (otherwise we inherit old fds[client].revents from
374                  * previous socket there and die mysteriously! )
375                  */
376                 this->fds[this->fds_count].revents = 0;
377
378                 this->fds[this->fds_count].events = POLLIN;
379                 this->fds[this->fds_count++].fd = accept_fd;
380
381                 /* external POLL support via protocol 0 */
382                 this->protocols[0].callback(new_wsi,
383                         LWS_CALLBACK_ADD_POLL_FD,
384                         (void *)(long)accept_fd, NULL, POLLIN);
385
386                 break;
387
388         case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
389
390                 /* as we are listening, POLLIN means accept() is needed */
391         
392                 if (!pollfd->revents & POLLIN)
393                         break;
394
395                 /* listen socket got an unencrypted connection... */
396
397                 clilen = sizeof(cli_addr);
398                 accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
399                                                                        &clilen);
400                 if (accept_fd < 0) {
401                         fprintf(stderr, "ERROR on accept");
402                         break;
403                 }
404
405                 if (this->fds_count >= MAX_CLIENTS) {
406                         fprintf(stderr, "too busy to accept new broadcast "
407                                                               "proxy client\n");
408                         close(accept_fd);
409                         break;
410                 }
411
412                 /* create a dummy wsi for the connection and add it */
413
414                 new_wsi = malloc(sizeof(struct libwebsocket));
415                 memset(new_wsi, 0, sizeof (struct libwebsocket));
416                 new_wsi->sock = accept_fd;
417                 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
418                 new_wsi->state = WSI_STATE_ESTABLISHED;
419                 /* note which protocol we are proxying */
420                 new_wsi->protocol_index_for_broadcast_proxy =
421                                         wsi->protocol_index_for_broadcast_proxy;
422                 insert_wsi(this, new_wsi);
423
424                 /* add connected socket to internal poll array */
425
426                 this->fds[this->fds_count].revents = 0;
427                 this->fds[this->fds_count].events = POLLIN;
428                 this->fds[this->fds_count++].fd = accept_fd;
429
430                 /* external POLL support via protocol 0 */
431                 this->protocols[0].callback(new_wsi,
432                         LWS_CALLBACK_ADD_POLL_FD,
433                         (void *)(long)accept_fd, NULL, POLLIN);
434
435                 break;
436
437         case LWS_CONNMODE_BROADCAST_PROXY:
438
439                 /* handle session socket closed */
440
441                 if (pollfd->revents & (POLLERR | POLLHUP)) {
442
443                         debug("Session Socket %p (fd=%d) dead\n",
444                                 (void *)wsi, accept_fd);
445
446                         libwebsocket_close_and_free_session(wsi);
447                         goto nuke_this;
448                 }
449
450                 /* the guy requested a callback when it was OK to write */
451
452                 if (pollfd->revents & POLLOUT) {
453
454                         /* one shot */
455
456                         pollfd->events &= ~POLLOUT;
457
458                         /* external POLL support via protocol 0 */
459                         this->protocols[0].callback(wsi,
460                                 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
461                                 (void *)(long)wsi->sock, NULL, POLLOUT);
462
463                         wsi->protocol->callback(wsi,
464                                 LWS_CALLBACK_CLIENT_WRITEABLE,
465                                 wsi->user_space,
466                                 NULL, 0);
467                 }
468
469                 /* any incoming data ready? */
470
471                 if (!(pollfd->revents & POLLIN))
472                         break;
473
474                 /* get the issued broadcast payload from the socket */
475
476                 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
477                                                          MAX_BROADCAST_PAYLOAD);
478                 if (len < 0) {
479                         fprintf(stderr, "Error reading broadcast payload\n");
480                         break;;
481                 }
482
483                 /* broadcast it to all guys with this protocol index */
484
485                 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
486
487                         for (m = 0; m < this->fd_hashtable[n].length; m++) {
488
489                                 new_wsi = this->fd_hashtable[n].wsi[m];
490
491                                 /* only to clients we are serving to */
492
493                                 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
494                                         continue;
495
496                                 /*
497                                  * never broadcast to non-established
498                                  * connection
499                                  */
500
501                                 if (new_wsi->state != WSI_STATE_ESTABLISHED)
502                                         continue;
503
504                                 /*
505                                  * only broadcast to connections using
506                                  * the requested protocol
507                                  */
508
509                                 if (new_wsi->protocol->protocol_index !=
510                                         wsi->protocol_index_for_broadcast_proxy)
511                                         continue;
512
513                                 /* broadcast it to this connection */
514
515                                 new_wsi->protocol->callback(new_wsi,
516                                         LWS_CALLBACK_BROADCAST,
517                                         new_wsi->user_space,
518                                         buf + LWS_SEND_BUFFER_PRE_PADDING, len);
519                         }
520                 }
521                 break;
522
523         case LWS_CONNMODE_WS_SERVING:
524         case LWS_CONNMODE_WS_CLIENT:
525
526                 /* handle session socket closed */
527
528                 if (pollfd->revents & (POLLERR | POLLHUP)) {
529
530                         debug("Session Socket %p (fd=%d) dead\n",
531                                 (void *)wsi, pollfd->fd);
532
533                         libwebsocket_close_and_free_session(wsi);
534                         goto nuke_this;
535                 }
536
537                 /* the guy requested a callback when it was OK to write */
538
539                 if (pollfd->revents & POLLOUT) {
540
541                         pollfd->events &= ~POLLOUT;
542
543                         /* external POLL support via protocol 0 */
544                         this->protocols[0].callback(wsi,
545                                 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
546                                 (void *)(long)wsi->sock, NULL, POLLOUT);
547
548                         wsi->protocol->callback(wsi,
549                                 LWS_CALLBACK_CLIENT_WRITEABLE,
550                                 wsi->user_space,
551                                 NULL, 0);
552                 }
553
554                 /* any incoming data ready? */
555
556                 if (!(pollfd->revents & POLLIN))
557                         break;
558
559 #ifdef LWS_OPENSSL_SUPPORT
560                 if (wsi->ssl)
561                         n = SSL_read(wsi->ssl, buf, sizeof buf);
562                 else
563 #endif
564                         n = recv(pollfd->fd, buf, sizeof buf, 0);
565
566                 if (n < 0) {
567                         fprintf(stderr, "Socket read returned %d\n", n);
568                         break;;
569                 }
570                 if (!n) {
571                         libwebsocket_close_and_free_session(wsi);
572                         goto nuke_this;
573                 }
574
575                 /* service incoming data */
576
577                 n = libwebsocket_read(wsi, buf, n);
578                 if (n >= 0)
579                         break;;
580                 /*
581                  * it closed and nuked wsi[client], so remove the
582                  * socket handle and wsi from our service list
583                  */
584 nuke_this:
585
586                 debug("nuking wsi %p, fsd_count = %d\n",
587                                 (void *)wsi, this->fds_count - 1);
588
589                 delete_from_fd(this, pollfd->fd);
590
591                 this->fds_count--;
592                 for (n = 0; n < this->fds_count; n++)
593                         if (this->fds[n].fd == pollfd->fd) {
594                                 while (n < this->fds_count) {
595                                         this->fds[n] = this->fds[n + 1];
596                                         n++;
597                                 }
598                                 n = this->fds_count;
599                         }
600
601                 /* external POLL support via protocol 0 */
602                 this->protocols[0].callback(wsi,
603                         LWS_CALLBACK_DEL_POLL_FD,
604                         (void *)(long)pollfd->fd, NULL, 0);
605
606
607                 break;
608         }
609
610         return 0;
611 }
612
613
614 /**
615  * libwebsocket_context_destroy() - Destroy the websocket context
616  * @this:       Websocket context
617  *
618  *      This function closes any active connections and then frees the
619  *      context.  After calling this, any further use of the context is
620  *      undefined.
621  */
622 void
623 libwebsocket_context_destroy(struct libwebsocket_context *this)
624 {
625         int n;
626         int m;
627         struct libwebsocket *wsi;
628
629         for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
630
631                 for (m = 0; m < this->fd_hashtable[n].length; m++) {
632
633                         wsi = this->fd_hashtable[n].wsi[m];
634
635                         switch (wsi->mode) {
636                         case LWS_CONNMODE_WS_SERVING:
637                                 libwebsocket_close_and_free_session(wsi);
638                                 break;
639                         case LWS_CONNMODE_WS_CLIENT:
640                                 libwebsocket_client_close(wsi);
641                                 break;
642                         default:
643                                 break;
644                         }
645                 }
646         }
647
648         close(this->fd_random);
649
650 #ifdef LWS_OPENSSL_SUPPORT
651         if (this->ssl_ctx)
652                 SSL_CTX_free(this->ssl_ctx);
653         if (this->ssl_client_ctx)
654                 SSL_CTX_free(this->ssl_client_ctx);
655 #endif
656
657         free(this);
658 }
659
660 /**
661  * libwebsocket_service() - Service any pending websocket activity
662  * @this:       Websocket context
663  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
664  *              service otherwise block and service immediately, returning
665  *              after the timeout if nothing needed service.
666  *
667  *      This function deals with any pending websocket traffic, for three
668  *      kinds of event.  It handles these events on both server and client
669  *      types of connection the same.
670  *
671  *      1) Accept new connections to our context's server
672  *
673  *      2) Perform pending broadcast writes initiated from other forked
674  *         processes (effectively serializing asynchronous broadcasts)
675  *
676  *      3) Call the receive callback for incoming frame data received by
677  *          server or client connections.
678  *
679  *      You need to call this service function periodically to all the above
680  *      functions to happen; if your application is single-threaded you can
681  *      just call it in your main event loop.
682  *
683  *      Alternatively you can fork a new process that asynchronously handles
684  *      calling this service in a loop.  In that case you are happy if this
685  *      call blocks your thread until it needs to take care of something and
686  *      would call it with a large nonzero timeout.  Your loop then takes no
687  *      CPU while there is nothing happening.
688  *
689  *      If you are calling it in a single-threaded app, you don't want it to
690  *      wait around blocking other things in your loop from happening, so you
691  *      would call it with a timeout_ms of 0, so it returns immediately if
692  *      nothing is pending, or as soon as it services whatever was pending.
693  */
694
695
696 int
697 libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
698 {
699         int n;
700
701         /* stay dead once we are dead */
702
703         if (this == NULL)
704                 return 1;
705
706         /* wait for something to need service */
707
708         n = poll(this->fds, this->fds_count, timeout_ms);
709         if (n == 0) /* poll timeout */
710                 return 0;
711
712         if (n < 0 || this->fds[0].revents & (POLLERR | POLLHUP)) {
713                 /*
714                 fprintf(stderr, "Listen Socket dead\n");
715                 */
716                 return 1;
717         }
718
719         /* handle accept on listening socket? */
720
721         for (n = 0; n < this->fds_count; n++)
722                 if (this->fds[n].revents)
723                         libwebsocket_service_fd(this, &this->fds[n]);
724
725         return 0;
726 }
727
728 /**
729  * libwebsocket_callback_on_writable() - Request a callback when this socket
730  *                                       becomes able to be written to without
731  *                                       blocking
732  * *
733  * @wsi:        Websocket connection instance to get callback for
734  */
735
736 int
737 libwebsocket_callback_on_writable(struct libwebsocket *wsi)
738 {
739         struct libwebsocket_context *this = wsi->protocol->owning_server;
740         int n;
741
742         for (n = 0; n < this->fds_count; n++)
743                 if (this->fds[n].fd == wsi->sock) {
744                         this->fds[n].events |= POLLOUT;
745                         n = this->fds_count;
746                 }
747
748         /* external POLL support via protocol 0 */
749         this->protocols[0].callback(wsi,
750                 LWS_CALLBACK_SET_MODE_POLL_FD,
751                 (void *)(long)wsi->sock, NULL, POLLOUT);
752
753         return 1;
754 }
755
756 /**
757  * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
758  *                      all connections using the given protocol when it
759  *                      becomes possible to write to each socket without
760  *                      blocking in turn.
761  *
762  * @protocol:   Protocol whose connections will get callbacks
763  */
764
765 int
766 libwebsocket_callback_on_writable_all_protocol(
767                                   const struct libwebsocket_protocols *protocol)
768 {
769         struct libwebsocket_context *this = protocol->owning_server;
770         int n;
771         int m;
772         struct libwebsocket *wsi;
773
774         for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
775
776                 for (m = 0; m < this->fd_hashtable[n].length; m++) {
777
778                         wsi = this->fd_hashtable[n].wsi[m];
779
780                         if (wsi->protocol == protocol)
781                                 libwebsocket_callback_on_writable(wsi);
782                 }
783         }
784
785         return 0;
786 }
787
788
789 /**
790  * libwebsocket_get_socket_fd() - returns the socket file descriptor
791  *
792  * You will not need this unless you are doing something special
793  *
794  * @wsi:        Websocket connection instance
795  */
796
797 int
798 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
799 {
800         return wsi->sock;
801 }
802
803 /**
804  * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
805  *                              receieved packets.
806  *
807  * If the output side of a server process becomes choked, this allows flow
808  * control for the input side.
809  *
810  * @wsi:        Websocket connection instance to get callback for
811  * @enable:     0 = disable read servicing for this connection, 1 = enable
812  */
813
814 int
815 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
816 {
817         struct libwebsocket_context *this = wsi->protocol->owning_server;
818         int n;
819
820         for (n = 0; n < this->fds_count; n++)
821                 if (this->fds[n].fd == wsi->sock) {
822                         if (enable)
823                                 this->fds[n].events |= POLLIN;
824                         else
825                                 this->fds[n].events &= ~POLLIN;
826
827                         return 0;
828                 }
829
830         if (enable)
831                 /* external POLL support via protocol 0 */
832                 this->protocols[0].callback(wsi,
833                         LWS_CALLBACK_SET_MODE_POLL_FD,
834                         (void *)(long)wsi->sock, NULL, POLLIN);
835         else
836                 /* external POLL support via protocol 0 */
837                 this->protocols[0].callback(wsi,
838                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
839                         (void *)(long)wsi->sock, NULL, POLLIN);
840
841
842         fprintf(stderr, "libwebsocket_callback_on_writable "
843                                                      "unable to find socket\n");
844         return 1;
845 }
846
847 /**
848  * libwebsocket_canonical_hostname() - returns this host's hostname
849  *
850  * This is typically used by client code to fill in the host parameter
851  * when making a client connection.  You can only call it after the context
852  * has been created.
853  *
854  * @this:       Websocket context
855  */
856
857
858 extern const char *
859 libwebsocket_canonical_hostname(struct libwebsocket_context *this)
860 {
861         return (const char *)this->canonical_hostname;
862 }
863
864
865 static void sigpipe_handler(int x)
866 {
867 }
868
869
870
871 /**
872  * libwebsocket_create_context() - Create the websocket handler
873  * @port:       Port to listen on... you can use 0 to suppress listening on
874  *              any port, that's what you want if you are not running a
875  *              websocket server at all but just using it as a client
876  * @protocols:  Array of structures listing supported protocols and a protocol-
877  *              specific callback for each one.  The list is ended with an
878  *              entry that has a NULL callback pointer.
879  *              It's not const because we write the owning_server member
880  * @ssl_cert_filepath:  If libwebsockets was compiled to use ssl, and you want
881  *                      to listen using SSL, set to the filepath to fetch the
882  *                      server cert from, otherwise NULL for unencrypted
883  * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
884  *                      else ignored
885  * @gid:        group id to change to after setting listen socket, or -1.
886  * @uid:        user id to change to after setting listen socket, or -1.
887  * @options:    0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
888  *
889  *      This function creates the listening socket and takes care
890  *      of all initialization in one step.
891  *
892  *      After initialization, it returns a struct libwebsocket_context * that
893  *      represents this server.  After calling, user code needs to take care
894  *      of calling libwebsocket_service() with the context pointer to get the
895  *      server's sockets serviced.  This can be done in the same process context
896  *      or a forked process, or another thread,
897  *
898  *      The protocol callback functions are called for a handful of events
899  *      including http requests coming in, websocket connections becoming
900  *      established, and data arriving; it's also called periodically to allow
901  *      async transmission.
902  *
903  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
904  *      at that time websocket protocol has not been negotiated.  Other
905  *      protocols after the first one never see any HTTP callack activity.
906  *
907  *      The server created is a simple http server by default; part of the
908  *      websocket standard is upgrading this http connection to a websocket one.
909  *
910  *      This allows the same server to provide files like scripts and favicon /
911  *      images or whatever over http and dynamic data over websockets all in
912  *      one place; they're all handled in the user callback.
913  */
914
915 struct libwebsocket_context *
916 libwebsocket_create_context(int port,
917                                struct libwebsocket_protocols *protocols,
918                                const char *ssl_cert_filepath,
919                                const char *ssl_private_key_filepath,
920                                int gid, int uid, unsigned int options)
921 {
922         int n;
923         int sockfd = 0;
924         int fd;
925         struct sockaddr_in serv_addr, cli_addr;
926         int opt = 1;
927         struct libwebsocket_context *this = NULL;
928         unsigned int slen;
929         char *p;
930         char hostname[1024];
931         struct hostent *he;
932         struct libwebsocket *wsi;
933
934 #ifdef LWS_OPENSSL_SUPPORT
935         SSL_METHOD *method;
936         char ssl_err_buf[512];
937 #endif
938
939         this = malloc(sizeof(struct libwebsocket_context));
940         if (!this) {
941                 fprintf(stderr, "No memory for websocket context\n");
942                 return NULL;
943         }
944         this->protocols = protocols;
945         this->listen_port = port;
946         this->http_proxy_port = 0;
947         this->http_proxy_address[0] = '\0';
948         this->options = options;
949         this->fds_count = 0;
950
951         this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
952         if (this->fd_random < 0) {
953                 fprintf(stderr, "Unable to open random device %s %d\n",
954                                        SYSTEM_RANDOM_FILEPATH, this->fd_random);
955                 return NULL;
956         }
957
958         /* find canonical hostname */
959
960         hostname[(sizeof hostname) - 1] = '\0';
961         gethostname(hostname, (sizeof hostname) - 1);
962         he = gethostbyname(hostname);
963         strncpy(this->canonical_hostname, he->h_name,
964                                            sizeof this->canonical_hostname - 1);
965         this->canonical_hostname[sizeof this->canonical_hostname - 1] = '\0';
966         fprintf(stderr, "  canonical hostname = '%s'\n",
967                                         this->canonical_hostname);
968
969         /* split the proxy ads:port if given */
970
971         p = getenv("http_proxy");
972         if (p) {
973                 strncpy(this->http_proxy_address, p,
974                                            sizeof this->http_proxy_address - 1);
975                 this->http_proxy_address[
976                                     sizeof this->http_proxy_address - 1] = '\0';
977
978                 p = strchr(this->http_proxy_address, ':');
979                 if (p == NULL) {
980                         fprintf(stderr, "http_proxy needs to be ads:port\n");
981                         return NULL;
982                 }
983                 *p = '\0';
984                 this->http_proxy_port = atoi(p + 1);
985
986                 fprintf(stderr, "Using proxy %s:%u\n",
987                                 this->http_proxy_address,
988                                                         this->http_proxy_port);
989         }
990
991         if (port) {
992
993 #ifdef LWS_OPENSSL_SUPPORT
994                 this->use_ssl = ssl_cert_filepath != NULL &&
995                                                ssl_private_key_filepath != NULL;
996                 if (this->use_ssl)
997                         fprintf(stderr, " Compiled with SSL support, "
998                                                                   "using it\n");
999                 else
1000                         fprintf(stderr, " Compiled with SSL support, "
1001                                                               "not using it\n");
1002
1003 #else
1004                 if (ssl_cert_filepath != NULL &&
1005                                              ssl_private_key_filepath != NULL) {
1006                         fprintf(stderr, " Not compiled for OpenSSl support!\n");
1007                         return NULL;
1008                 }
1009                 fprintf(stderr, " Compiled without SSL support, "
1010                                                        "serving unencrypted\n");
1011 #endif
1012         }
1013
1014         /* ignore SIGPIPE */
1015
1016         signal(SIGPIPE, sigpipe_handler);
1017
1018
1019 #ifdef LWS_OPENSSL_SUPPORT
1020
1021         /* basic openssl init */
1022
1023         SSL_library_init();
1024
1025         OpenSSL_add_all_algorithms();
1026         SSL_load_error_strings();
1027
1028         /*
1029          * Firefox insists on SSLv23 not SSLv3
1030          * Konq disables SSLv2 by default now, SSLv23 works
1031          */
1032
1033         method = (SSL_METHOD *)SSLv23_server_method();
1034         if (!method) {
1035                 fprintf(stderr, "problem creating ssl method: %s\n",
1036                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1037                 return NULL;
1038         }
1039         this->ssl_ctx = SSL_CTX_new(method);    /* create context */
1040         if (!this->ssl_ctx) {
1041                 fprintf(stderr, "problem creating ssl context: %s\n",
1042                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1043                 return NULL;
1044         }
1045
1046         /* client context */
1047
1048         method = (SSL_METHOD *)SSLv23_client_method();
1049         if (!method) {
1050                 fprintf(stderr, "problem creating ssl method: %s\n",
1051                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1052                 return NULL;
1053         }
1054         this->ssl_client_ctx = SSL_CTX_new(method);     /* create context */
1055         if (!this->ssl_client_ctx) {
1056                 fprintf(stderr, "problem creating ssl context: %s\n",
1057                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1058                 return NULL;
1059         }
1060
1061
1062         /* openssl init for cert verification (used with client sockets) */
1063
1064         if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
1065                                                     LWS_OPENSSL_CLIENT_CERTS)) {
1066                 fprintf(stderr, "Unable to load SSL Client certs from %s "
1067                         "(set by --with-client-cert-dir= in configure) -- "
1068                         " client ssl isn't going to work",
1069                                                       LWS_OPENSSL_CLIENT_CERTS);
1070         }
1071
1072         if (this->use_ssl) {
1073
1074                 /* openssl init for server sockets */
1075
1076                 /* set the local certificate from CertFile */
1077                 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
1078                                         ssl_cert_filepath, SSL_FILETYPE_PEM);
1079                 if (n != 1) {
1080                         fprintf(stderr, "problem getting cert '%s': %s\n",
1081                                 ssl_cert_filepath,
1082                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
1083                         return NULL;
1084                 }
1085                 /* set the private key from KeyFile */
1086                 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
1087                                                 ssl_private_key_filepath,
1088                                                        SSL_FILETYPE_PEM) != 1) {
1089                         fprintf(stderr, "ssl problem getting key '%s': %s\n",
1090                                                 ssl_private_key_filepath,
1091                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
1092                         return NULL;
1093                 }
1094                 /* verify private key */
1095                 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
1096                         fprintf(stderr, "Private SSL key doesn't match cert\n");
1097                         return NULL;
1098                 }
1099
1100                 /* SSL is happy and has a cert it's content with */
1101         }
1102 #endif
1103
1104         /* selftest */
1105
1106         if (lws_b64_selftest())
1107                 return NULL;
1108
1109         /* fd hashtable init */
1110
1111         for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1112                 this->fd_hashtable[n].length = 0;
1113
1114         /* set up our external listening socket we serve on */
1115
1116         if (port) {
1117
1118                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1119                 if (sockfd < 0) {
1120                         fprintf(stderr, "ERROR opening socket");
1121                         return NULL;
1122                 }
1123
1124                 /* allow us to restart even if old sockets in TIME_WAIT */
1125                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1126
1127                 bzero((char *) &serv_addr, sizeof(serv_addr));
1128                 serv_addr.sin_family = AF_INET;
1129                 serv_addr.sin_addr.s_addr = INADDR_ANY;
1130                 serv_addr.sin_port = htons(port);
1131
1132                 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1133                                                              sizeof(serv_addr));
1134                 if (n < 0) {
1135                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1136                                                                 port, n, errno);
1137                         return NULL;
1138                 }
1139
1140                 wsi = malloc(sizeof(struct libwebsocket));
1141                 memset(wsi, 0, sizeof (struct libwebsocket));
1142                 wsi->sock = sockfd;
1143                 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1144                 insert_wsi(this, wsi);
1145
1146                 listen(sockfd, 5);
1147                 fprintf(stderr, " Listening on port %d\n", port);
1148
1149                 /* list in the internal poll array */
1150                 
1151                 this->fds[this->fds_count].fd = sockfd;
1152                 this->fds[this->fds_count++].events = POLLIN;
1153
1154                 /* external POLL support via protocol 0 */
1155                 this->protocols[0].callback(wsi,
1156                         LWS_CALLBACK_ADD_POLL_FD,
1157                         (void *)(long)sockfd, NULL, POLLIN);
1158
1159         }
1160
1161         /* drop any root privs for this process */
1162
1163         if (gid != -1)
1164                 if (setgid(gid))
1165                         fprintf(stderr, "setgid: %s\n", strerror(errno));
1166         if (uid != -1)
1167                 if (setuid(uid))
1168                         fprintf(stderr, "setuid: %s\n", strerror(errno));
1169
1170
1171         /* set up our internal broadcast trigger sockets per-protocol */
1172
1173         for (this->count_protocols = 0;
1174                         protocols[this->count_protocols].callback;
1175                                                       this->count_protocols++) {
1176                 protocols[this->count_protocols].owning_server = this;
1177                 protocols[this->count_protocols].protocol_index =
1178                                                           this->count_protocols;
1179
1180                 fd = socket(AF_INET, SOCK_STREAM, 0);
1181                 if (fd < 0) {
1182                         fprintf(stderr, "ERROR opening socket");
1183                         return NULL;
1184                 }
1185
1186                 /* allow us to restart even if old sockets in TIME_WAIT */
1187                 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1188
1189                 bzero((char *) &serv_addr, sizeof(serv_addr));
1190                 serv_addr.sin_family = AF_INET;
1191                 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1192                 serv_addr.sin_port = 0; /* pick the port for us */
1193
1194                 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1195                 if (n < 0) {
1196                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1197                                                                 port, n, errno);
1198                         return NULL;
1199                 }
1200
1201                 slen = sizeof cli_addr;
1202                 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1203                 if (n < 0) {
1204                         fprintf(stderr, "getsockname failed\n");
1205                         return NULL;
1206                 }
1207                 protocols[this->count_protocols].broadcast_socket_port =
1208                                                        ntohs(cli_addr.sin_port);
1209                 listen(fd, 5);
1210
1211                 debug("  Protocol %s broadcast socket %d\n",
1212                                 protocols[this->count_protocols].name,
1213                                                       ntohs(cli_addr.sin_port));
1214
1215                 /* dummy wsi per broadcast proxy socket */
1216
1217                 wsi = malloc(sizeof(struct libwebsocket));
1218                 memset(wsi, 0, sizeof (struct libwebsocket));
1219                 wsi->sock = fd;
1220                 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1221                 /* note which protocol we are proxying */
1222                 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
1223                 insert_wsi(this, wsi);
1224
1225                 /* list in internal poll array */
1226
1227                 this->fds[this->fds_count].fd = fd;
1228                 this->fds[this->fds_count].events = POLLIN;
1229                 this->fds[this->fds_count].revents = 0;
1230                 this->fds_count++;
1231
1232                 /* external POLL support via protocol 0 */
1233                 this->protocols[0].callback(wsi,
1234                         LWS_CALLBACK_ADD_POLL_FD,
1235                         (void *)(long)fd, NULL, POLLIN);
1236         }
1237
1238         return this;
1239 }
1240
1241
1242 #ifndef LWS_NO_FORK
1243
1244 /**
1245  * libwebsockets_fork_service_loop() - Optional helper function forks off
1246  *                                a process for the websocket server loop.
1247  *                              You don't have to use this but if not, you
1248  *                              have to make sure you are calling
1249  *                              libwebsocket_service periodically to service
1250  *                              the websocket traffic
1251  * @this:       server context returned by creation function
1252  */
1253
1254 int
1255 libwebsockets_fork_service_loop(struct libwebsocket_context *this)
1256 {
1257         int fd;
1258         struct sockaddr_in cli_addr;
1259         int n;
1260         int p;
1261
1262         n = fork();
1263         if (n < 0)
1264                 return n;
1265
1266         if (!n) {
1267
1268                 /* main process context */
1269
1270                 /*
1271                  * set up the proxy sockets to allow broadcast from
1272                  * service process context
1273                  */
1274
1275                 for (p = 0; p < this->count_protocols; p++) {
1276                         fd = socket(AF_INET, SOCK_STREAM, 0);
1277                         if (fd < 0) {
1278                                 fprintf(stderr, "Unable to create socket\n");
1279                                 return -1;
1280                         }
1281                         cli_addr.sin_family = AF_INET;
1282                         cli_addr.sin_port = htons(
1283                              this->protocols[p].broadcast_socket_port);
1284                         cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1285                         n = connect(fd, (struct sockaddr *)&cli_addr,
1286                                                                sizeof cli_addr);
1287                         if (n < 0) {
1288                                 fprintf(stderr, "Unable to connect to "
1289                                                 "broadcast socket %d, %s\n",
1290                                                 n, strerror(errno));
1291                                 return -1;
1292                         }
1293
1294                         this->protocols[p].broadcast_socket_user_fd = fd;
1295                 }
1296
1297                 return 0;
1298         }
1299
1300         /* we want a SIGHUP when our parent goes down */
1301         prctl(PR_SET_PDEATHSIG, SIGHUP);
1302
1303         /* in this forked process, sit and service websocket connections */
1304
1305         while (1)
1306                 if (libwebsocket_service(this, 1000))
1307                         return -1;
1308
1309         return 0;
1310 }
1311
1312 #endif
1313
1314 /**
1315  * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
1316  *                                connection.
1317  * @wsi:        pointer to struct websocket you want to know the protocol of
1318  *
1319  *
1320  *      This is useful to get the protocol to broadcast back to from inside
1321  * the callback.
1322  */
1323
1324 const struct libwebsocket_protocols *
1325 libwebsockets_get_protocol(struct libwebsocket *wsi)
1326 {
1327         return wsi->protocol;
1328 }
1329
1330 /**
1331  * libwebsockets_broadcast() - Sends a buffer to the callback for all active
1332  *                                connections of the given protocol.
1333  * @protocol:   pointer to the protocol you will broadcast to all members of
1334  * @buf:  buffer containing the data to be broadcase.  NOTE: this has to be
1335  *              allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
1336  *              the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
1337  *              case you are calling this function from callback context.
1338  * @len:        length of payload data in buf, starting from buf.
1339  *
1340  *      This function allows bulk sending of a packet to every connection using
1341  * the given protocol.  It does not send the data directly; instead it calls
1342  * the callback with a reason type of LWS_CALLBACK_BROADCAST.  If the callback
1343  * wants to actually send the data for that connection, the callback itself
1344  * should call libwebsocket_write().
1345  *
1346  * libwebsockets_broadcast() can be called from another fork context without
1347  * having to take any care about data visibility between the processes, it'll
1348  * "just work".
1349  */
1350
1351
1352 int
1353 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
1354                                                  unsigned char *buf, size_t len)
1355 {
1356         struct libwebsocket_context *this = protocol->owning_server;
1357         int n;
1358         int m;
1359         struct libwebsocket * wsi;
1360
1361         if (!protocol->broadcast_socket_user_fd) {
1362                 /*
1363                  * We are either running unforked / flat, or we are being
1364                  * called from poll thread context
1365                  * eg, from a callback.  In that case don't use sockets for
1366                  * broadcast IPC (since we can't open a socket connection to
1367                  * a socket listening on our own thread) but directly do the
1368                  * send action.
1369                  *
1370                  * Locking is not needed because we are by definition being
1371                  * called in the poll thread context and are serialized.
1372                  */
1373
1374                 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1375
1376                         for (m = 0; m < this->fd_hashtable[n].length; m++) {
1377
1378                                 wsi = this->fd_hashtable[n].wsi[m];
1379
1380                                 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
1381                                         continue;
1382
1383                                 /*
1384                                  * never broadcast to
1385                                  * non-established connections
1386                                  */
1387                                 if (wsi->state != WSI_STATE_ESTABLISHED)
1388                                         continue;
1389
1390                                 /* only broadcast to guys using
1391                                  * requested protocol
1392                                  */
1393                                 if (wsi->protocol != protocol)
1394                                         continue;
1395
1396                                 wsi->protocol->callback(wsi,
1397                                          LWS_CALLBACK_BROADCAST,
1398                                          wsi->user_space,
1399                                          buf, len);
1400                         }
1401                 }
1402
1403                 return 0;
1404         }
1405
1406         /*
1407          * We're being called from a different process context than the server
1408          * loop.  Instead of broadcasting directly, we send our
1409          * payload on a socket to do the IPC; the server process will serialize
1410          * the broadcast action in its main poll() loop.
1411          *
1412          * There's one broadcast socket listening for each protocol supported
1413          * set up when the websocket server initializes
1414          */
1415
1416         n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
1417
1418         return n;
1419 }