change-client-mode-to-enum.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 void
25 libwebsocket_close_and_free_session(struct libwebsocket *wsi)
26 {
27         int n;
28
29         if ((unsigned long)wsi < LWS_MAX_PROTOCOLS)
30                 return;
31
32         n = wsi->state;
33
34         wsi->state = WSI_STATE_DEAD_SOCKET;
35
36         if (wsi->protocol->callback && n == WSI_STATE_ESTABLISHED)
37                 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
38                                                       wsi->user_space, NULL, 0);
39
40         for (n = 0; n < WSI_TOKEN_COUNT; n++)
41                 if (wsi->utf8_token[n].token)
42                         free(wsi->utf8_token[n].token);
43
44 /*      fprintf(stderr, "closing fd=%d\n", wsi->sock); */
45
46 #ifdef LWS_OPENSSL_SUPPORT
47         if (wsi->ssl) {
48                 n = SSL_get_fd(wsi->ssl);
49                 SSL_shutdown(wsi->ssl);
50                 close(n);
51                 SSL_free(wsi->ssl);
52         } else {
53 #endif
54                 shutdown(wsi->sock, SHUT_RDWR);
55                 close(wsi->sock);
56 #ifdef LWS_OPENSSL_SUPPORT
57         }
58 #endif
59         if (wsi->user_space)
60                 free(wsi->user_space);
61
62         free(wsi);
63 }
64
65 static int
66 libwebsocket_poll_connections(struct libwebsocket_context *this)
67 {
68         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
69                                                   LWS_SEND_BUFFER_POST_PADDING];
70         int client = this->count_protocols + 1;
71         struct libwebsocket *wsi;
72         int n;
73         size_t len;
74
75         /* check for activity on client sockets */
76
77         for (; client < this->fds_count; client++) {
78
79                 /* handle session socket closed */
80
81                 if (this->fds[client].revents & (POLLERR | POLLHUP)) {
82
83                         debug("Session Socket %d %p (fd=%d) dead\n",
84                                 client, (void *)this->wsi[client],
85                                                           this->fds[client].fd);
86
87                         libwebsocket_close_and_free_session(this->wsi[client]);
88                         goto nuke_this;
89                 }
90
91                 /* the guy requested a callback when it was OK to write */
92
93                 if ((unsigned long)this->wsi[client] > LWS_MAX_PROTOCOLS &&
94                                           this->fds[client].revents & POLLOUT) {
95
96                         this->fds[client].events &= ~POLLOUT;
97
98                         this->wsi[client]->protocol->callback(this->wsi[client],
99                                 LWS_CALLBACK_CLIENT_WRITEABLE,
100                                 this->wsi[client]->user_space,
101                                 NULL, 0);
102                 }
103
104                 /* any incoming data ready? */
105
106                 if (!(this->fds[client].revents & POLLIN))
107                         continue;
108
109                 /* broadcast? */
110
111                 if ((unsigned long)this->wsi[client] < LWS_MAX_PROTOCOLS) {
112
113                         /* get the issued broadcast payload from the socket */
114
115                         len = read(this->fds[client].fd,
116                                    buf + LWS_SEND_BUFFER_PRE_PADDING,
117                                    MAX_BROADCAST_PAYLOAD);
118
119                         if (len < 0) {
120                                 fprintf(stderr,
121                                            "Error reading broadcast payload\n");
122                                 continue;
123                         }
124
125                         /* broadcast it to all guys with this protocol index */
126
127                         for (n = this->count_protocols + 1;
128                                                      n < this->fds_count; n++) {
129
130                                 wsi = this->wsi[n];
131
132                                 if ((unsigned long)wsi < LWS_MAX_PROTOCOLS)
133                                         continue;
134
135                                 /*
136                                  * never broadcast to non-established
137                                  * connection
138                                  */
139
140                                 if (wsi->state != WSI_STATE_ESTABLISHED)
141                                         continue;
142
143                                 /* only to clients connected to us */
144
145                                 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
146                                         continue;
147
148                                 /*
149                                  * only broadcast to connections using
150                                  * the requested protocol
151                                  */
152
153                                 if (wsi->protocol->protocol_index !=
154                                           (int)(unsigned long)this->wsi[client])
155                                         continue;
156
157                                 /* broadcast it to this connection */
158
159                                 wsi->protocol->callback(wsi,
160                                         LWS_CALLBACK_BROADCAST,
161                                         wsi->user_space,
162                                         buf + LWS_SEND_BUFFER_PRE_PADDING, len);
163                         }
164
165                         continue;
166                 }
167
168 #ifdef LWS_OPENSSL_SUPPORT
169                 if (this->wsi[client]->ssl)
170                         n = SSL_read(this->wsi[client]->ssl, buf, sizeof buf);
171                 else
172 #endif
173                         n = recv(this->fds[client].fd, buf, sizeof buf, 0);
174
175                 if (n < 0) {
176                         fprintf(stderr, "Socket read returned %d\n", n);
177                         continue;
178                 }
179                 if (!n) {
180                         libwebsocket_close_and_free_session(this->wsi[client]);
181                         goto nuke_this;
182                 }
183
184                 /* service incoming data */
185
186                 n = libwebsocket_read(this->wsi[client], buf, n);
187                 if (n >= 0)
188                         continue;
189                 /*
190                  * it closed and nuked wsi[client], so remove the
191                  * socket handle and wsi from our service list
192                  */
193 nuke_this:
194
195                 debug("nuking wsi %p, fsd_count = %d\n",
196                                 (void *)this->wsi[client], this->fds_count - 1);
197
198                 this->fds_count--;
199                 for (n = client; n < this->fds_count; n++) {
200                         this->fds[n] = this->fds[n + 1];
201                         this->wsi[n] = this->wsi[n + 1];
202                 }
203
204                 return 0;
205
206         }
207
208         return 0;
209 }
210
211 /**
212  * libwebsocket_context_destroy() - Destroy the websocket context
213  * @this:       Websocket context
214  *
215  *      This function closes any active connections and then frees the
216  *      context.  After calling this, any further use of the context is
217  *      undefined.
218  */
219 void
220 libwebsocket_context_destroy(struct libwebsocket_context *this)
221 {
222         int client;
223
224         /* close listening skt and per-protocol broadcast sockets */
225         for (client = this->count_protocols + 1; client < this->fds_count; client++)
226                 switch (this->wsi[client]->mode) {
227                 case LWS_CONNMODE_WS_SERVING:
228                         libwebsocket_close_and_free_session(this->wsi[client]);
229                         break;
230                 case LWS_CONNMODE_WS_CLIENT:
231                         libwebsocket_client_close(this->wsi[client]);
232                         break;
233                 }
234
235 #ifdef LWS_OPENSSL_SUPPORT
236         if (this->ssl_ctx)
237                 SSL_CTX_free(this->ssl_ctx);
238 #endif
239
240         if (this)
241                 free(this);
242 }
243
244 /**
245  * libwebsocket_service() - Service any pending websocket activity
246  * @this:       Websocket context
247  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
248  *              service otherwise block and service immediately, returning
249  *              after the timeout if nothing needed service.
250  *
251  *      This function deals with any pending websocket traffic, for three
252  *      kinds of event.  It handles these events on both server and client
253  *      types of connection the same.
254  *
255  *      1) Accept new connections to our context's server
256  *
257  *      2) Perform pending broadcast writes initiated from other forked
258  *         processes (effectively serializing asynchronous broadcasts)
259  *
260  *      3) Call the receive callback for incoming frame data received by
261  *          server or client connections.
262  *
263  *      You need to call this service function periodically to all the above
264  *      functions to happen; if your application is single-threaded you can
265  *      just call it in your main event loop.
266  *
267  *      Alternatively you can fork a new process that asynchronously handles
268  *      calling this service in a loop.  In that case you are happy if this
269  *      call blocks your thread until it needs to take care of something and
270  *      would call it with a large nonzero timeout.  Your loop then takes no
271  *      CPU while there is nothing happening.
272  *
273  *      If you are calling it in a single-threaded app, you don't want it to
274  *      wait around blocking other things in your loop from happening, so you
275  *      would call it with a timeout_ms of 0, so it returns immediately if
276  *      nothing is pending, or as soon as it services whatever was pending.
277  */
278
279
280 int
281 libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
282 {
283         int n;
284         int client;
285         unsigned int clilen;
286         struct sockaddr_in cli_addr;
287         int fd;
288
289         /* stay dead once we are dead */
290
291         if (this == NULL)
292                 return 1;
293
294         /* don't check listen socket if we are not listening */
295
296         if (this->listen_port)
297                 n = poll(this->fds, this->fds_count, timeout_ms);
298         else
299                 n = poll(&this->fds[1], this->fds_count - 1, timeout_ms);
300
301
302         if (n < 0 || this->fds[0].revents & (POLLERR | POLLHUP)) {
303                 fprintf(stderr, "Listen Socket dead\n");
304                 goto fatal;
305         }
306         if (n == 0) /* poll timeout */
307                 return 0;
308
309         /* handle accept on listening socket? */
310
311         for (client = 0; client < this->count_protocols + 1; client++) {
312
313                 if (!this->fds[client].revents & POLLIN)
314                         continue;
315
316                 /* listen socket got an unencrypted connection... */
317
318                 clilen = sizeof(cli_addr);
319                 fd  = accept(this->fds[client].fd,
320                              (struct sockaddr *)&cli_addr, &clilen);
321                 if (fd < 0) {
322                         fprintf(stderr, "ERROR on accept");
323                         continue;
324                 }
325
326                 if (this->fds_count >= MAX_CLIENTS) {
327                         fprintf(stderr, "too busy");
328                         close(fd);
329                         continue;
330                 }
331
332                 if (client) {
333                         /*
334                          * accepting a connection to broadcast socket
335                          * set wsi to be protocol index not pointer
336                          */
337
338                         this->wsi[this->fds_count] =
339                               (struct libwebsocket *)(long)(client - 1);
340
341                         goto fill_in_fds;
342                 }
343
344                 /* accepting connection to main listener */
345
346                 this->wsi[this->fds_count] =
347                                     malloc(sizeof(struct libwebsocket));
348                 if (!this->wsi[this->fds_count]) {
349                         fprintf(stderr, "Out of memory for new connection\n");
350                         continue;
351                 }
352
353 #ifdef LWS_OPENSSL_SUPPORT
354                 this->wsi[this->fds_count]->ssl = NULL;
355
356                 if (this->use_ssl) {
357
358                         this->wsi[this->fds_count]->ssl =
359                                                          SSL_new(this->ssl_ctx);
360                         if (this->wsi[this->fds_count]->ssl == NULL) {
361                                 fprintf(stderr, "SSL_new failed: %s\n",
362                                     ERR_error_string(SSL_get_error(
363                                     this->wsi[this->fds_count]->ssl, 0),
364                                                                  NULL));
365                                 free(this->wsi[this->fds_count]);
366                                 continue;
367                         }
368
369                         SSL_set_fd(this->wsi[this->fds_count]->ssl, fd);
370
371                         n = SSL_accept(this->wsi[this->fds_count]->ssl);
372                         if (n != 1) {
373                                 /*
374                                  * browsers seem to probe with various
375                                  * ssl params which fail then retry
376                                  * and succeed
377                                  */
378                                 debug("SSL_accept failed skt %u: %s\n",
379                                       fd,
380                                       ERR_error_string(SSL_get_error(
381                                       this->wsi[this->fds_count]->ssl,
382                                                              n), NULL));
383                                 SSL_free(
384                                        this->wsi[this->fds_count]->ssl);
385                                 free(this->wsi[this->fds_count]);
386                                 continue;
387                         }
388                         debug("accepted new SSL conn  "
389                               "port %u on fd=%d SSL ver %s\n",
390                                 ntohs(cli_addr.sin_port), fd,
391                                   SSL_get_version(this->wsi[
392                                                 this->fds_count]->ssl));
393
394                 } else
395 #endif
396                         debug("accepted new conn  port %u on fd=%d\n",
397                                           ntohs(cli_addr.sin_port), fd);
398
399                 /* intialize the instance struct */
400
401                 this->wsi[this->fds_count]->sock = fd;
402                 this->wsi[this->fds_count]->state = WSI_STATE_HTTP;
403                 this->wsi[this->fds_count]->name_buffer_pos = 0;
404                 this->wsi[this->fds_count]->mode = LWS_CONNMODE_WS_SERVING;
405
406                 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
407                         this->wsi[this->fds_count]->
408                                              utf8_token[n].token = NULL;
409                         this->wsi[this->fds_count]->
410                                             utf8_token[n].token_len = 0;
411                 }
412
413                 /*
414                  * these can only be set once the protocol is known
415                  * we set an unestablished connection's protocol pointer
416                  * to the start of the supported list, so it can look
417                  * for matching ones during the handshake
418                  */
419                 this->wsi[this->fds_count]->protocol = this->protocols;
420                 this->wsi[this->fds_count]->user_space = NULL;
421
422                 /*
423                  * Default protocol is 76 / 00
424                  * After 76, there's a header specified to inform which
425                  * draft the client wants, when that's seen we modify
426                  * the individual connection's spec revision accordingly
427                  */
428                 this->wsi[this->fds_count]->ietf_spec_revision = 0;
429
430 fill_in_fds:
431
432                 /*
433                  * make sure NO events are seen yet on this new socket
434                  * (otherwise we inherit old fds[client].revents from
435                  * previous socket there and die mysteriously! )
436                  */
437                 this->fds[this->fds_count].revents = 0;
438
439                 this->fds[this->fds_count].events = POLLIN;
440                 this->fds[this->fds_count++].fd = fd;
441
442         }
443
444         /* service anything incoming on websocket connection */
445
446         libwebsocket_poll_connections(this);
447
448         /* this round is done */
449
450         return 0;
451
452 fatal:
453
454         fprintf(stderr, "service hits fatal\n");
455
456         /* close listening skt and per-protocol broadcast sockets */
457         for (client = 0; client < this->fds_count; client++)
458                 close(this->fds[0].fd);
459
460 #ifdef LWS_OPENSSL_SUPPORT
461         if (this->ssl_ctx)
462                 SSL_CTX_free(this->ssl_ctx);
463 #endif
464
465         if (this)
466                 free(this);
467
468         this = NULL;
469
470         /* inform caller we are dead */
471
472         return 1;
473 }
474
475 /**
476  * libwebsocket_callback_on_writable() - Request a callback when this socket
477  *                                       becomes able to be written to without
478  *                                       blocking
479  *
480  * @wsi:        Websocket connection instance to get callback for
481  */
482
483 int
484 libwebsocket_callback_on_writable(struct libwebsocket *wsi)
485 {
486         struct libwebsocket_context *this = wsi->protocol->owning_server;
487         int n;
488
489         for (n = this->count_protocols + 1; n < this->fds_count; n++)
490                 if (this->wsi[n] == wsi) {
491                         this->fds[n].events |= POLLOUT;
492                         return 0;
493                 }
494
495         fprintf(stderr, "libwebsocket_callback_on_writable "
496                                                         "didn't find socket\n");
497         return 1;
498 }
499
500 /**
501  * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
502  *                      all connections using the given protocol when it
503  *                      becomes possible to write to each socket without
504  *                      blocking in turn.
505  *
506  * @protocol:   Protocol whose connections will get callbacks
507  */
508
509 int
510 libwebsocket_callback_on_writable_all_protocol(
511                                   const struct libwebsocket_protocols *protocol)
512 {
513         struct libwebsocket_context *this = protocol->owning_server;
514         int n;
515
516         for (n = this->count_protocols + 1; n < this->fds_count; n++)
517                 if ((unsigned long)this->wsi[n] > LWS_MAX_PROTOCOLS)
518                         if (this->wsi[n]->protocol == protocol)
519                                 this->fds[n].events |= POLLOUT;
520
521         return 0;
522 }
523
524
525 /**
526  * libwebsocket_get_socket_fd() - returns the socket file descriptor
527  *
528  * You will not need this unless you are doing something special
529  *
530  * @wsi:        Websocket connection instance
531  */
532
533 int
534 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
535 {
536         return wsi->sock;
537 }
538
539 /**
540  * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
541  *                              receieved packets.
542  *
543  * If the output side of a server process becomes choked, this allows flow
544  * control for the input side.
545  *
546  * @wsi:        Websocket connection instance to get callback for
547  * @enable:     0 = disable read servicing for this connection, 1 = enable
548  */
549
550 int
551 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
552 {
553         struct libwebsocket_context *this = wsi->protocol->owning_server;
554         int n;
555
556         for (n = this->count_protocols + 1; n < this->fds_count; n++)
557                 if (this->wsi[n] == wsi) {
558                         if (enable)
559                                 this->fds[n].events |= POLLIN;
560                         else
561                                 this->fds[n].events &= ~POLLIN;
562
563                         return 0;
564                 }
565
566         fprintf(stderr, "libwebsocket_callback_on_writable "
567                                                      "unable to find socket\n");
568         return 1;
569 }
570
571 /**
572  * libwebsocket_canonical_hostname() - returns this host's hostname
573  *
574  * This is typically used by client code to fill in the host parameter
575  * when making a client connection.  You can only call it after the context
576  * has been created.
577  *
578  * @this:       Websocket context
579  */
580
581
582 extern const char *
583 libwebsocket_canonical_hostname(struct libwebsocket_context *this)
584 {
585         return (const char *)this->canonical_hostname;
586 }
587
588
589 static void sigpipe_handler(int x)
590 {
591 }
592
593
594 /**
595  * libwebsocket_create_context() - Create the websocket handler
596  * @port:       Port to listen on... you can use 0 to suppress listening on
597  *              any port, that's what you want if you are not running a
598  *              websocket server at all but just using it as a client
599  * @protocols:  Array of structures listing supported protocols and a protocol-
600  *              specific callback for each one.  The list is ended with an
601  *              entry that has a NULL callback pointer.
602  *              It's not const because we write the owning_server member
603  * @ssl_cert_filepath:  If libwebsockets was compiled to use ssl, and you want
604  *                      to listen using SSL, set to the filepath to fetch the
605  *                      server cert from, otherwise NULL for unencrypted
606  * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
607  *                      else ignored
608  * @gid:        group id to change to after setting listen socket, or -1.
609  * @uid:        user id to change to after setting listen socket, or -1.
610  *
611  *      This function creates the listening socket and takes care
612  *      of all initialization in one step.
613  *
614  *      After initialization, it returns a struct libwebsocket_context * that
615  *      represents this server.  After calling, user code needs to take care
616  *      of calling libwebsocket_service() with the context pointer to get the
617  *      server's sockets serviced.  This can be done in the same process context
618  *      or a forked process, or another thread,
619  *
620  *      The protocol callback functions are called for a handful of events
621  *      including http requests coming in, websocket connections becoming
622  *      established, and data arriving; it's also called periodically to allow
623  *      async transmission.
624  *
625  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
626  *      at that time websocket protocol has not been negotiated.  Other
627  *      protocols after the first one never see any HTTP callack activity.
628  *
629  *      The server created is a simple http server by default; part of the
630  *      websocket standard is upgrading this http connection to a websocket one.
631  *
632  *      This allows the same server to provide files like scripts and favicon /
633  *      images or whatever over http and dynamic data over websockets all in
634  *      one place; they're all handled in the user callback.
635  */
636
637 struct libwebsocket_context *
638 libwebsocket_create_context(int port,
639                                struct libwebsocket_protocols *protocols,
640                                const char *ssl_cert_filepath,
641                                const char *ssl_private_key_filepath,
642                                int gid, int uid, unsigned int options)
643 {
644         int n;
645         int sockfd = 0;
646         int fd;
647         struct sockaddr_in serv_addr, cli_addr;
648         int opt = 1;
649         struct libwebsocket_context *this = NULL;
650         unsigned int slen;
651         char *p;
652         char hostname[1024];
653         struct hostent *he;
654
655 #ifdef LWS_OPENSSL_SUPPORT
656         SSL_METHOD *method;
657         char ssl_err_buf[512];
658 #endif
659
660         this = malloc(sizeof(struct libwebsocket_context));
661         if (!this) {
662                 fprintf(stderr, "No memory for websocket context\n");
663                 return NULL;
664         }
665         this->protocols = protocols;
666         this->listen_port = port;
667         this->http_proxy_port = 0;
668         this->http_proxy_address[0] = '\0';
669         this->options = options;
670
671         /* find canonical hostname */
672
673         hostname[(sizeof hostname) - 1] = '\0';
674         gethostname(hostname, (sizeof hostname) - 1);
675         he = gethostbyname(hostname);
676         strncpy(this->canonical_hostname, he->h_name,
677                                            sizeof this->canonical_hostname - 1);
678         this->canonical_hostname[sizeof this->canonical_hostname - 1] = '\0';
679         fprintf(stderr, "  canonical hostname = '%s'\n",
680                                         this->canonical_hostname);
681
682         /* split the proxy ads:port if given */
683
684         p = getenv("http_proxy");
685         if (p) {
686                 strncpy(this->http_proxy_address, p,
687                                            sizeof this->http_proxy_address - 1);
688                 this->http_proxy_address[
689                                     sizeof this->http_proxy_address - 1] = '\0';
690
691                 p = strchr(this->http_proxy_address, ':');
692                 if (p == NULL) {
693                         fprintf(stderr, "http_proxy needs to be ads:port\n");
694                         return NULL;
695                 }
696                 *p = '\0';
697                 this->http_proxy_port = atoi(p + 1);
698
699                 fprintf(stderr, "Using proxy %s:%u\n",
700                                 this->http_proxy_address,
701                                                         this->http_proxy_port);
702         }
703
704         if (port) {
705
706 #ifdef LWS_OPENSSL_SUPPORT
707                 this->use_ssl = ssl_cert_filepath != NULL &&
708                                                ssl_private_key_filepath != NULL;
709                 if (this->use_ssl)
710                         fprintf(stderr, " Compiled with SSL support, "
711                                                                   "using it\n");
712                 else
713                         fprintf(stderr, " Compiled with SSL support, "
714                                                               "not using it\n");
715
716 #else
717                 if (ssl_cert_filepath != NULL &&
718                                              ssl_private_key_filepath != NULL) {
719                         fprintf(stderr, " Not compiled for OpenSSl support!\n");
720                         return NULL;
721                 }
722                 fprintf(stderr, " Compiled without SSL support, "
723                                                        "serving unencrypted\n");
724 #endif
725         }
726
727         /* ignore SIGPIPE */
728
729         signal(SIGPIPE, sigpipe_handler);
730
731
732 #ifdef LWS_OPENSSL_SUPPORT
733
734         /* basic openssl init */
735
736         SSL_library_init();
737
738         OpenSSL_add_all_algorithms();
739         SSL_load_error_strings();
740
741         /*
742          * Firefox insists on SSLv23 not SSLv3
743          * Konq disables SSLv2 by default now, SSLv23 works
744          */
745
746         method = (SSL_METHOD *)SSLv23_server_method();
747         if (!method) {
748                 fprintf(stderr, "problem creating ssl method: %s\n",
749                         ERR_error_string(ERR_get_error(), ssl_err_buf));
750                 return NULL;
751         }
752         this->ssl_ctx = SSL_CTX_new(method);    /* create context */
753         if (!this->ssl_ctx) {
754                 fprintf(stderr, "problem creating ssl context: %s\n",
755                         ERR_error_string(ERR_get_error(), ssl_err_buf));
756                 return NULL;
757         }
758
759         /* client context */
760
761         method = (SSL_METHOD *)SSLv23_client_method();
762         if (!method) {
763                 fprintf(stderr, "problem creating ssl method: %s\n",
764                         ERR_error_string(ERR_get_error(), ssl_err_buf));
765                 return NULL;
766         }
767         this->ssl_client_ctx = SSL_CTX_new(method);     /* create context */
768         if (!this->ssl_client_ctx) {
769                 fprintf(stderr, "problem creating ssl context: %s\n",
770                         ERR_error_string(ERR_get_error(), ssl_err_buf));
771                 return NULL;
772         }
773
774
775         /* openssl init for cert verification (used with client sockets) */
776
777         if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
778                                                     LWS_OPENSSL_CLIENT_CERTS)) {
779                 fprintf(stderr, "Unable to load SSL Client certs from %s "
780                         "(set by --with-client-cert-dir= in configure) -- "
781                         " client ssl isn't going to work",
782                                                       LWS_OPENSSL_CLIENT_CERTS);
783         }
784
785         if (this->use_ssl) {
786
787                 /* openssl init for server sockets */
788
789                 /* set the local certificate from CertFile */
790                 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
791                                         ssl_cert_filepath, SSL_FILETYPE_PEM);
792                 if (n != 1) {
793                         fprintf(stderr, "problem getting cert '%s': %s\n",
794                                 ssl_cert_filepath,
795                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
796                         return NULL;
797                 }
798                 /* set the private key from KeyFile */
799                 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
800                                                 ssl_private_key_filepath,
801                                                        SSL_FILETYPE_PEM) != 1) {
802                         fprintf(stderr, "ssl problem getting key '%s': %s\n",
803                                                 ssl_private_key_filepath,
804                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
805                         return NULL;
806                 }
807                 /* verify private key */
808                 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
809                         fprintf(stderr, "Private SSL key doesn't match cert\n");
810                         return NULL;
811                 }
812
813                 /* SSL is happy and has a cert it's content with */
814         }
815 #endif
816
817         /* selftest */
818
819         if (lws_b64_selftest())
820                 return NULL;
821
822         /* set up our external listening socket we serve on */
823
824         if (port) {
825
826                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
827                 if (sockfd < 0) {
828                         fprintf(stderr, "ERROR opening socket");
829                         return NULL;
830                 }
831
832                 /* allow us to restart even if old sockets in TIME_WAIT */
833                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
834
835                 bzero((char *) &serv_addr, sizeof(serv_addr));
836                 serv_addr.sin_family = AF_INET;
837                 serv_addr.sin_addr.s_addr = INADDR_ANY;
838                 serv_addr.sin_port = htons(port);
839
840                 n = bind(sockfd, (struct sockaddr *) &serv_addr,
841                                                              sizeof(serv_addr));
842                 if (n < 0) {
843                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
844                                                                 port, n, errno);
845                         return NULL;
846                 }
847         }
848
849         /* drop any root privs for this process */
850
851         if (gid != -1)
852                 if (setgid(gid))
853                         fprintf(stderr, "setgid: %s\n", strerror(errno));
854         if (uid != -1)
855                 if (setuid(uid))
856                         fprintf(stderr, "setuid: %s\n", strerror(errno));
857
858         /*
859          * prepare the poll() fd array... it's like this
860          *
861          * [0] = external listening socket
862          * [1 .. this->count_protocols] = per-protocol broadcast sockets
863          * [this->count_protocols + 1 ... this->fds_count-1] = connection skts
864          */
865
866         this->fds_count = 1;
867         this->fds[0].fd = sockfd;
868         this->fds[0].events = POLLIN;
869         this->count_protocols = 0;
870
871         if (port) {
872                 listen(sockfd, 5);
873                 fprintf(stderr, " Listening on port %d\n", port);
874         }
875
876         /* set up our internal broadcast trigger sockets per-protocol */
877
878         for (; protocols[this->count_protocols].callback;
879                                                       this->count_protocols++) {
880                 protocols[this->count_protocols].owning_server = this;
881                 protocols[this->count_protocols].protocol_index =
882                                                           this->count_protocols;
883
884                 fd = socket(AF_INET, SOCK_STREAM, 0);
885                 if (fd < 0) {
886                         fprintf(stderr, "ERROR opening socket");
887                         return NULL;
888                 }
889
890                 /* allow us to restart even if old sockets in TIME_WAIT */
891                 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
892
893                 bzero((char *) &serv_addr, sizeof(serv_addr));
894                 serv_addr.sin_family = AF_INET;
895                 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
896                 serv_addr.sin_port = 0; /* pick the port for us */
897
898                 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
899                 if (n < 0) {
900                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
901                                                                 port, n, errno);
902                         return NULL;
903                 }
904
905                 slen = sizeof cli_addr;
906                 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
907                 if (n < 0) {
908                         fprintf(stderr, "getsockname failed\n");
909                         return NULL;
910                 }
911                 protocols[this->count_protocols].broadcast_socket_port =
912                                                        ntohs(cli_addr.sin_port);
913                 listen(fd, 5);
914
915                 debug("  Protocol %s broadcast socket %d\n",
916                                 protocols[this->count_protocols].name,
917                                                       ntohs(cli_addr.sin_port));
918
919                 this->fds[this->fds_count].fd = fd;
920                 this->fds[this->fds_count].events = POLLIN;
921                 /* wsi only exists for connections, not broadcast listener */
922                 this->wsi[this->fds_count] = NULL;
923                 this->fds_count++;
924         }
925
926         return this;
927 }
928
929
930 #ifndef LWS_NO_FORK
931
932 /**
933  * libwebsockets_fork_service_loop() - Optional helper function forks off
934  *                                a process for the websocket server loop.
935  *                              You don't have to use this but if not, you
936  *                              have to make sure you are calling
937  *                              libwebsocket_service periodically to service
938  *                              the websocket traffic
939  * @this:       server context returned by creation function
940  */
941
942 int
943 libwebsockets_fork_service_loop(struct libwebsocket_context *this)
944 {
945         int client;
946         int fd;
947         struct sockaddr_in cli_addr;
948         int n;
949
950         n = fork();
951         if (n < 0)
952                 return n;
953
954         if (!n) {
955
956                 /* main process context */
957
958                 for (client = 1; client < this->count_protocols + 1; client++) {
959                         fd = socket(AF_INET, SOCK_STREAM, 0);
960                         if (fd < 0) {
961                                 fprintf(stderr, "Unable to create socket\n");
962                                 return -1;
963                         }
964                         cli_addr.sin_family = AF_INET;
965                         cli_addr.sin_port = htons(
966                              this->protocols[client - 1].broadcast_socket_port);
967                         cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
968                         n = connect(fd, (struct sockaddr *)&cli_addr,
969                                                                sizeof cli_addr);
970                         if (n < 0) {
971                                 fprintf(stderr, "Unable to connect to "
972                                                 "broadcast socket %d, %s\n",
973                                                 client, strerror(errno));
974                                 return -1;
975                         }
976
977                         this->protocols[client - 1].broadcast_socket_user_fd =
978                                                                              fd;
979                 }
980
981
982                 return 0;
983         }
984
985         /* we want a SIGHUP when our parent goes down */
986         prctl(PR_SET_PDEATHSIG, SIGHUP);
987
988         /* in this forked process, sit and service websocket connections */
989
990         while (1)
991                 if (libwebsocket_service(this, 1000))
992                         return -1;
993
994         return 0;
995 }
996
997 #endif
998
999 /**
1000  * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
1001  *                                connection.
1002  * @wsi:        pointer to struct websocket you want to know the protocol of
1003  *
1004  *
1005  *      This is useful to get the protocol to broadcast back to from inside
1006  * the callback.
1007  */
1008
1009 const struct libwebsocket_protocols *
1010 libwebsockets_get_protocol(struct libwebsocket *wsi)
1011 {
1012         return wsi->protocol;
1013 }
1014
1015 /**
1016  * libwebsockets_broadcast() - Sends a buffer to the callback for all active
1017  *                                connections of the given protocol.
1018  * @protocol:   pointer to the protocol you will broadcast to all members of
1019  * @buf:  buffer containing the data to be broadcase.  NOTE: this has to be
1020  *              allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
1021  *              the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
1022  *              case you are calling this function from callback context.
1023  * @len:        length of payload data in buf, starting from buf.
1024  *
1025  *      This function allows bulk sending of a packet to every connection using
1026  * the given protocol.  It does not send the data directly; instead it calls
1027  * the callback with a reason type of LWS_CALLBACK_BROADCAST.  If the callback
1028  * wants to actually send the data for that connection, the callback itself
1029  * should call libwebsocket_write().
1030  *
1031  * libwebsockets_broadcast() can be called from another fork context without
1032  * having to take any care about data visibility between the processes, it'll
1033  * "just work".
1034  */
1035
1036
1037 int
1038 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
1039                                                  unsigned char *buf, size_t len)
1040 {
1041         struct libwebsocket_context *this = protocol->owning_server;
1042         int n;
1043
1044         if (!protocol->broadcast_socket_user_fd) {
1045                 /*
1046                  * We are either running unforked / flat, or we are being
1047                  * called from poll thread context
1048                  * eg, from a callback.  In that case don't use sockets for
1049                  * broadcast IPC (since we can't open a socket connection to
1050                  * a socket listening on our own thread) but directly do the
1051                  * send action.
1052                  *
1053                  * Locking is not needed because we are by definition being
1054                  * called in the poll thread context and are serialized.
1055                  */
1056
1057                 for (n = this->count_protocols + 1; n < this->fds_count; n++) {
1058
1059                         if ((unsigned long)this->wsi[n] < LWS_MAX_PROTOCOLS)
1060                                 continue;
1061
1062                         /* never broadcast to non-established connection */
1063                         if (this->wsi[n]->state != WSI_STATE_ESTABLISHED)
1064                                 continue;
1065
1066                         /* only broadcast to guys using requested protocol */
1067                         if (this->wsi[n]->protocol != protocol)
1068                                 continue;
1069
1070                         this->wsi[n]->protocol->callback(this->wsi[n],
1071                                          LWS_CALLBACK_BROADCAST,
1072                                          this->wsi[n]->user_space,
1073                                          buf, len);
1074                 }
1075
1076                 return 0;
1077         }
1078
1079         /*
1080          * We're being called from a different process context than the server
1081          * loop.  Instead of broadcasting directly, we send our
1082          * payload on a socket to do the IPC; the server process will serialize
1083          * the broadcast action in its main poll() loop.
1084          *
1085          * There's one broadcast socket listening for each protocol supported
1086          * set up when the websocket server initializes
1087          */
1088
1089         n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
1090
1091         return n;
1092 }