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