bfc56153612ebe0efbab2e5ca1106c79eef07cb5
[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 #ifdef LWS_OPENSSL_SUPPORT
25 SSL_CTX *ssl_ctx;
26 int use_ssl;
27 #endif
28
29
30 extern int 
31 libwebsocket_read(struct libwebsocket *wsi, unsigned char * buf, size_t len);
32
33
34 /* document the generic callback (it's a fake prototype under this) */
35 /**
36  * callback() - User server actions
37  * @wsi:        Opaque websocket instance pointer
38  * @reason:     The reason for the call
39  * @user:       Pointer to per-session user data allocated by library
40  * @in:         Pointer used for some callback reasons
41  * @len:        Length set for some callback reasons
42  * 
43  *      This callback is the way the user controls what is served.  All the
44  *      protocol detail is hidden and handled by the library.
45  * 
46  *      For each connection / session there is user data allocated that is
47  *      pointed to by "user".  You set the size of this user data area when
48  *      the library is initialized with libwebsocket_create_server.
49  * 
50  *      You get an opportunity to initialize user data when called back with
51  *      LWS_CALLBACK_ESTABLISHED reason.
52  * 
53  *      LWS_CALLBACK_ESTABLISHED:  after successful websocket handshake
54  * 
55  *      LWS_CALLBACK_CLOSED: when the websocket session ends
56  *
57  *      LWS_CALLBACK_BROADCAST: signal to send to client (you would use
58  *                              libwebsocket_write() taking care about the
59  *                              special buffer requirements
60  *      LWS_CALLBACK_RECEIVE: data has appeared for the server, it can be
61  *                              found at *in and is len bytes long
62  *
63  *      LWS_CALLBACK_HTTP: an http request has come from a client that is not
64  *                              asking to upgrade the connection to a websocket
65  *                              one.  This is a chance to serve http content,
66  *                              for example, to send a script to the client
67  *                              which will then open the websockets connection.
68  *                              @in points to the URI path requested and 
69  *                              libwebsockets_serve_http_file() makes it very
70  *                              simple to send back a file to the client.
71  */
72 extern int callback(struct libwebsocket * wsi,
73                          enum libwebsocket_callback_reasons reason, void * user,
74                                                           void *in, size_t len);
75
76
77 void 
78 libwebsocket_close_and_free_session(struct libwebsocket *wsi)
79 {
80         int n;
81
82         if ((unsigned long)wsi < LWS_MAX_PROTOCOLS)
83                 return;
84
85         n = wsi->state;
86
87         wsi->state = WSI_STATE_DEAD_SOCKET;
88
89         if (wsi->protocol->callback && n == WSI_STATE_ESTABLISHED)
90                 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
91                                                       wsi->user_space, NULL, 0);
92
93         for (n = 0; n < WSI_TOKEN_COUNT; n++)
94                 if (wsi->utf8_token[n].token)
95                         free(wsi->utf8_token[n].token);
96
97 //      fprintf(stderr, "closing fd=%d\n", wsi->sock);
98
99 #ifdef LWS_OPENSSL_SUPPORT
100         if (use_ssl) {
101                 n = SSL_get_fd(wsi->ssl);
102                 SSL_shutdown(wsi->ssl);
103                 close(n);
104                 SSL_free(wsi->ssl);
105         } else {
106 #endif
107                 shutdown(wsi->sock, SHUT_RDWR);
108                 close(wsi->sock);
109 #ifdef LWS_OPENSSL_SUPPORT
110         }
111 #endif
112         if (wsi->user_space)
113                 free(wsi->user_space);
114
115         free(wsi);
116 }
117
118 static int
119 libwebsocket_poll_connections(struct libwebsocket_context *this)
120 {
121         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
122                                                   LWS_SEND_BUFFER_POST_PADDING];
123         int client;
124         int n;
125         size_t len;
126
127         /* check for activity on client sockets */
128         
129         for (client = this->count_protocols + 1; client < this->fds_count;
130                                                                      client++) {
131                 
132                 /* handle session socket closed */
133                 
134                 if (this->fds[client].revents & (POLLERR | POLLHUP)) {
135                         
136                         debug("Session Socket %d %p (fd=%d) dead\n",
137                                   client, this->wsi[client], this->fds[client]);
138
139                         libwebsocket_close_and_free_session(this->wsi[client]);
140                         goto nuke_this;
141                 }
142                 
143                 /* any incoming data ready? */
144
145                 if (!(this->fds[client].revents & POLLIN))
146                         continue;
147
148                 /* broadcast? */
149
150                 if ((unsigned long)this->wsi[client] < LWS_MAX_PROTOCOLS) {
151
152                         len = read(this->fds[client].fd,
153                                    buf + LWS_SEND_BUFFER_PRE_PADDING,
154                                    MAX_BROADCAST_PAYLOAD);
155                         if (len < 0) {
156                                 fprintf(stderr, "Error receiving broadcast payload\n");
157                                 continue;
158                         }
159
160                         /* broadcast it to all guys with this protocol index */
161
162                         for (n = this->count_protocols + 1;
163                                                      n < this->fds_count; n++) {
164
165                                 if ((unsigned long)this->wsi[n] <
166                                                               LWS_MAX_PROTOCOLS)
167                                         continue;
168
169                                 /*
170                                  * never broadcast to non-established
171                                  * connection
172                                  */
173
174                                 if (this->wsi[n]->state != WSI_STATE_ESTABLISHED)
175                                         continue;
176
177                                 /*
178                                  * only broadcast to connections using
179                                  * the requested protocol
180                                  */
181
182                                 if (this->wsi[n]->protocol->protocol_index !=
183                                                (unsigned long)this->wsi[client])
184                                         continue;
185
186                                 this->wsi[n]->protocol-> callback(this->wsi[n],
187                                                  LWS_CALLBACK_BROADCAST, 
188                                                  this->wsi[n]->user_space,
189                                                  buf + LWS_SEND_BUFFER_PRE_PADDING, len);
190                         }
191
192                         continue;
193                 }
194
195 #ifdef LWS_OPENSSL_SUPPORT
196                 if (this->use_ssl)
197                         n = SSL_read(this->wsi[client]->ssl, buf, sizeof buf);
198                 else
199 #endif
200                         n = recv(this->fds[client].fd, buf, sizeof buf, 0);
201
202                 if (n < 0) {
203                         fprintf(stderr, "Socket read returned %d\n", n);
204                         continue;
205                 }
206                 if (!n) {
207 //                      fprintf(stderr, "POLLIN with 0 len waiting\n");
208                                 libwebsocket_close_and_free_session(
209                                                              this->wsi[client]);
210                         goto nuke_this;
211                 }
212
213
214                 /* service incoming data */
215
216                 if (libwebsocket_read(this->wsi[client], buf, n) >= 0)
217                         continue;
218                 
219                 /*
220                  * it closed and nuked wsi[client], so remove the
221                  * socket handle and wsi from our service list
222                  */
223 nuke_this:
224
225                 debug("nuking wsi %p, fsd_count = %d\n",
226                                         this->wsi[client], this->fds_count - 1);
227
228                 this->fds_count--;
229                 for (n = client; n < this->fds_count; n++) {
230                         this->fds[n] = this->fds[n + 1];
231                         this->wsi[n] = this->wsi[n + 1];
232                 }
233                 break;
234         }
235
236         return 0;
237 }
238
239
240
241 /**
242  * libwebsocket_create_server() - Create the listening websockets server
243  * @port:       Port to listen on
244  * @protocols:  Array of structures listing supported protocols and a protocol-
245  *              specific callback for each one.  The list is ended with an
246  *              entry that has a NULL callback pointer.
247  *              It's not const because we write the owning_server member
248  * @ssl_cert_filepath:  If libwebsockets was compiled to use ssl, and you want
249  *                      to listen using SSL, set to the filepath to fetch the
250  *                      server cert from, otherwise NULL for unencrypted
251  * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
252  *                      else ignored
253  * @gid:        group id to change to after setting listen socket, or -1.
254  * @uid:        user id to change to after setting listen socket, or -1.
255  * 
256  *      This function creates the listening socket and takes care
257  *      of all initialization in one step.
258  *
259  *      After initialization, it forks a thread that will sits in a service loop
260  *      and returns to the caller.  The actual service actions are performed by
261  *      user code in a per-protocol callback from the appropriate one selected
262  *      by the client from the list in @protocols.
263  * 
264  *      The protocol callback functions are called for a handful of events
265  *      including http requests coming in, websocket connections becoming
266  *      established, and data arriving; it's also called periodically to allow
267  *      async transmission.
268  *
269  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
270  *      at that time websocket protocol has not been negotiated.  Other
271  *      protocols after the first one never see any HTTP callack activity.
272  * 
273  *      The server created is a simple http server by default; part of the
274  *      websocket standard is upgrading this http connection to a websocket one.
275  * 
276  *      This allows the same server to provide files like scripts and favicon /
277  *      images or whatever over http and dynamic data over websockets all in
278  *      one place; they're all handled in the user callback.
279  */
280
281 int libwebsocket_create_server(int port,
282                                struct libwebsocket_protocols *protocols,
283                                const char * ssl_cert_filepath,
284                                const char * ssl_private_key_filepath,
285                                int gid, int uid)
286 {
287         int n;
288         int client;
289         int sockfd;
290         int fd;
291         unsigned int clilen;
292         struct sockaddr_in serv_addr, cli_addr;
293         int opt = 1;
294         struct libwebsocket_context * this = NULL;
295         unsigned int slen;
296
297 #ifdef LWS_OPENSSL_SUPPORT
298         SSL_METHOD *method;
299         char ssl_err_buf[512];
300
301         use_ssl = ssl_cert_filepath != NULL && ssl_private_key_filepath != NULL;
302         if (use_ssl)
303                 fprintf(stderr, " Compiled with SSL support, using it\n");
304         else
305                 fprintf(stderr, " Compiled with SSL support, not using it\n");
306
307 #else
308         if (ssl_cert_filepath != NULL && ssl_private_key_filepath != NULL) {
309                 fprintf(stderr, " Not compiled for OpenSSl support!\n");
310                 return -1;
311         }
312         fprintf(stderr, " Compiled without SSL support, serving unencrypted\n");
313 #endif
314
315 #ifdef LWS_OPENSSL_SUPPORT
316         if (use_ssl) {
317                 SSL_library_init();
318
319                 OpenSSL_add_all_algorithms();
320                 SSL_load_error_strings();
321
322                         // Firefox insists on SSLv23 not SSLv3
323                         // Konq disables SSLv2 by default now, SSLv23 works
324
325                 method = (SSL_METHOD *)SSLv23_server_method();
326                 if (!method) {
327                         fprintf(stderr, "problem creating ssl method: %s\n",
328                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
329                         return -1;
330                 }
331                 ssl_ctx = SSL_CTX_new(method);  /* create context */
332                 if (!ssl_ctx) {
333                         printf("problem creating ssl context: %s\n",
334                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
335                         return -1;
336                 }
337                 /* set the local certificate from CertFile */
338                 n = SSL_CTX_use_certificate_file(ssl_ctx,
339                                         ssl_cert_filepath, SSL_FILETYPE_PEM);
340                 if (n != 1) {
341                         fprintf(stderr, "problem getting cert '%s': %s\n",
342                                 ssl_cert_filepath,
343                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
344                         return -1;
345                 }
346                 /* set the private key from KeyFile */
347                 if (SSL_CTX_use_PrivateKey_file(ssl_ctx,
348                                                 ssl_private_key_filepath,
349                                                 SSL_FILETYPE_PEM) != 1) {
350                         fprintf(stderr, "ssl problem getting key '%s': %s\n",
351                                                 ssl_private_key_filepath,
352                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
353                         return (-1);
354                 }
355                 /* verify private key */
356                 if (!SSL_CTX_check_private_key(ssl_ctx)) {
357                         fprintf(stderr, "Private SSL key doesn't match cert\n");
358                         return (-1);
359                 }
360
361                 /* SSL is happy and has a cert it's content with */
362         }
363 #endif
364
365         this = malloc(sizeof (struct libwebsocket_context));
366
367         /* set up our external listening socket we serve on */
368   
369         sockfd = socket(AF_INET, SOCK_STREAM, 0);
370         if (sockfd < 0) {
371                 fprintf(stderr, "ERROR opening socket");
372                 return -1;
373         }
374         
375         /* allow us to restart even if old sockets in TIME_WAIT */
376         setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
377
378         bzero((char *) &serv_addr, sizeof(serv_addr));
379         serv_addr.sin_family = AF_INET;
380         serv_addr.sin_addr.s_addr = INADDR_ANY;
381         serv_addr.sin_port = htons(port);
382
383         n = bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
384         if (n < 0) {
385               fprintf(stderr, "ERROR on binding to port %d (%d %d)\n", port, n,
386                                                                          errno);
387               return -1;
388         }
389
390         /* drop any root privs for this process */
391
392         if (gid != -1)
393                 if (setgid(gid))
394                         fprintf(stderr, "setgid: %s\n", strerror(errno));
395         if (uid != -1)
396                 if (setuid(uid))
397                         fprintf(stderr, "setuid: %s\n", strerror(errno));
398
399         /*
400          * prepare the poll() fd array... it's like this
401          *
402          * [0] = external listening socket
403          * [1 .. this->count_protocols] = per-protocol broadcast sockets
404          * [this->count_protocols + 1 ... this->fds_count-1] = connection skts
405          */
406
407         this->fds_count = 1;
408         this->fds[0].fd = sockfd;
409         this->fds[0].events = POLLIN;
410         this->count_protocols = 0;
411 #ifdef LWS_OPENSSL_SUPPORT
412         this->use_ssl = use_ssl;
413 #endif
414
415         listen(sockfd, 5);
416         fprintf(stderr, " Listening on port %d\n", port);
417
418         /* set up our internal broadcast trigger sockets per-protocol */
419
420         for (; protocols[this->count_protocols].callback;
421                                                       this->count_protocols++) {
422                 protocols[this->count_protocols].owning_server = this;
423                 protocols[this->count_protocols].protocol_index =
424                                                           this->count_protocols;
425
426                 fd = socket(AF_INET, SOCK_STREAM, 0);
427                 if (fd < 0) {
428                         fprintf(stderr, "ERROR opening socket");
429                         return -1;
430                 }
431                 
432                 /* allow us to restart even if old sockets in TIME_WAIT */
433                 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
434
435                 bzero((char *) &serv_addr, sizeof(serv_addr));
436                 serv_addr.sin_family = AF_INET;
437                 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
438                 serv_addr.sin_port = 0; /* pick the port for us */
439
440                 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
441                 if (n < 0) {
442                       fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
443                                                                 port, n, errno);
444                       return -1;
445                 }
446
447                 slen = sizeof cli_addr;
448                 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
449                 if (n < 0) {
450                         fprintf(stderr, "getsockname failed\n");
451                         return -1;
452                 }
453                 protocols[this->count_protocols].broadcast_socket_port =
454                                                        ntohs(cli_addr.sin_port);
455                 listen(fd, 5);
456
457                 debug("  Protocol %s broadcast socket %d\n",
458                                 protocols[this->count_protocols].name,
459                                                       ntohs(cli_addr.sin_port));
460
461                 this->fds[this->fds_count].fd = fd;
462                 this->fds[this->fds_count].events = POLLIN;
463                 /* wsi only exists for connections, not broadcast listener */
464                 this->wsi[this->fds_count] = NULL;
465                 this->fds_count++;
466         }
467
468
469         /*
470          * We will enter out poll and service loop now, just before that
471          * fork and return to caller for the main thread of execution
472          */
473
474         n = fork();
475         if (n < 0) {
476                 fprintf(stderr, "Failed to fork websocket poll loop\n");
477                 return -1;
478         }
479         if (n) {
480                 /* original process context */
481
482                 /*
483                  * before we return to caller, we set up per-protocol
484                  * broadcast sockets connected to the server ready to use
485                  */
486
487                 /* give server fork a chance to start up */
488                 sleep(1);
489
490                 for (client = 1; client < this->count_protocols + 1; client++) {
491                         fd = socket(AF_INET, SOCK_STREAM, 0);
492                         if (fd < 0) {
493                                 fprintf(stderr,"Unable to create socket\n");
494                                 return -1;
495                         }
496                         cli_addr.sin_family = AF_INET;
497                         cli_addr.sin_port = htons(
498                                    protocols[client - 1].broadcast_socket_port);
499                         cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
500                         n = connect(fd, (struct sockaddr *)&cli_addr,
501                                                                sizeof cli_addr);
502                         if (n < 0) {
503                                 fprintf(stderr, "Unable to connect to "
504                                                 "broadcast socket %d, %s\n",
505                                                 client, strerror(errno));
506                                 return -1;
507                         }
508
509                         protocols[client - 1].broadcast_socket_user_fd = fd;
510                 }
511
512                 fprintf(stderr, "libwebsocket poll process forked\n");
513                 
514                 return 0;
515         }
516
517         /* we want a SIGHUP when our parent goes down */
518         prctl(PR_SET_PDEATHSIG, SIGHUP);
519
520         /* in this forked process, sit and service websocket connections */
521     
522         while (1) {
523
524                 n = poll(this->fds, this->fds_count, 1000);
525
526                 if (n < 0 || this->fds[0].revents & (POLLERR | POLLHUP)) {
527                         fprintf(stderr, "Listen Socket dead\n");
528                         goto fatal;
529                 }
530                 if (n == 0) /* poll timeout */
531                         continue;
532
533                 /* handle accept on listening socket? */
534
535                 for (client = 0; client < this->count_protocols + 1; client++) {
536
537                         if (!this->fds[client].revents & POLLIN)
538                                 continue;
539
540                         /* listen socket got an unencrypted connection... */
541
542                         clilen = sizeof(cli_addr);
543                         fd  = accept(this->fds[client].fd,
544                                      (struct sockaddr *)&cli_addr, &clilen);
545                         if (fd < 0) {
546                                 fprintf(stderr, "ERROR on accept");
547                                 continue;
548                         }
549
550                         if (this->fds_count >= MAX_CLIENTS) {
551                                 fprintf(stderr, "too busy");
552                                 close(fd);
553                                 continue;
554                         }
555
556                         if (client) {
557                                 /*
558                                  * accepting a connection to broadcast socket
559                                  * set wsi to be protocol index not pointer
560                                  */
561
562                                 this->wsi[this->fds_count] =
563                                       (struct libwebsocket *)(long)(client - 1);
564
565                                 goto fill_in_fds;
566                         }
567
568                         /* accepting connection to main listener */
569
570                         this->wsi[this->fds_count] =
571                                             malloc(sizeof(struct libwebsocket));
572                         if (!this->wsi[this->fds_count])
573                                 return -1;
574
575         #ifdef LWS_OPENSSL_SUPPORT
576                         if (this->use_ssl) {
577
578                                 this->wsi[this->fds_count]->ssl =
579                                                                SSL_new(ssl_ctx);
580                                 if (this->wsi[this->fds_count]->ssl == NULL) {
581                                         fprintf(stderr, "SSL_new failed: %s\n",
582                                             ERR_error_string(SSL_get_error(
583                                             this->wsi[this->fds_count]->ssl, 0),
584                                                                          NULL));
585                                         free(this->wsi[this->fds_count]);
586                                         continue;
587                                 }
588
589                                 SSL_set_fd(this->wsi[this->fds_count]->ssl, fd);
590
591                                 n = SSL_accept(this->wsi[this->fds_count]->ssl);
592                                 if (n != 1) {
593                                         /*
594                                          * browsers seem to probe with various
595                                          * ssl params which fail then retry
596                                          * and succeed
597                                          */
598                                         debug("SSL_accept failed skt %u: %s\n",
599                                               fd,
600                                               ERR_error_string(SSL_get_error(
601                                               this->wsi[this->fds_count]->ssl,
602                                                                      n), NULL));
603                                         SSL_free(
604                                                this->wsi[this->fds_count]->ssl);
605                                         free(this->wsi[this->fds_count]);
606                                         continue;
607                                 }
608                                 debug("accepted new SSL conn  "
609                                       "port %u on fd=%d SSL ver %s\n",
610                                         ntohs(cli_addr.sin_port), fd,
611                                           SSL_get_version(this->wsi[
612                                                         this->fds_count]->ssl));
613                                 
614                         } else
615         #endif
616                                 debug("accepted new conn  port %u on fd=%d\n",
617                                                   ntohs(cli_addr.sin_port), fd);
618                                 
619                         /* intialize the instance struct */
620
621                         this->wsi[this->fds_count]->sock = fd;
622                         this->wsi[this->fds_count]->state = WSI_STATE_HTTP;
623                         this->wsi[this->fds_count]->name_buffer_pos = 0;
624
625                         for (n = 0; n < WSI_TOKEN_COUNT; n++) {
626                                 this->wsi[this->fds_count]->
627                                                      utf8_token[n].token = NULL;
628                                 this->wsi[this->fds_count]->
629                                                     utf8_token[n].token_len = 0;
630                         }
631
632                         /*
633                          * these can only be set once the protocol is known
634                          * we set an unestablished connection's protocol pointer
635                          * to the start of the supported list, so it can look
636                          * for matching ones during the handshake
637                          */
638                         this->wsi[this->fds_count]->protocol = protocols;
639                         this->wsi[this->fds_count]->user_space = NULL;
640
641                         /*
642                          * Default protocol is 76
643                          * After 76, there's a header specified to inform which
644                          * draft the client wants, when that's seen we modify
645                          * the individual connection's spec revision accordingly
646                          */
647                         this->wsi[this->fds_count]->ietf_spec_revision = 76;
648
649 fill_in_fds:
650
651                         /*
652                          * make sure NO events are seen yet on this new socket
653                          * (otherwise we inherit old fds[client].revents from
654                          * previous socket there and die mysteriously! )
655                          */
656                         this->fds[this->fds_count].revents = 0;
657
658                         this->fds[this->fds_count].events = POLLIN;
659                         this->fds[this->fds_count++].fd = fd;
660
661                 }
662
663
664                 /* service anything incoming on websocket connection */
665
666                 libwebsocket_poll_connections(this);
667         }
668         
669 fatal:
670
671         /* close listening skt and per-protocol broadcast sockets */
672         for (client = 0; client < this->fds_count; client++)
673                 close(this->fds[0].fd);
674
675 #ifdef LWS_OPENSSL_SUPPORT
676         SSL_CTX_free(ssl_ctx);
677 #endif
678         kill(0, SIGTERM);
679
680         if (this)
681                 free(this);
682         
683         return 0;
684 }
685
686 /**
687  * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
688  *                                connection.
689  * @wsi:        pointer to struct websocket you want to know the protocol of
690  *
691  * 
692  *      This is useful to get the protocol to broadcast back to from inside
693  * the callback.
694  */
695
696 const struct libwebsocket_protocols *
697 libwebsockets_get_protocol(struct libwebsocket *wsi)
698 {
699         return wsi->protocol;
700 }
701
702 /**
703  * libwebsockets_broadcast() - Sends a buffer to rthe callback for all active
704  *                                connections of the given protocol.
705  * @protocol:   pointer to the protocol you will broadcast to all members of
706  * @buf:  buffer containing the data to be broadcase.  NOTE: this has to be
707  *              allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
708  *              the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
709  *              case you are calling this function from callback context.
710  * @len:        length of payload data in buf, starting from buf.
711  * 
712  *      This function allows bulk sending of a packet to every connection using
713  * the given protocol.  It does not send the data directly; instead it calls
714  * the callback with a reason type of LWS_CALLBACK_BROADCAST.  If the callback
715  * wants to actually send the data for that connection, the callback itself
716  * should call libwebsocket_write().
717  *
718  * libwebsockets_broadcast() can be called from another fork context without
719  * having to take any care about data visibility between the processes, it'll
720  * "just work".
721  */
722
723
724 int
725 libwebsockets_broadcast(const struct libwebsocket_protocols * protocol,
726                                                  unsigned char *buf, size_t len)
727 {
728         struct libwebsocket_context * this = protocol->owning_server;
729         int n;
730
731         if (!protocol->broadcast_socket_user_fd) {
732                 /*
733                  * we are being called from poll thread context
734                  * eg, from a callback.  In that case don't use sockets for
735                  * broadcast IPC (since we can't open a socket connection to
736                  * a socket listening on our own thread) but directly do the
737                  * send action.
738                  *
739                  * Locking is not needed because we are by definition being
740                  * called in the poll thread context and are serialized.
741                  */
742
743                 for (n = this->count_protocols + 1; n < this->fds_count; n++) {
744
745                         if ((unsigned long)this->wsi[n] < LWS_MAX_PROTOCOLS)
746                                 continue;
747
748                         /* never broadcast to non-established connection */
749
750                         if (this->wsi[n]->state != WSI_STATE_ESTABLISHED)
751                                 continue;
752
753                         /* only broadcast to guys using requested protocol */
754
755                         if (this->wsi[n]->protocol != protocol)
756                                 continue;
757
758                         this->wsi[n]->protocol-> callback(this->wsi[n],
759                                          LWS_CALLBACK_BROADCAST, 
760                                          this->wsi[n]->user_space,
761                                          buf, len);
762                 }
763
764                 return 0;
765         }
766
767         n = send(protocol->broadcast_socket_user_fd, buf, len, 0);
768
769         return n;
770 }