improve static allocation notice
[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 WIN32
25 #include <tchar.h>
26 #include <io.h>
27 #else
28 #ifdef LWS_BUILTIN_GETIFADDRS
29 #include <getifaddrs.h>
30 #else
31 #include <ifaddrs.h>
32 #endif
33 #include <syslog.h>
34 #include <sys/un.h>
35 #include <sys/socket.h>
36 #include <netdb.h>
37 #endif
38
39 #ifdef LWS_OPENSSL_SUPPORT
40 int openssl_websocket_private_data_index;
41 #endif
42
43 #ifdef __MINGW32__
44 #include "../win32port/win32helpers/websock-w32.c"
45 #else
46 #ifdef __MINGW64__
47 #include "../win32port/win32helpers/websock-w32.c"
48 #endif
49 #endif
50
51 #ifndef LWS_BUILD_HASH
52 #define LWS_BUILD_HASH "unknown-build-hash"
53 #endif
54
55 static int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
56 static void lwsl_emit_stderr(int level, const char *line);
57 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
58
59 static const char *library_version = LWS_LIBRARY_VERSION " " LWS_BUILD_HASH;
60
61 static const char *log_level_names[] = {
62         "ERR",
63         "WARN",
64         "NOTICE",
65         "INFO",
66         "DEBUG",
67         "PARSER",
68         "HEADER",
69         "EXTENSION",
70         "CLIENT",
71         "LATENCY",
72 };
73
74 /**
75  * lws_get_library_version: get version and git hash library built from
76  *
77  *      returns a const char * to a string like "1.1 178d78c"
78  *      representing the library version followed by the git head hash it
79  *      was built from
80  */
81
82 const char *
83 lws_get_library_version(void)
84 {
85         return library_version;
86 }
87
88 int
89 insert_wsi_socket_into_fds(struct libwebsocket_context *context, struct libwebsocket *wsi)
90 {
91         if (context->fds_count >= context->max_fds) {
92                 lwsl_err("Reached limit of fds tracking (%d)\n", context->max_fds);
93                 return 1;
94         }
95
96         if (wsi->sock > context->max_fds) {
97                 lwsl_err("Socket fd %d is beyond what we can index (%d)\n", wsi->sock, context->max_fds);
98                 return 1;
99         }
100
101         assert(wsi);
102         assert(wsi->sock);
103
104         lwsl_info("insert_wsi_socket_into_fds: wsi=%p, sock=%d, fds pos=%d\n", wsi, wsi->sock, context->fds_count);
105
106         context->lws_lookup[wsi->sock] = wsi;
107         wsi->position_in_fds_table = context->fds_count;
108         context->fds[context->fds_count].fd = wsi->sock;
109         context->fds[context->fds_count].events = POLLIN;
110         context->fds[context->fds_count++].revents = 0;
111
112         /* external POLL support via protocol 0 */
113         context->protocols[0].callback(context, wsi,
114                 LWS_CALLBACK_ADD_POLL_FD,
115                 (void *)(long)wsi->sock, NULL, POLLIN);
116
117         return 0;
118 }
119
120 static int
121 remove_wsi_socket_from_fds(struct libwebsocket_context *context, struct libwebsocket *wsi)
122 {
123         int m;
124
125         if (!--context->fds_count)
126                 goto do_ext;
127
128         if (wsi->sock > context->max_fds) {
129                 lwsl_err("Socket fd %d is beyond what we can index (%d)\n", wsi->sock, context->max_fds);
130                 return 1;
131         }
132
133         lwsl_info("remove_wsi_socket_from_fds: wsi=%p, sock=%d, fds pos=%d\n", wsi, wsi->sock, wsi->position_in_fds_table);
134
135         m = wsi->position_in_fds_table; /* replace the contents for this */
136
137         /* have the last guy take up the vacant slot */
138         context->fds[m] = context->fds[context->fds_count]; /* vacant fds slot filled with end one */
139         /* end guy's fds_lookup entry remains unchanged (still same fd pointing to same wsi) */
140         /* end guy's "position in fds table" changed */
141         context->lws_lookup[context->fds[context->fds_count].fd]->position_in_fds_table = m;
142         /* deletion guy's lws_lookup entry needs nuking */
143         context->lws_lookup[wsi->sock] = NULL; /* no WSI for the socket of the wsi being removed*/
144         wsi->position_in_fds_table = -1; /* removed wsi has no position any more */
145
146 do_ext:
147         /* remove also from external POLL support via protocol 0 */
148         if (wsi->sock)
149                 context->protocols[0].callback(context, wsi,
150                     LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
151
152         return 0;
153 }
154
155
156 void
157 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
158                          struct libwebsocket *wsi, enum lws_close_status reason)
159 {
160         int n;
161         int old_state;
162         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
163                                                   LWS_SEND_BUFFER_POST_PADDING];
164 #ifndef LWS_NO_EXTENSIONS
165         int ret;
166         int m;
167         struct lws_tokens eff_buf;
168         struct libwebsocket_extension *ext;
169 #endif
170
171         if (!wsi)
172                 return;
173
174         old_state = wsi->state;
175
176         if (old_state == WSI_STATE_DEAD_SOCKET)
177                 return;
178
179         wsi->u.ws.close_reason = reason;
180
181         if (wsi->mode == LWS_CONNMODE_HTTP_SERVING && wsi->u.http.fd) {
182                 close(wsi->u.http.fd);
183                 wsi->u.http.fd = 0;
184         }
185
186 #ifndef LWS_NO_EXTENSIONS
187         /*
188          * are his extensions okay with him closing?  Eg he might be a mux
189          * parent and just his ch1 aspect is closing?
190          */
191
192         for (n = 0; n < wsi->count_active_extensions; n++) {
193                 if (!wsi->active_extensions[n]->callback)
194                         continue;
195
196                 m = wsi->active_extensions[n]->callback(context,
197                         wsi->active_extensions[n], wsi,
198                         LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
199                                        wsi->active_extensions_user[n], NULL, 0);
200
201                 /*
202                  * if somebody vetoed actually closing him at this time....
203                  * up to the extension to track the attempted close, let's
204                  * just bail
205                  */
206
207                 if (m) {
208                         lwsl_ext("extension vetoed close\n");
209                         return;
210                 }
211         }
212
213         /*
214          * flush any tx pending from extensions, since we may send close packet
215          * if there are problems with send, just nuke the connection
216          */
217
218         ret = 1;
219         while (ret == 1) {
220
221                 /* default to nobody has more to spill */
222
223                 ret = 0;
224                 eff_buf.token = NULL;
225                 eff_buf.token_len = 0;
226
227                 /* show every extension the new incoming data */
228
229                 for (n = 0; n < wsi->count_active_extensions; n++) {
230                         m = wsi->active_extensions[n]->callback(
231                                         wsi->protocol->owning_server,
232                                         wsi->active_extensions[n], wsi,
233                                         LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
234                                    wsi->active_extensions_user[n], &eff_buf, 0);
235                         if (m < 0) {
236                                 lwsl_ext("Extension reports fatal error\n");
237                                 goto just_kill_connection;
238                         }
239                         if (m)
240                                 /*
241                                  * at least one extension told us he has more
242                                  * to spill, so we will go around again after
243                                  */
244                                 ret = 1;
245                 }
246
247                 /* assuming they left us something to send, send it */
248
249                 if (eff_buf.token_len)
250                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
251                                                              eff_buf.token_len)) {
252                                 lwsl_debug("close: sending final extension spill had problems\n");
253                                 goto just_kill_connection;
254                         }
255         }
256 #endif
257
258         /*
259          * signal we are closing, libsocket_write will
260          * add any necessary version-specific stuff.  If the write fails,
261          * no worries we are closing anyway.  If we didn't initiate this
262          * close, then our state has been changed to
263          * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
264          *
265          * Likewise if it's a second call to close this connection after we
266          * sent the close indication to the peer already, we are in state
267          * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
268          */
269
270         if (old_state == WSI_STATE_ESTABLISHED &&
271                                           reason != LWS_CLOSE_STATUS_NOSTATUS) {
272
273                 lwsl_debug("sending close indication...\n");
274
275                 n = libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING],
276                                                             0, LWS_WRITE_CLOSE);
277                 if (!n) {
278                         /*
279                          * we have sent a nice protocol level indication we
280                          * now wish to close, we should not send anything more
281                          */
282
283                         wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
284
285                         /* and we should wait for a reply for a bit out of politeness */
286
287                         libwebsocket_set_timeout(wsi,
288                                                   PENDING_TIMEOUT_CLOSE_ACK, 1);
289
290                         lwsl_debug("sent close indication, awaiting ack\n");
291
292                         return;
293                 }
294
295                 lwsl_info("close: sending the close packet failed, hanging up\n");
296
297                 /* else, the send failed and we should just hang up */
298         }
299
300 #ifndef LWS_NO_EXTENSIONS
301 just_kill_connection:
302 #endif
303
304         lwsl_debug("libwebsocket_close_and_free_session: just_kill_connection\n");
305
306         /*
307          * we won't be servicing or receiving anything further from this guy
308          * delete socket from the internal poll list if still present
309          */
310
311         remove_wsi_socket_from_fds(context, wsi);
312
313         wsi->state = WSI_STATE_DEAD_SOCKET;
314
315         if (old_state == WSI_STATE_ESTABLISHED && wsi->u.ws.rx_user_buffer) {
316                 free(wsi->u.ws.rx_user_buffer);
317                 wsi->u.ws.rx_user_buffer = NULL;
318         }
319
320         /* tell the user it's all over for this guy */
321
322         if (wsi->protocol && wsi->protocol->callback &&
323                         ((old_state == WSI_STATE_ESTABLISHED) ||
324                          (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
325                          (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
326                 lwsl_debug("calling back CLOSED\n");
327                 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
328                                                       wsi->user_space, NULL, 0);
329         } else
330                 lwsl_debug("not calling back closed, old_state=%d\n", old_state);
331
332 #ifndef LWS_NO_EXTENSIONS
333         /* deallocate any active extension contexts */
334
335         for (n = 0; n < wsi->count_active_extensions; n++) {
336                 if (!wsi->active_extensions[n]->callback)
337                         continue;
338
339                 wsi->active_extensions[n]->callback(context,
340                         wsi->active_extensions[n], wsi,
341                                 LWS_EXT_CALLBACK_DESTROY,
342                                        wsi->active_extensions_user[n], NULL, 0);
343
344                 free(wsi->active_extensions_user[n]);
345         }
346
347         /*
348          * inform all extensions in case they tracked this guy out of band
349          * even though not active on him specifically
350          */
351
352         ext = context->extensions;
353         while (ext && ext->callback) {
354                 ext->callback(context, ext, wsi,
355                                 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
356                                        NULL, NULL, 0);
357                 ext++;
358         }
359 #endif
360
361 #ifndef LWS_NO_CLIENT
362         if (wsi->c_address)
363                 free(wsi->c_address);
364 #endif
365         if (wsi->u.ws.rxflow_buffer)
366                 free(wsi->u.ws.rxflow_buffer);
367
368 /*      lwsl_info("closing fd=%d\n", wsi->sock); */
369
370 #ifdef LWS_OPENSSL_SUPPORT
371         if (wsi->ssl) {
372                 n = SSL_get_fd(wsi->ssl);
373                 SSL_shutdown(wsi->ssl);
374                 compatible_close(n);
375                 SSL_free(wsi->ssl);
376         } else {
377 #endif
378                 if (wsi->sock) {
379                         n = shutdown(wsi->sock, SHUT_RDWR);
380                         if (n)
381                                 lwsl_debug("closing: shutdown returned %d\n", errno);
382
383                         n = compatible_close(wsi->sock);
384                         if (n)
385                                 lwsl_debug("closing: close returned %d\n", errno);
386                 }
387 #ifdef LWS_OPENSSL_SUPPORT
388         }
389 #endif
390         if (wsi->protocol && wsi->protocol->per_session_data_size && wsi->user_space) /* user code may own */
391                 free(wsi->user_space);
392
393         free(wsi);
394 }
395
396 /**
397  * libwebsockets_hangup_on_client() - Server calls to terminate client
398  *                                      connection
399  * @context:    libwebsockets context
400  * @fd:         Connection socket descriptor
401  */
402
403 void
404 libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
405 {
406         struct libwebsocket *wsi = context->lws_lookup[fd];
407
408         if (wsi) {
409                 lwsl_info("closing connection at libwebsockets_hangup_on_client:\n");
410                 libwebsocket_close_and_free_session(context,
411                         wsi, LWS_CLOSE_STATUS_NOSTATUS);
412         } else
413                 close(fd);
414 }
415
416
417 /**
418  * libwebsockets_get_peer_addresses() - Get client address information
419  * @context:    Libwebsockets context
420  * @wsi:        Local struct libwebsocket associated with
421  * @fd:         Connection socket descriptor
422  * @name:       Buffer to take client address name
423  * @name_len:   Length of client address name buffer
424  * @rip:        Buffer to take client address IP qotted quad
425  * @rip_len:    Length of client address IP buffer
426  *
427  *      This function fills in @name and @rip with the name and IP of
428  *      the client connected with socket descriptor @fd.  Names may be
429  *      truncated if there is not enough room.  If either cannot be
430  *      determined, they will be returned as valid zero-length strings.
431  */
432
433 void
434 libwebsockets_get_peer_addresses(struct libwebsocket_context *context,
435         struct libwebsocket *wsi, int fd, char *name, int name_len,
436                                         char *rip, int rip_len)
437 {
438         unsigned int len;
439         struct sockaddr_in sin;
440         struct hostent *host;
441         struct hostent *host1;
442         char ip[128];
443         unsigned char *p;
444         int n;
445         int ret = -1;
446 #ifdef AF_LOCAL
447     struct sockaddr_un *un;
448 #endif
449
450         rip[0] = '\0';
451         name[0] = '\0';
452
453         lws_latency_pre(context, wsi);
454
455         len = sizeof sin;
456         if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
457                 perror("getpeername");
458                 goto bail;
459         }
460
461         host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
462                                                                        AF_INET);
463         if (host == NULL) {
464                 perror("gethostbyaddr");
465                 goto bail;
466         }
467
468         strncpy(name, host->h_name, name_len);
469         name[name_len - 1] = '\0';
470
471         host1 = gethostbyname(host->h_name);
472         if (host1 == NULL)
473                 goto bail;
474         p = (unsigned char *)host1;
475         n = 0;
476         while (p != NULL) {
477                 p = (unsigned char *)host1->h_addr_list[n++];
478                 if (p == NULL)
479                         continue;
480                 if ((host1->h_addrtype != AF_INET)
481 #ifdef AF_LOCAL
482                         && (host1->h_addrtype != AF_LOCAL)
483 #endif
484                         )
485                         continue;
486
487                 if (host1->h_addrtype == AF_INET)
488                         sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
489 #ifdef AF_LOCAL
490                 else {
491                         un = (struct sockaddr_un *)p;
492                         strncpy(ip, un->sun_path, sizeof(ip) - 1);
493                         ip[sizeof(ip) - 1] = '\0';
494                 }
495 #endif
496                 p = NULL;
497                 strncpy(rip, ip, rip_len);
498                 rip[rip_len - 1] = '\0';
499         }
500
501         ret = 0;
502 bail:
503         lws_latency(context, wsi, "libwebsockets_get_peer_addresses", ret, 1);
504 }
505
506 int libwebsockets_get_random(struct libwebsocket_context *context,
507                                                              void *buf, int len)
508 {
509         int n;
510         char *p = (char *)buf;
511
512 #ifdef WIN32
513         for (n = 0; n < len; n++)
514                 p[n] = (unsigned char)rand();
515 #else
516         n = read(context->fd_random, p, len);
517 #endif
518
519         return n;
520 }
521
522 int lws_set_socket_options(struct libwebsocket_context *context, int fd)
523 {
524         int optval = 1;
525         socklen_t optlen = sizeof(optval);
526 #ifdef WIN32
527         unsigned long optl = 0;
528 #endif
529 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
530         struct protoent *tcp_proto;
531 #endif
532
533         if (context->ka_time) {
534                 /* enable keepalive on this socket */
535                 optval = 1;
536                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
537                                              (const void *)&optval, optlen) < 0)
538                         return 1;
539
540 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
541
542                 /*
543                  * didn't find a way to set these per-socket, need to
544                  * tune kernel systemwide values
545                  */
546
547 #else
548                 /* set the keepalive conditions we want on it too */
549                 optval = context->ka_time;
550                 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPIDLE,
551                                              (const void *)&optval, optlen) < 0)
552                         return 1;
553
554                 optval = context->ka_probes;
555                 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPINTVL,
556                                              (const void *)&optval, optlen) < 0)
557                         return 1;
558
559                 optval = context->ka_interval;
560                 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPCNT,
561                                              (const void *)&optval, optlen) < 0)
562                         return 1;
563 #endif
564         }
565
566         /* Disable Nagle */
567         optval = 1;
568 #if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__)
569         setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen);
570 #else
571         tcp_proto = getprotobyname("TCP");
572         setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen);
573 #endif
574
575         /* We are nonblocking... */
576 #ifdef WIN32
577         ioctlsocket(fd, FIONBIO, &optl);
578 #else
579         fcntl(fd, F_SETFL, O_NONBLOCK);
580 #endif
581
582         return 0;
583 }
584
585 int lws_send_pipe_choked(struct libwebsocket *wsi)
586 {
587         struct pollfd fds;
588
589         fds.fd = wsi->sock;
590         fds.events = POLLOUT;
591         fds.revents = 0;
592
593         if (poll(&fds, 1, 0) != 1)
594                 return 1;
595
596         if ((fds.revents & POLLOUT) == 0)
597                 return 1;
598
599         /* okay to send another packet without blocking */
600
601         return 0;
602 }
603
604 int
605 lws_handle_POLLOUT_event(struct libwebsocket_context *context,
606                                 struct libwebsocket *wsi, struct pollfd *pollfd)
607 {
608         int n;
609
610 #ifndef LWS_NO_EXTENSIONS
611         struct lws_tokens eff_buf;
612         int ret;
613         int m;
614         int handled = 0;
615
616         for (n = 0; n < wsi->count_active_extensions; n++) {
617                 if (!wsi->active_extensions[n]->callback)
618                         continue;
619
620                 m = wsi->active_extensions[n]->callback(context,
621                         wsi->active_extensions[n], wsi,
622                         LWS_EXT_CALLBACK_IS_WRITEABLE,
623                                        wsi->active_extensions_user[n], NULL, 0);
624                 if (m > handled)
625                         handled = m;
626         }
627
628         if (handled == 1)
629                 goto notify_action;
630
631         if (!wsi->extension_data_pending || handled == 2)
632                 goto user_service;
633
634         /*
635          * check in on the active extensions, see if they
636          * had pending stuff to spill... they need to get the
637          * first look-in otherwise sequence will be disordered
638          *
639          * NULL, zero-length eff_buf means just spill pending
640          */
641
642         ret = 1;
643         while (ret == 1) {
644
645                 /* default to nobody has more to spill */
646
647                 ret = 0;
648                 eff_buf.token = NULL;
649                 eff_buf.token_len = 0;
650
651                 /* give every extension a chance to spill */
652
653                 for (n = 0; n < wsi->count_active_extensions; n++) {
654                         m = wsi->active_extensions[n]->callback(
655                                 wsi->protocol->owning_server,
656                                 wsi->active_extensions[n], wsi,
657                                         LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
658                                    wsi->active_extensions_user[n], &eff_buf, 0);
659                         if (m < 0) {
660                                 lwsl_err("ext reports fatal error\n");
661                                 return -1;
662                         }
663                         if (m)
664                                 /*
665                                  * at least one extension told us he has more
666                                  * to spill, so we will go around again after
667                                  */
668                                 ret = 1;
669                 }
670
671                 /* assuming they gave us something to send, send it */
672
673                 if (eff_buf.token_len) {
674                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
675                                                              eff_buf.token_len))
676                                 return -1;
677                 } else
678                         continue;
679
680                 /* no extension has more to spill */
681
682                 if (!ret)
683                         continue;
684
685                 /*
686                  * There's more to spill from an extension, but we just sent
687                  * something... did that leave the pipe choked?
688                  */
689
690                 if (!lws_send_pipe_choked(wsi))
691                         /* no we could add more */
692                         continue;
693
694                 lwsl_info("choked in POLLOUT service\n");
695
696                 /*
697                  * Yes, he's choked.  Leave the POLLOUT masked on so we will
698                  * come back here when he is unchoked.  Don't call the user
699                  * callback to enforce ordering of spilling, he'll get called
700                  * when we come back here and there's nothing more to spill.
701                  */
702
703                 return 0;
704         }
705
706         wsi->extension_data_pending = 0;
707
708 user_service:
709 #endif
710         /* one shot */
711
712         if (pollfd) {
713                 pollfd->events &= ~POLLOUT;
714
715                 /* external POLL support via protocol 0 */
716                 context->protocols[0].callback(context, wsi,
717                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
718                         (void *)(long)wsi->sock, NULL, POLLOUT);
719         }
720 #ifndef LWS_NO_EXTENSIONS
721 notify_action:
722 #endif
723
724         if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
725                 n = LWS_CALLBACK_CLIENT_WRITEABLE;
726         else
727                 n = LWS_CALLBACK_SERVER_WRITEABLE;
728
729         return user_callback_handle_rxflow(wsi->protocol->callback, context,
730                 wsi, (enum libwebsocket_callback_reasons) n, wsi->user_space, NULL, 0);
731 }
732
733
734
735 void
736 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
737                                      struct libwebsocket *wsi, unsigned int sec)
738 {
739 #ifndef LWS_NO_EXTENSIONS
740         int n;
741
742         /*
743          * if extensions want in on it (eg, we are a mux parent)
744          * give them a chance to service child timeouts
745          */
746
747         for (n = 0; n < wsi->count_active_extensions; n++)
748                 wsi->active_extensions[n]->callback(
749                                     context, wsi->active_extensions[n],
750                                     wsi, LWS_EXT_CALLBACK_1HZ,
751                                     wsi->active_extensions_user[n], NULL, sec);
752
753 #endif
754         if (!wsi->pending_timeout)
755                 return;
756
757         /*
758          * if we went beyond the allowed time, kill the
759          * connection
760          */
761
762         if (sec > wsi->pending_timeout_limit) {
763                 lwsl_info("TIMEDOUT WAITING\n");
764                 libwebsocket_close_and_free_session(context,
765                                 wsi, LWS_CLOSE_STATUS_NOSTATUS);
766         }
767 }
768
769 /**
770  * libwebsocket_service_fd() - Service polled socket with something waiting
771  * @context:    Websocket context
772  * @pollfd:     The pollfd entry describing the socket fd and which events
773  *              happened.
774  *
775  *      This function takes a pollfd that has POLLIN or POLLOUT activity and
776  *      services it according to the state of the associated struct libwebsocket.
777  *
778  *      The one call deals with all "service" that might happen on a socket
779  *      including listen accepts, http files as well as websocket protocol.
780  */
781
782 int
783 libwebsocket_service_fd(struct libwebsocket_context *context,
784                                                           struct pollfd *pollfd)
785 {
786         struct libwebsocket *wsi;
787         int n;
788         int m;
789         int listen_socket_fds_index = 0;
790         struct timeval tv;
791
792 #ifndef LWS_NO_EXTENSIONS
793         int more = 1;
794 #endif
795         struct lws_tokens eff_buf;
796 #ifndef LWS_NO_CLIENT
797         extern int lws_client_socket_service(struct libwebsocket_context *context, struct libwebsocket *wsi, struct pollfd *pollfd);
798 #endif
799 #ifndef LWS_NO_SERVER
800         extern int lws_server_socket_service(struct libwebsocket_context *context, struct libwebsocket *wsi, struct pollfd *pollfd);
801 #endif
802
803         if (context->listen_service_fd)
804                 listen_socket_fds_index = context->lws_lookup[
805                              context->listen_service_fd]->position_in_fds_table;
806
807         /*
808          * you can call us with pollfd = NULL to just allow the once-per-second
809          * global timeout checks; if less than a second since the last check
810          * it returns immediately then.
811          */
812
813         gettimeofday(&tv, NULL);
814
815         if (context->last_timeout_check_s != tv.tv_sec) {
816                 context->last_timeout_check_s = tv.tv_sec;
817
818                 #ifndef WIN32
819                 /* if our parent went down, don't linger around */
820                 if (context->started_with_parent && kill(context->started_with_parent, 0) < 0)
821                         kill(getpid(), SIGTERM);
822                 #endif
823
824                 /* global timeout check once per second */
825
826                 for (n = 0; n < context->fds_count; n++) {
827                         struct libwebsocket *new_wsi = context->lws_lookup[context->fds[n].fd];
828                         if (!new_wsi)
829                                 continue;
830                         libwebsocket_service_timeout_check(context,
831                                 new_wsi, tv.tv_sec);
832                 }
833         }
834
835         /* just here for timeout management? */
836
837         if (pollfd == NULL)
838                 return 0;
839
840         /* no, here to service a socket descriptor */
841
842         /*
843          * deal with listen service piggybacking
844          * every listen_service_modulo services of other fds, we
845          * sneak one in to service the listen socket if there's anything waiting
846          *
847          * To handle connection storms, as found in ab, if we previously saw a
848          * pending connection here, it causes us to check again next time.
849          */
850
851         if (context->listen_service_fd && pollfd != &context->fds[listen_socket_fds_index]) {
852                 context->listen_service_count++;
853                 if (context->listen_service_extraseen ||
854                                 context->listen_service_count == context->listen_service_modulo) {
855                         context->listen_service_count = 0;
856                         m = 1;
857                         if (context->listen_service_extraseen > 5)
858                                 m = 2;
859                         while (m--) {
860                                 /* even with extpoll, we prepared this internal fds for listen */
861                                 n = poll(&context->fds[listen_socket_fds_index], 1, 0);
862                                 if (n > 0) { /* there's a connection waiting for us */
863                                         libwebsocket_service_fd(context, &context->fds[listen_socket_fds_index]);
864                                         context->listen_service_extraseen++;
865                                 } else {
866                                         if (context->listen_service_extraseen)
867                                                 context->listen_service_extraseen--;
868                                         break;
869                                 }
870                         }
871                 }
872
873         }
874
875         /* okay, what we came here to do... */
876
877         wsi = context->lws_lookup[pollfd->fd];
878         if (wsi == NULL) {
879                 if (pollfd->fd > 11)
880                         lwsl_err("unexpected NULL wsi fd=%d fds_count=%d\n", pollfd->fd, context->fds_count);
881                 return 0;
882         }
883
884         switch (wsi->mode) {
885
886 #ifndef LWS_NO_SERVER
887         case LWS_CONNMODE_HTTP_SERVING:
888         case LWS_CONNMODE_SERVER_LISTENER:
889         case LWS_CONNMODE_SSL_ACK_PENDING:
890                 return lws_server_socket_service(context, wsi, pollfd);
891 #endif
892
893         case LWS_CONNMODE_WS_SERVING:
894         case LWS_CONNMODE_WS_CLIENT:
895
896                 /* handle session socket closed */
897
898                 if (pollfd->revents & (POLLERR | POLLHUP)) {
899
900                         lwsl_debug("Session Socket %p (fd=%d) dead\n",
901                                 (void *)wsi, pollfd->fd);
902
903                         libwebsocket_close_and_free_session(context, wsi,
904                                                      LWS_CLOSE_STATUS_NOSTATUS);
905                         return 0;
906                 }
907
908                 /* the guy requested a callback when it was OK to write */
909
910                 if ((pollfd->revents & POLLOUT) &&
911                                             wsi->state == WSI_STATE_ESTABLISHED)
912                         if (lws_handle_POLLOUT_event(context, wsi,
913                                                                   pollfd) < 0) {
914                                 libwebsocket_close_and_free_session(
915                                          context, wsi, LWS_CLOSE_STATUS_NORMAL);
916                                 return 0;
917                         }
918
919
920                 /* any incoming data ready? */
921
922                 if (!(pollfd->revents & POLLIN))
923                         break;
924
925 #ifdef LWS_OPENSSL_SUPPORT
926 read_pending:
927                 if (wsi->ssl) {
928                         eff_buf.token_len = SSL_read(wsi->ssl,
929                                         context->service_buffer,
930                                                 sizeof context->service_buffer);
931                         if (!eff_buf.token_len) {
932                                 n = SSL_get_error(wsi->ssl, eff_buf.token_len);
933                                 lwsl_err("SSL_read returned 0 with reason %s\n",
934                                   ERR_error_string(n, (char *)context->service_buffer));
935                         }
936                 } else
937 #endif
938                         eff_buf.token_len = recv(pollfd->fd,
939                                         context->service_buffer,
940                                              sizeof context->service_buffer, 0);
941
942                 if (eff_buf.token_len < 0) {
943                         lwsl_debug("Socket read returned %d\n",
944                                                             eff_buf.token_len);
945                         if (errno != EINTR && errno != EAGAIN)
946                                 libwebsocket_close_and_free_session(context,
947                                                wsi, LWS_CLOSE_STATUS_NOSTATUS);
948                         return 0;
949                 }
950                 if (!eff_buf.token_len) {
951                         lwsl_info("closing connection due to zero length read\n");
952                         libwebsocket_close_and_free_session(context, wsi,
953                                                     LWS_CLOSE_STATUS_NOSTATUS);
954                         return 0;
955                 }
956
957                 /*
958                  * give any active extensions a chance to munge the buffer
959                  * before parse.  We pass in a pointer to an lws_tokens struct
960                  * prepared with the default buffer and content length that's in
961                  * there.  Rather than rewrite the default buffer, extensions
962                  * that expect to grow the buffer can adapt .token to
963                  * point to their own per-connection buffer in the extension
964                  * user allocation.  By default with no extensions or no
965                  * extension callback handling, just the normal input buffer is
966                  * used then so it is efficient.
967                  */
968
969                 eff_buf.token = (char *)context->service_buffer;
970 #ifndef LWS_NO_EXTENSIONS
971                 more = 1;
972                 while (more) {
973
974                         more = 0;
975
976                         for (n = 0; n < wsi->count_active_extensions; n++) {
977                                 m = wsi->active_extensions[n]->callback(context,
978                                         wsi->active_extensions[n], wsi,
979                                         LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
980                                         wsi->active_extensions_user[n],
981                                                                    &eff_buf, 0);
982                                 if (m < 0) {
983                                         lwsl_ext(
984                                             "Extension reports fatal error\n");
985                                         libwebsocket_close_and_free_session(
986                                                 context, wsi,
987                                                     LWS_CLOSE_STATUS_NOSTATUS);
988                                         return 0;
989                                 }
990                                 if (m)
991                                         more = 1;
992                         }
993 #endif
994                         /* service incoming data */
995
996                         if (eff_buf.token_len) {
997                                 n = libwebsocket_read(context, wsi,
998                                         (unsigned char *)eff_buf.token,
999                                                             eff_buf.token_len);
1000                                 if (n < 0)
1001                                         /* we closed wsi */
1002                                         return 0;
1003                         }
1004 #ifndef LWS_NO_EXTENSIONS
1005                         eff_buf.token = NULL;
1006                         eff_buf.token_len = 0;
1007                 }
1008 #endif
1009
1010 #ifdef LWS_OPENSSL_SUPPORT
1011                 if (wsi->ssl && SSL_pending(wsi->ssl))
1012                         goto read_pending;
1013 #endif
1014                 break;
1015
1016         default:
1017 #ifdef LWS_NO_CLIENT
1018                 break;
1019 #else
1020                 return  lws_client_socket_service(context, wsi, pollfd);
1021 #endif
1022         }
1023
1024         return 0;
1025 }
1026
1027
1028 /**
1029  * libwebsocket_context_destroy() - Destroy the websocket context
1030  * @context:    Websocket context
1031  *
1032  *      This function closes any active connections and then frees the
1033  *      context.  After calling this, any further use of the context is
1034  *      undefined.
1035  */
1036 void
1037 libwebsocket_context_destroy(struct libwebsocket_context *context)
1038 {
1039 #ifndef LWS_NO_EXTENSIONS
1040         int n;
1041         int m;
1042         struct libwebsocket_extension *ext;
1043
1044 #ifdef LWS_LATENCY
1045         if (context->worst_latency_info[0])
1046                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
1047 #endif
1048
1049         for (n = 0; n < context->fds_count; n++) {
1050                 struct libwebsocket *wsi = context->lws_lookup[context->fds[n].fd];
1051                 libwebsocket_close_and_free_session(context,
1052                         wsi, LWS_CLOSE_STATUS_GOINGAWAY);
1053         }
1054
1055         /*
1056          * give all extensions a chance to clean up any per-context
1057          * allocations they might have made
1058          */
1059
1060         ext = context->extensions;
1061         m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
1062         if (context->listen_port)
1063                 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
1064         while (ext && ext->callback) {
1065                 ext->callback(context, ext, NULL, (enum libwebsocket_extension_callback_reasons)m, NULL, NULL, 0);
1066                 ext++;
1067         }
1068 #endif
1069
1070 #ifdef WIN32
1071 #else
1072         close(context->fd_random);
1073 #endif
1074
1075 #ifdef LWS_OPENSSL_SUPPORT
1076         if (context->ssl_ctx)
1077                 SSL_CTX_free(context->ssl_ctx);
1078         if (context->ssl_client_ctx)
1079                 SSL_CTX_free(context->ssl_client_ctx);
1080 #endif
1081
1082         if (context->fds)
1083                 free(context->fds);
1084         if (context->lws_lookup)
1085                 free(context->lws_lookup);
1086
1087         free(context);
1088
1089 #ifdef WIN32
1090         WSACleanup();
1091 #endif
1092 }
1093
1094 /**
1095  * libwebsocket_context_user() - get the user data associated with the whole context
1096  * @context: Websocket context
1097  *
1098  *      This returns the optional user allocation that can be attached to
1099  *      the context the sockets live in at context_create time.  It's a way
1100  *      to let all sockets serviced in the same context share data without
1101  *      using globals statics in the user code.
1102  */
1103
1104
1105 LWS_EXTERN void *
1106 libwebsocket_context_user(struct libwebsocket_context *context)
1107 {
1108     return context->user_space;
1109 }
1110
1111 /**
1112  * libwebsocket_service() - Service any pending websocket activity
1113  * @context:    Websocket context
1114  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1115  *              service otherwise block and service immediately, returning
1116  *              after the timeout if nothing needed service.
1117  *
1118  *      This function deals with any pending websocket traffic, for three
1119  *      kinds of event.  It handles these events on both server and client
1120  *      types of connection the same.
1121  *
1122  *      1) Accept new connections to our context's server
1123  *
1124  *      2) Call the receive callback for incoming frame data received by
1125  *          server or client connections.
1126  *
1127  *      You need to call this service function periodically to all the above
1128  *      functions to happen; if your application is single-threaded you can
1129  *      just call it in your main event loop.
1130  *
1131  *      Alternatively you can fork a new process that asynchronously handles
1132  *      calling this service in a loop.  In that case you are happy if this
1133  *      call blocks your thread until it needs to take care of something and
1134  *      would call it with a large nonzero timeout.  Your loop then takes no
1135  *      CPU while there is nothing happening.
1136  *
1137  *      If you are calling it in a single-threaded app, you don't want it to
1138  *      wait around blocking other things in your loop from happening, so you
1139  *      would call it with a timeout_ms of 0, so it returns immediately if
1140  *      nothing is pending, or as soon as it services whatever was pending.
1141  */
1142
1143
1144 int
1145 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
1146 {
1147         int n;
1148
1149         /* stay dead once we are dead */
1150
1151         if (context == NULL)
1152                 return 1;
1153
1154         /* wait for something to need service */
1155
1156         n = poll(context->fds, context->fds_count, timeout_ms);
1157         if (n == 0) /* poll timeout */
1158                 return 0;
1159
1160         if (n < 0)
1161                 return -1;
1162
1163         /* any socket with events to service? */
1164
1165         for (n = 0; n < context->fds_count; n++)
1166                 if (context->fds[n].revents)
1167                         if (libwebsocket_service_fd(context,
1168                                                         &context->fds[n]) < 0)
1169                                 return -1;
1170         return 0;
1171 }
1172
1173 #ifndef LWS_NO_EXTENSIONS
1174 int
1175 lws_any_extension_handled(struct libwebsocket_context *context,
1176                           struct libwebsocket *wsi,
1177                           enum libwebsocket_extension_callback_reasons r,
1178                                                        void *v, size_t len)
1179 {
1180         int n;
1181         int handled = 0;
1182
1183         /* maybe an extension will take care of it for us */
1184
1185         for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
1186                 if (!wsi->active_extensions[n]->callback)
1187                         continue;
1188
1189                 handled |= wsi->active_extensions[n]->callback(context,
1190                         wsi->active_extensions[n], wsi,
1191                         r, wsi->active_extensions_user[n], v, len);
1192         }
1193
1194         return handled;
1195 }
1196
1197
1198 void *
1199 lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
1200                                            struct libwebsocket_extension *ext)
1201 {
1202         int n = 0;
1203
1204         if (wsi == NULL)
1205                 return NULL;
1206
1207         while (n < wsi->count_active_extensions) {
1208                 if (wsi->active_extensions[n] != ext) {
1209                         n++;
1210                         continue;
1211                 }
1212                 return wsi->active_extensions_user[n];
1213         }
1214
1215         return NULL;
1216 }
1217 #endif
1218
1219 /**
1220  * libwebsocket_callback_on_writable() - Request a callback when this socket
1221  *                                       becomes able to be written to without
1222  *                                       blocking
1223  *
1224  * @context:    libwebsockets context
1225  * @wsi:        Websocket connection instance to get callback for
1226  */
1227
1228 int
1229 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
1230                                                       struct libwebsocket *wsi)
1231 {
1232 #ifndef LWS_NO_EXTENSIONS
1233         int n;
1234         int handled = 0;
1235
1236         /* maybe an extension will take care of it for us */
1237
1238         for (n = 0; n < wsi->count_active_extensions; n++) {
1239                 if (!wsi->active_extensions[n]->callback)
1240                         continue;
1241
1242                 handled |= wsi->active_extensions[n]->callback(context,
1243                         wsi->active_extensions[n], wsi,
1244                         LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
1245                                        wsi->active_extensions_user[n], NULL, 0);
1246         }
1247
1248         if (handled)
1249                 return 1;
1250 #endif
1251         if (wsi->position_in_fds_table < 0) {
1252                 lwsl_err("libwebsocket_callback_on_writable: "
1253                                       "failed to find socket %d\n", wsi->sock);
1254                 return -1;
1255         }
1256
1257         context->fds[wsi->position_in_fds_table].events |= POLLOUT;
1258
1259         /* external POLL support via protocol 0 */
1260         context->protocols[0].callback(context, wsi,
1261                 LWS_CALLBACK_SET_MODE_POLL_FD,
1262                 (void *)(long)wsi->sock, NULL, POLLOUT);
1263
1264         return 1;
1265 }
1266
1267 /**
1268  * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1269  *                      all connections using the given protocol when it
1270  *                      becomes possible to write to each socket without
1271  *                      blocking in turn.
1272  *
1273  * @protocol:   Protocol whose connections will get callbacks
1274  */
1275
1276 int
1277 libwebsocket_callback_on_writable_all_protocol(
1278                                   const struct libwebsocket_protocols *protocol)
1279 {
1280         struct libwebsocket_context *context = protocol->owning_server;
1281         int n;
1282         struct libwebsocket *wsi;
1283
1284         for (n = 0; n < context->fds_count; n++) {
1285                 wsi = context->lws_lookup[context->fds[n].fd];
1286                 if (!wsi)
1287                         continue;
1288                 if (wsi->protocol == protocol)
1289                         libwebsocket_callback_on_writable(context, wsi);
1290         }
1291
1292         return 0;
1293 }
1294
1295 /**
1296  * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1297  *
1298  * You will not need this unless you are doing something special
1299  *
1300  * @wsi:        Websocket connection instance
1301  * @reason:     timeout reason
1302  * @secs:       how many seconds
1303  */
1304
1305 void
1306 libwebsocket_set_timeout(struct libwebsocket *wsi,
1307                                           enum pending_timeout reason, int secs)
1308 {
1309         struct timeval tv;
1310
1311         gettimeofday(&tv, NULL);
1312
1313         wsi->pending_timeout_limit = tv.tv_sec + secs;
1314         wsi->pending_timeout = reason;
1315 }
1316
1317
1318 /**
1319  * libwebsocket_get_socket_fd() - returns the socket file descriptor
1320  *
1321  * You will not need this unless you are doing something special
1322  *
1323  * @wsi:        Websocket connection instance
1324  */
1325
1326 int
1327 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1328 {
1329         return wsi->sock;
1330 }
1331
1332 #ifdef LWS_LATENCY
1333 void
1334 lws_latency(struct libwebsocket_context *context, struct libwebsocket *wsi, const char *action, int ret, int completed)
1335 {
1336         struct timeval tv;
1337         unsigned long u;
1338         char buf[256];
1339
1340         gettimeofday(&tv, NULL);
1341
1342         u = (tv.tv_sec * 1000000) + tv.tv_usec;
1343
1344         if (action) {
1345                 if (completed) {
1346                         if (wsi->action_start == wsi->latency_start)
1347                                 sprintf(buf, "Completion first try lat %luus: %p: ret %d: %s\n", u - wsi->latency_start, (void *)wsi, ret, action);
1348                         else
1349                                 sprintf(buf, "Completion %luus: lat %luus: %p: ret %d: %s\n", u - wsi->action_start, u - wsi->latency_start, (void *)wsi, ret, action);
1350                         wsi->action_start = 0;
1351                 } else
1352                         sprintf(buf, "lat %luus: %p: ret %d: %s\n", u - wsi->latency_start, (void *)wsi, ret, action);
1353                 if (u - wsi->latency_start > context->worst_latency) {
1354                         context->worst_latency = u - wsi->latency_start;
1355                         strcpy(context->worst_latency_info, buf);
1356                 }
1357                 lwsl_latency("%s", buf);
1358         } else {
1359                 wsi->latency_start = u;
1360                 if (!wsi->action_start)
1361                         wsi->action_start = u;
1362         }
1363 }
1364 #endif
1365
1366 #ifdef LWS_NO_SERVER
1367 int
1368 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1369 {
1370         return 0;
1371 }
1372 #else
1373 int
1374 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1375 {
1376         struct libwebsocket_context *context = wsi->protocol->owning_server;
1377         int n;
1378
1379         if (!(wsi->u.ws.rxflow_change_to & 2))
1380                 return 0;
1381
1382         wsi->u.ws.rxflow_change_to &= ~2;
1383
1384         lwsl_info("rxflow: wsi %p change_to %d\n", wsi, wsi->u.ws.rxflow_change_to);
1385
1386         /* if we're letting it come again, did we interrupt anything? */
1387         if ((wsi->u.ws.rxflow_change_to & 1) && wsi->u.ws.rxflow_buffer) {
1388                 n = libwebsocket_interpret_incoming_packet(wsi, NULL, 0);
1389                 if (n < 0) {
1390                         lwsl_info("returning that we want to close connection at libwebsocket_rx_flow_control:\n");
1391                         return -1;
1392                 }
1393                 if (n)
1394                         /* oh he stuck again, do nothing */
1395                         return 0;
1396         }
1397
1398         if (wsi->u.ws.rxflow_change_to & 1)
1399                 context->fds[wsi->position_in_fds_table].events |= POLLIN;
1400         else
1401                 context->fds[wsi->position_in_fds_table].events &= ~POLLIN;
1402
1403         if (wsi->u.ws.rxflow_change_to & 1)
1404                 /* external POLL support via protocol 0 */
1405                 context->protocols[0].callback(context, wsi,
1406                         LWS_CALLBACK_SET_MODE_POLL_FD,
1407                         (void *)(long)wsi->sock, NULL, POLLIN);
1408         else
1409                 /* external POLL support via protocol 0 */
1410                 context->protocols[0].callback(context, wsi,
1411                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1412                         (void *)(long)wsi->sock, NULL, POLLIN);
1413
1414         return 1;
1415 }
1416 #endif
1417
1418 /**
1419  * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1420  *                              receieved packets.
1421  *
1422  * If the output side of a server process becomes choked, this allows flow
1423  * control for the input side.
1424  *
1425  * @wsi:        Websocket connection instance to get callback for
1426  * @enable:     0 = disable read servicing for this connection, 1 = enable
1427  */
1428
1429 int
1430 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1431 {
1432         wsi->u.ws.rxflow_change_to = 2 | !!enable;
1433
1434         return 0;
1435 }
1436
1437
1438 /**
1439  * libwebsocket_canonical_hostname() - returns this host's hostname
1440  *
1441  * This is typically used by client code to fill in the host parameter
1442  * when making a client connection.  You can only call it after the context
1443  * has been created.
1444  *
1445  * @context:    Websocket context
1446  */
1447
1448
1449 extern const char *
1450 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
1451 {
1452         return (const char *)context->canonical_hostname;
1453 }
1454
1455
1456 static void sigpipe_handler(int x)
1457 {
1458 }
1459
1460 #ifdef LWS_OPENSSL_SUPPORT
1461 static int
1462 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1463 {
1464
1465         SSL *ssl;
1466         int n;
1467         struct libwebsocket_context *context;
1468
1469         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1470                 SSL_get_ex_data_X509_STORE_CTX_idx());
1471
1472         /*
1473          * !!! nasty openssl requires the index to come as a library-scope
1474          * static
1475          */
1476         context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
1477
1478         n = context->protocols[0].callback(NULL, NULL,
1479                 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1480                                                    x509_ctx, ssl, preverify_ok);
1481
1482         /* convert return code from 0 = OK to 1 = OK */
1483
1484         if (!n)
1485                 n = 1;
1486         else
1487                 n = 0;
1488
1489         return n;
1490 }
1491 #endif
1492
1493 int user_callback_handle_rxflow(callback_function callback_function,
1494                 struct libwebsocket_context * context,
1495                         struct libwebsocket *wsi,
1496                          enum libwebsocket_callback_reasons reason, void *user,
1497                                                           void *in, size_t len)
1498 {
1499         int n;
1500
1501         n = callback_function(context, wsi, reason, user, in, len);
1502         if (!n)
1503                 n = _libwebsocket_rx_flow_control(wsi);
1504
1505         return n;
1506 }
1507
1508
1509 /**
1510  * libwebsocket_create_context() - Create the websocket handler
1511  * @info:       pointer to struct with parameters
1512  *
1513  *      This function creates the listening socket (if serving) and takes care
1514  *      of all initialization in one step.
1515  *
1516  *      After initialization, it returns a struct libwebsocket_context * that
1517  *      represents this server.  After calling, user code needs to take care
1518  *      of calling libwebsocket_service() with the context pointer to get the
1519  *      server's sockets serviced.  This can be done in the same process context
1520  *      or a forked process, or another thread,
1521  *
1522  *      The protocol callback functions are called for a handful of events
1523  *      including http requests coming in, websocket connections becoming
1524  *      established, and data arriving; it's also called periodically to allow
1525  *      async transmission.
1526  *
1527  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
1528  *      at that time websocket protocol has not been negotiated.  Other
1529  *      protocols after the first one never see any HTTP callack activity.
1530  *
1531  *      The server created is a simple http server by default; part of the
1532  *      websocket standard is upgrading this http connection to a websocket one.
1533  *
1534  *      This allows the same server to provide files like scripts and favicon /
1535  *      images or whatever over http and dynamic data over websockets all in
1536  *      one place; they're all handled in the user callback.
1537  */
1538
1539 struct libwebsocket_context *
1540 libwebsocket_create_context(struct lws_context_creation_info *info)
1541 {
1542         int n;
1543         struct libwebsocket_context *context = NULL;
1544         char *p;
1545 #ifndef LWS_NO_SERVER
1546         int opt = 1;
1547         struct libwebsocket *wsi;
1548         struct sockaddr_in serv_addr;
1549 #endif
1550 #ifndef LWS_NO_EXTENSIONS
1551         int m;
1552         struct libwebsocket_extension *ext;
1553 #endif
1554
1555 #ifdef LWS_OPENSSL_SUPPORT
1556         SSL_METHOD *method;
1557 #endif
1558
1559 #ifndef LWS_NO_DAEMONIZE
1560         extern int get_daemonize_pid();
1561         int pid_daemon = get_daemonize_pid();
1562 #endif
1563
1564         lwsl_notice("Initial logging level %d\n", log_level);
1565         lwsl_notice("Library version: %s\n", library_version);
1566         lwsl_info(" LWS_MAX_HEADER_NAME_LENGTH: %u\n", LWS_MAX_HEADER_NAME_LENGTH);
1567         lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN);
1568         lwsl_info(" LWS_INITIAL_HDR_ALLOC: %u\n", LWS_INITIAL_HDR_ALLOC);
1569         lwsl_info(" LWS_ADDITIONAL_HDR_ALLOC: %u\n", LWS_ADDITIONAL_HDR_ALLOC);
1570         lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS);
1571 #ifndef LWS_NO_EXTENSIONS
1572         lwsl_info(" LWS_MAX_EXTENSIONS_ACTIVE: %u\n", LWS_MAX_EXTENSIONS_ACTIVE);
1573 #else
1574         lwsl_notice(" Configured without extension support\n");
1575 #endif
1576         lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED);
1577         lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT);
1578         lwsl_info(" CIPHERS_LIST_STRING: '%s'\n", CIPHERS_LIST_STRING);
1579         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
1580         lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER);
1581
1582 #ifdef _WIN32
1583         {
1584                 WORD wVersionRequested;
1585                 WSADATA wsaData;
1586                 int err;
1587                 HMODULE wsdll;
1588
1589                 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1590                 wVersionRequested = MAKEWORD(2, 2);
1591
1592                 err = WSAStartup(wVersionRequested, &wsaData);
1593                 if (err != 0) {
1594                         /* Tell the user that we could not find a usable */
1595                         /* Winsock DLL.                                  */
1596                         lwsl_err("WSAStartup failed with error: %d\n", err);
1597                         return NULL;
1598                 }
1599
1600                 /* default to a poll() made out of select() */
1601                 poll = emulated_poll;
1602
1603                 /* if windows socket lib available, use his WSAPoll */
1604                 wsdll = GetModuleHandle(_T("Ws2_32.dll"));
1605                 if (wsdll)
1606                         poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
1607
1608                 /* Finally fall back to emulated poll if all else fails */
1609                 if (!poll)
1610                         poll = emulated_poll;
1611         }
1612 #endif
1613
1614         context = (struct libwebsocket_context *) malloc(sizeof(struct libwebsocket_context));
1615         if (!context) {
1616                 lwsl_err("No memory for websocket context\n");
1617                 return NULL;
1618         }
1619         memset(context, 0, sizeof(*context));
1620 #ifndef LWS_NO_DAEMONIZE
1621         context->started_with_parent = pid_daemon;
1622         lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
1623 #endif
1624         
1625         context->listen_service_extraseen = 0;
1626         context->protocols = info->protocols;
1627         context->listen_port = info->port;
1628         context->http_proxy_port = 0;
1629         context->http_proxy_address[0] = '\0';
1630         context->options = info->options;
1631         /* to reduce this allocation, */
1632         context->max_fds = getdtablesize();
1633         lwsl_notice(" static allocation: %u + (%u x %u fds) = %u bytes\n",
1634                 sizeof(struct libwebsocket_context),
1635                 sizeof(struct pollfd) + sizeof(struct libwebsocket *),
1636                 context->max_fds,
1637                 sizeof(struct libwebsocket_context) + ((sizeof(struct pollfd) + sizeof(struct libwebsocket *)) * context->max_fds));
1638
1639         context->fds = (struct pollfd *)malloc(sizeof(struct pollfd) * context->max_fds);
1640         if (context->fds == NULL) {
1641                 lwsl_err("Unable to allocate fds array for %d connections\n", context->max_fds);
1642                 free(context);
1643                 return NULL;
1644         }
1645         context->lws_lookup = (struct libwebsocket **)malloc(sizeof(struct libwebsocket *) * context->max_fds);
1646         if (context->lws_lookup == NULL) {
1647                 lwsl_err("Unable to allocate lws_lookup array for %d connections\n", context->max_fds);
1648                 free(context->fds);
1649                 free(context);
1650                 return NULL;
1651         }
1652
1653         context->fds_count = 0;
1654 #ifndef LWS_NO_EXTENSIONS
1655         context->extensions = info->extensions;
1656 #endif
1657         context->last_timeout_check_s = 0;
1658         context->user_space = info->user;
1659
1660 #ifdef WIN32
1661         context->fd_random = 0;
1662 #else
1663         context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1664         if (context->fd_random < 0) {
1665                 lwsl_err("Unable to open random device %s %d\n",
1666                                     SYSTEM_RANDOM_FILEPATH, context->fd_random);
1667                 goto bail;
1668         }
1669 #endif
1670
1671 #ifdef LWS_OPENSSL_SUPPORT
1672         context->use_ssl = 0;
1673         context->ssl_ctx = NULL;
1674         context->ssl_client_ctx = NULL;
1675         openssl_websocket_private_data_index = 0;
1676 #endif
1677
1678         strcpy(context->canonical_hostname, "unknown");
1679
1680 #ifndef LWS_NO_SERVER
1681         if (!(info->options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)) {
1682                 struct sockaddr sa;
1683                 context->service_buffer[0] = '\0';
1684
1685                 /* find canonical hostname */
1686
1687                 context->service_buffer[(sizeof context->service_buffer) - 1] = '\0';
1688                 memset(&sa, 0, sizeof(sa));
1689                 sa.sa_family = AF_INET;
1690                 sa.sa_data[(sizeof sa.sa_data) - 1] = '\0';
1691                 gethostname((char *)context->service_buffer, (sizeof context->service_buffer) - 1);
1692
1693                 n = 0;
1694
1695                 if (strlen((char *)context->service_buffer) < sizeof(sa.sa_data) - 1) {
1696                         strcpy(sa.sa_data, (char *)context->service_buffer);
1697                         lwsl_debug("my host name is %s\n", sa.sa_data);
1698                         n = getnameinfo(&sa, sizeof(sa), (char *)context->service_buffer,
1699                                 (sizeof context->service_buffer) - 1, NULL, 0, NI_NAMEREQD);
1700                 }
1701
1702                 if (!n) {
1703                         strncpy(context->canonical_hostname, (char *)context->service_buffer,
1704                                                 sizeof context->canonical_hostname - 1);
1705                         context->canonical_hostname[
1706                                         sizeof context->canonical_hostname - 1] = '\0';
1707                 } else
1708                         strncpy(context->canonical_hostname, (char *)context->service_buffer,
1709                                                 sizeof context->canonical_hostname - 1);
1710
1711                 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
1712         }
1713 #endif
1714
1715         /* split the proxy ads:port if given */
1716
1717         p = getenv("http_proxy");
1718         if (p) {
1719                 strncpy(context->http_proxy_address, p,
1720                                        sizeof context->http_proxy_address - 1);
1721                 context->http_proxy_address[
1722                                  sizeof context->http_proxy_address - 1] = '\0';
1723
1724                 p = strchr(context->http_proxy_address, ':');
1725                 if (p == NULL) {
1726                         lwsl_err("http_proxy needs to be ads:port\n");
1727                         goto bail;
1728                 }
1729                 *p = '\0';
1730                 context->http_proxy_port = atoi(p + 1);
1731
1732                 lwsl_notice(" Proxy %s:%u\n",
1733                                 context->http_proxy_address,
1734                                                       context->http_proxy_port);
1735         }
1736
1737 #ifndef LWS_NO_SERVER
1738         if (info->port) {
1739
1740 #ifdef LWS_OPENSSL_SUPPORT
1741                 context->use_ssl = info->ssl_cert_filepath != NULL &&
1742                                          info->ssl_private_key_filepath != NULL;
1743 #ifdef USE_CYASSL
1744                 lwsl_notice(" Compiled with CYASSL support\n");
1745 #else
1746                 lwsl_notice(" Compiled with OpenSSL support\n");
1747 #endif
1748                 if (context->use_ssl)
1749                         lwsl_notice(" Using SSL mode\n");
1750                 else
1751                         lwsl_notice(" Using non-SSL mode\n");
1752
1753 #else
1754                 if (info->ssl_cert_filepath != NULL &&
1755                                        info->ssl_private_key_filepath != NULL) {
1756                         lwsl_notice(" Not compiled for OpenSSl support!\n");
1757                         goto bail;
1758                 }
1759                 lwsl_notice(" Compiled without SSL support, "
1760                                                        "serving unencrypted\n");
1761 #endif
1762
1763                 lwsl_notice(" per-connection allocation: %u + headers during handshake + frame buffer set by protocol\n", sizeof(struct libwebsocket));
1764         }
1765 #endif
1766
1767         /* ignore SIGPIPE */
1768 #ifdef WIN32
1769 #else
1770         signal(SIGPIPE, sigpipe_handler);
1771 #endif
1772
1773
1774 #ifdef LWS_OPENSSL_SUPPORT
1775
1776         /* basic openssl init */
1777
1778         SSL_library_init();
1779
1780         OpenSSL_add_all_algorithms();
1781         SSL_load_error_strings();
1782
1783         openssl_websocket_private_data_index =
1784                 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1785
1786         /*
1787          * Firefox insists on SSLv23 not SSLv3
1788          * Konq disables SSLv2 by default now, SSLv23 works
1789          */
1790
1791         method = (SSL_METHOD *)SSLv23_server_method();
1792         if (!method) {
1793                 lwsl_err("problem creating ssl method: %s\n",
1794                         ERR_error_string(ERR_get_error(), (char *)context->service_buffer));
1795                 goto bail;
1796         }
1797         context->ssl_ctx = SSL_CTX_new(method); /* create context */
1798         if (!context->ssl_ctx) {
1799                 lwsl_err("problem creating ssl context: %s\n",
1800                         ERR_error_string(ERR_get_error(), (char *)context->service_buffer));
1801                 goto bail;
1802         }
1803
1804 #ifdef SSL_OP_NO_COMPRESSION
1805         SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
1806 #endif
1807         SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
1808         SSL_CTX_set_cipher_list(context->ssl_ctx, CIPHERS_LIST_STRING);
1809
1810 #ifndef LWS_NO_CLIENT
1811
1812         /* client context */
1813
1814         if (info->port == CONTEXT_PORT_NO_LISTEN) {
1815                 method = (SSL_METHOD *)SSLv23_client_method();
1816                 if (!method) {
1817                         lwsl_err("problem creating ssl method: %s\n",
1818                                 ERR_error_string(ERR_get_error(), (char *)context->service_buffer));
1819                         goto bail;
1820                 }
1821                 /* create context */
1822                 context->ssl_client_ctx = SSL_CTX_new(method);
1823                 if (!context->ssl_client_ctx) {
1824                         lwsl_err("problem creating ssl context: %s\n",
1825                                 ERR_error_string(ERR_get_error(), (char *)context->service_buffer));
1826                         goto bail;
1827                 }
1828
1829 #ifdef SSL_OP_NO_COMPRESSION
1830                 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_NO_COMPRESSION);
1831 #endif
1832                 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
1833                 SSL_CTX_set_cipher_list(context->ssl_client_ctx, CIPHERS_LIST_STRING);
1834
1835                 /* openssl init for cert verification (for client sockets) */
1836                 if (!info->ssl_ca_filepath) {
1837                         if (!SSL_CTX_load_verify_locations(
1838                                 context->ssl_client_ctx, NULL,
1839                                                      LWS_OPENSSL_CLIENT_CERTS))
1840                                 lwsl_err(
1841                                         "Unable to load SSL Client certs from %s "
1842                                         "(set by --with-client-cert-dir= in configure) -- "
1843                                         " client ssl isn't going to work",
1844                                                      LWS_OPENSSL_CLIENT_CERTS);
1845                 } else
1846                         if (!SSL_CTX_load_verify_locations(
1847                                 context->ssl_client_ctx, info->ssl_ca_filepath,
1848                                                                   NULL))
1849                                 lwsl_err(
1850                                         "Unable to load SSL Client certs "
1851                                         "file from %s -- client ssl isn't "
1852                                         "going to work", info->ssl_ca_filepath);
1853
1854                 /*
1855                  * callback allowing user code to load extra verification certs
1856                  * helping the client to verify server identity
1857                  */
1858
1859                 context->protocols[0].callback(context, NULL,
1860                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1861                         context->ssl_client_ctx, NULL, 0);
1862         }
1863 #endif
1864
1865         /* as a server, are we requiring clients to identify themselves? */
1866
1867         if (info->options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1868
1869                 /* absolutely require the client cert */
1870
1871                 SSL_CTX_set_verify(context->ssl_ctx,
1872                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1873                                                        OpenSSL_verify_callback);
1874
1875                 /*
1876                  * give user code a chance to load certs into the server
1877                  * allowing it to verify incoming client certs
1878                  */
1879
1880                 context->protocols[0].callback(context, NULL,
1881                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
1882                                                      context->ssl_ctx, NULL, 0);
1883         }
1884
1885         if (context->use_ssl) {
1886
1887                 /* openssl init for server sockets */
1888
1889                 /* set the local certificate from CertFile */
1890                 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
1891                                         info->ssl_cert_filepath);
1892                 if (n != 1) {
1893                         lwsl_err("problem getting cert '%s': %s\n",
1894                                 info->ssl_cert_filepath,
1895                                 ERR_error_string(ERR_get_error(), (char *)context->service_buffer));
1896                         goto bail;
1897                 }
1898                 /* set the private key from KeyFile */
1899                 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
1900                              info->ssl_private_key_filepath,
1901                                                        SSL_FILETYPE_PEM) != 1) {
1902                         lwsl_err("ssl problem getting key '%s': %s\n",
1903                                                 info->ssl_private_key_filepath,
1904                                 ERR_error_string(ERR_get_error(), (char *)context->service_buffer));
1905                         goto bail;
1906                 }
1907                 /* verify private key */
1908                 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
1909                         lwsl_err("Private SSL key doesn't match cert\n");
1910                         goto bail;
1911                 }
1912
1913                 /* SSL is happy and has a cert it's content with */
1914         }
1915 #endif
1916
1917         /* selftest */
1918
1919         if (lws_b64_selftest())
1920                 goto bail;
1921
1922 #ifndef LWS_NO_SERVER
1923         /* set up our external listening socket we serve on */
1924
1925         if (info->port) {
1926                 extern int interface_to_sa(const char *ifname, struct sockaddr_in *addr, size_t addrlen);
1927                 int sockfd;
1928
1929                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1930                 if (sockfd < 0) {
1931                         lwsl_err("ERROR opening socket\n");
1932                         goto bail;
1933                 }
1934
1935 #ifndef WIN32
1936                 /* allow us to restart even if old sockets in TIME_WAIT
1937                  * (REUSEADDR on Unix means, "don't hang on to this address after the
1938                  * listener is closed."  On Windows, though, it means "don't keep other
1939                  * processes from binding to this address while we're using it) */
1940                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
1941                                               (const void *)&opt, sizeof(opt));
1942 #endif
1943
1944                 /* Disable Nagle */
1945                 opt = 1;
1946                 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
1947                                               (const void *)&opt, sizeof(opt));
1948
1949                 #ifdef WIN32
1950                 opt = 0;
1951                 ioctlsocket(sockfd, FIONBIO, (unsigned long *)&opt );
1952                 #else
1953                 fcntl(sockfd, F_SETFL, O_NONBLOCK);
1954                 #endif
1955
1956                 bzero((char *) &serv_addr, sizeof(serv_addr));
1957                 serv_addr.sin_family = AF_INET;
1958                 if (info->interface == NULL)
1959                         serv_addr.sin_addr.s_addr = INADDR_ANY;
1960                 else
1961                         interface_to_sa(info->interface, &serv_addr,
1962                                                 sizeof(serv_addr));
1963                 serv_addr.sin_port = htons(info->port);
1964
1965                 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1966                                                              sizeof(serv_addr));
1967                 if (n < 0) {
1968                         lwsl_err("ERROR on binding to port %d (%d %d)\n",
1969                                                         info->port, n, errno);
1970                         close(sockfd);
1971                         goto bail;
1972                 }
1973
1974                 wsi = (struct libwebsocket *)malloc(sizeof(struct libwebsocket));
1975                 if (wsi == NULL) {
1976                         lwsl_err("Out of mem\n");
1977                         close(sockfd);
1978                         goto bail;
1979                 }
1980                 memset(wsi, 0, sizeof (struct libwebsocket));
1981                 wsi->sock = sockfd;
1982 #ifndef LWS_NO_EXTENSIONS
1983                 wsi->count_active_extensions = 0;
1984 #endif
1985                 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1986
1987                 insert_wsi_socket_into_fds(context, wsi);
1988
1989                 context->listen_service_modulo = LWS_LISTEN_SERVICE_MODULO;
1990                 context->listen_service_count = 0;
1991                 context->listen_service_fd = sockfd;
1992
1993                 listen(sockfd, LWS_SOMAXCONN);
1994                 lwsl_notice(" Listening on port %d\n", info->port);
1995         }
1996 #endif
1997
1998         /*
1999          * drop any root privs for this process
2000          * to listen on port < 1023 we would have needed root, but now we are
2001          * listening, we don't want the power for anything else
2002          */
2003 #ifdef WIN32
2004 #else
2005         if (info->gid != -1)
2006                 if (setgid(info->gid))
2007                         lwsl_warn("setgid: %s\n", strerror(errno));
2008         if (info->uid != -1)
2009                 if (setuid(info->uid))
2010                         lwsl_warn("setuid: %s\n", strerror(errno));
2011 #endif
2012
2013         /* initialize supported protocols */
2014
2015         for (context->count_protocols = 0;
2016                 info->protocols[context->count_protocols].callback;
2017                                                    context->count_protocols++) {
2018
2019                 lwsl_parser("  Protocol: %s\n",
2020                                 info->protocols[context->count_protocols].name);
2021
2022                 info->protocols[context->count_protocols].owning_server =
2023                                                                         context;
2024                 info->protocols[context->count_protocols].protocol_index =
2025                                                        context->count_protocols;
2026         }
2027
2028 #ifndef LWS_NO_EXTENSIONS
2029         /*
2030          * give all extensions a chance to create any per-context
2031          * allocations they need
2032          */
2033
2034         m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
2035         if (info->port)
2036                 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
2037         
2038         if (info->extensions) {
2039                 ext = info->extensions;
2040                 while (ext->callback) {
2041                         lwsl_ext("  Extension: %s\n", ext->name);
2042                         ext->callback(context, ext, NULL,
2043                         (enum libwebsocket_extension_callback_reasons)m,
2044                                                                 NULL, NULL, 0);
2045                         ext++;
2046                 }
2047         }
2048 #endif
2049         return context;
2050
2051 bail:
2052         libwebsocket_context_destroy(context);
2053         return NULL;
2054 }
2055
2056 /**
2057  * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2058  *                                connection.
2059  * @wsi:        pointer to struct websocket you want to know the protocol of
2060  *
2061  *
2062  *      Some apis can act on all live connections of a given protocol,
2063  *      this is how you can get a pointer to the active protocol if needed.
2064  */
2065
2066 const struct libwebsocket_protocols *
2067 libwebsockets_get_protocol(struct libwebsocket *wsi)
2068 {
2069         return wsi->protocol;
2070 }
2071
2072 int
2073 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
2074 {
2075         return wsi->u.ws.final;
2076 }
2077
2078 unsigned char
2079 libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
2080 {
2081         return wsi->u.ws.rsv;
2082 }
2083
2084 void *
2085 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
2086 {
2087         /* allocate the per-connection user memory (if any) */
2088
2089         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
2090                 wsi->user_space = malloc(
2091                                   wsi->protocol->per_session_data_size);
2092                 if (wsi->user_space  == NULL) {
2093                         lwsl_err("Out of memory for conn user space\n");
2094                         return NULL;
2095                 }
2096                 memset(wsi->user_space, 0,
2097                                          wsi->protocol->per_session_data_size);
2098         }
2099         return wsi->user_space;
2100 }
2101
2102 static void lwsl_emit_stderr(int level, const char *line)
2103 {
2104         char buf[300];
2105         struct timeval tv;
2106         int n;
2107
2108         gettimeofday(&tv, NULL);
2109
2110         buf[0] = '\0';
2111         for (n = 0; n < LLL_COUNT; n++)
2112                 if (level == (1 << n)) {
2113                         sprintf(buf, "[%ld:%04d] %s: ", tv.tv_sec,
2114                                         (int)(tv.tv_usec / 100), log_level_names[n]);
2115                         break;
2116                 }
2117         
2118         fprintf(stderr, "%s%s", buf, line);
2119 }
2120
2121 #ifdef WIN32
2122 void lwsl_emit_syslog(int level, const char *line)
2123 {
2124         lwsl_emit_stderr(level, line);
2125 }
2126 #else
2127 void lwsl_emit_syslog(int level, const char *line)
2128 {
2129         int syslog_level = LOG_DEBUG;
2130
2131         switch (level) {
2132         case LLL_ERR:
2133                 syslog_level = LOG_ERR;
2134                 break;
2135         case LLL_WARN:
2136                 syslog_level = LOG_WARNING;
2137                 break;
2138         case LLL_NOTICE:
2139                 syslog_level = LOG_NOTICE;
2140                 break;
2141         case LLL_INFO:
2142                 syslog_level = LOG_INFO;
2143                 break;
2144         }
2145         syslog(syslog_level, "%s", line);
2146 }
2147 #endif
2148
2149 void _lws_log(int filter, const char *format, ...)
2150 {
2151         char buf[256];
2152         va_list ap;
2153
2154         if (!(log_level & filter))
2155                 return;
2156
2157         va_start(ap, format);
2158         vsnprintf(buf, (sizeof buf), format, ap);
2159         buf[(sizeof buf) - 1] = '\0';
2160         va_end(ap);
2161
2162         lwsl_emit(filter, buf);
2163 }
2164
2165 /**
2166  * lws_set_log_level() - Set the logging bitfield
2167  * @level:      OR together the LLL_ debug contexts you want output from
2168  * @log_emit_function:  NULL to leave it as it is, or a user-supplied
2169  *                      function to perform log string emission instead of
2170  *                      the default stderr one.
2171  *
2172  *      log level defaults to "err" and "warn" contexts enabled only and
2173  *      emission on stderr.
2174  */
2175
2176 void lws_set_log_level(int level, void (*log_emit_function)(int level, const char *line))
2177 {
2178         log_level = level;
2179         if (log_emit_function)
2180                 lwsl_emit = log_emit_function;
2181 }