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