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