add-Sec-WebSocket-Draft-and-protocol-autodetect.patch
[profile/ivi/libwebsockets.git] / lib / libwebsockets.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  * 
4  * Copyright (C) 2010 Andy Green <andy@warmcat.com>
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public
8  *  License as published by the Free Software Foundation:
9  *  version 2.1 of the License.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23
24 #ifdef LWS_OPENSSL_SUPPORT
25 SSL_CTX *ssl_ctx;
26 int use_ssl;
27 #endif
28
29
30 extern int 
31 libwebsocket_read(struct libwebsocket *wsi, unsigned char * buf, size_t len);
32
33
34
35 void 
36 libwebsocket_close_and_free_session(struct libwebsocket *wsi)
37 {
38         int n = wsi->state;
39
40         wsi->state = WSI_STATE_DEAD_SOCKET;
41
42         if (wsi->callback && n == WSI_STATE_ESTABLISHED)
43                 wsi->callback(wsi, LWS_CALLBACK_CLOSED, &wsi->user_space[0], 
44                                                                        NULL, 0);
45
46         for (n = 0; n < WSI_TOKEN_COUNT; n++)
47                 if (wsi->utf8_token[n].token)
48                         free(wsi->utf8_token[n].token);
49
50 //      fprintf(stderr, "closing fd=%d\n", wsi->sock);
51
52 #ifdef LWS_OPENSSL_SUPPORT
53         if (use_ssl) {
54                 n = SSL_get_fd(wsi->ssl);
55                 SSL_shutdown(wsi->ssl);
56                 close(n);
57                 SSL_free(wsi->ssl);
58         } else {
59 #endif
60                 shutdown(wsi->sock, SHUT_RDWR);
61                 close(wsi->sock);
62 #ifdef LWS_OPENSSL_SUPPORT
63         }
64 #endif
65         free(wsi);
66 }
67
68 /**
69  * libwebsocket_create_server() - Create the listening websockets server
70  * @port:       Port to listen on
71  * @callback:   The callback in user code to perform actual serving
72  * @user_area_size:     How much memory to allocate per connection session
73  *                      which will be used by the user application to store
74  *                      per-session data.  A pointer to this space is given
75  *                      when the user callback is called.
76  * @ssl_cert_filepath:  If libwebsockets was compiled to use ssl, and you want
77  *                      to listen using SSL, set to the filepath to fetch the
78  *                      server cert from, otherwise NULL for unencrypted
79  * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
80  *                      else ignored
81  * @gid:        group id to change to after setting listen socket, or -1.
82  * @uid:        user id to change to after setting listen socket, or -1.
83  * 
84  *      This function forks to create the listening socket and takes care
85  *      of all initialization in one step.
86  * 
87  *      The callback function is called for a handful of events including
88  *      http requests coming in, websocket connections becoming
89  *      established, and data arriving; it's also called periodically to allow
90  *      async transmission.
91  * 
92  *      The server created is a simple http server by default; part of the
93  *      websocket standard is upgrading this http connection to a websocket one.
94  * 
95  *      This allows the same server to provide files like scripts and favicon /
96  *      images or whatever over http and dynamic data over websockets all in
97  *      one place; they're all handled in the user callback.
98  */
99
100 int libwebsocket_create_server(int port,
101                                int (*callback)(struct libwebsocket *,
102                                         enum libwebsocket_callback_reasons, 
103                                         void *, void *, size_t),
104                                size_t user_area_size,
105                                const char * ssl_cert_filepath,
106                                const char * ssl_private_key_filepath,
107                                int gid, int uid)
108 {
109         int n;
110         int client;
111         int sockfd;
112         int fd;
113         unsigned int clilen;
114         struct sockaddr_in serv_addr, cli_addr;
115         struct libwebsocket *wsi[MAX_CLIENTS + 1];
116         struct pollfd fds[MAX_CLIENTS + 1];
117         int fds_count = 0;
118         unsigned char buf[1024];
119         int opt = 1;
120
121 #ifdef LWS_OPENSSL_SUPPORT
122         const SSL_METHOD *method;
123         char ssl_err_buf[512];
124
125         use_ssl = ssl_cert_filepath != NULL && ssl_private_key_filepath != NULL;
126         if (use_ssl)
127                 fprintf(stderr, " Compiled with SSL support, using it\n");
128         else
129                 fprintf(stderr, " Compiled with SSL support, not using it\n");
130
131 #else
132         if (ssl_cert_filepath != NULL && ssl_private_key_filepath != NULL) {
133                 fprintf(stderr, " Not compiled for OpenSSl support!\n");
134                 return -1;
135         }
136         fprintf(stderr, " Compiled without SSL support, serving unencrypted\n");
137 #endif
138
139 #ifdef LWS_OPENSSL_SUPPORT
140         if (use_ssl) {
141                 SSL_library_init();
142
143                 OpenSSL_add_all_algorithms();
144                 SSL_load_error_strings();
145
146                         // Firefox insists on SSLv23 not SSLv3
147                         // Konq disables SSLv2 by default now, SSLv23 works
148
149                 method = SSLv23_server_method();   // create server instance
150                 if (!method) {
151                         fprintf(stderr, "problem creating ssl method: %s\n",
152                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
153                         return -1;
154                 }
155                 ssl_ctx = SSL_CTX_new(method);  /* create context */
156                 if (!ssl_ctx) {
157                         printf("problem creating ssl context: %s\n",
158                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
159                         return -1;
160                 }
161                 /* set the local certificate from CertFile */
162                 n = SSL_CTX_use_certificate_file(ssl_ctx,
163                                         ssl_cert_filepath, SSL_FILETYPE_PEM);
164                 if (n != 1) {
165                         fprintf(stderr, "problem getting cert '%s': %s\n",
166                                 ssl_cert_filepath,
167                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
168                         return -1;
169                 }
170                 /* set the private key from KeyFile */
171                 if (SSL_CTX_use_PrivateKey_file(ssl_ctx,
172                                                 ssl_private_key_filepath,
173                                                 SSL_FILETYPE_PEM) != 1) {
174                         fprintf(stderr, "ssl problem getting key '%s': %s\n",
175                                                 ssl_private_key_filepath,
176                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
177                         return (-1);
178                 }
179                 /* verify private key */
180                 if (!SSL_CTX_check_private_key(ssl_ctx)) {
181                         fprintf(stderr, "Private SSL key doesn't match cert\n");
182                         return (-1);
183                 }
184
185                 /* SSL is happy and has a cert it's content with */
186         }
187 #endif
188         
189         if (!callback) {
190                 fprintf(stderr, "callback is not optional!\n");
191                 return -1;
192         }
193  
194         /* sit there listening for connects, accept and spawn session servers */
195  
196         sockfd = socket(AF_INET, SOCK_STREAM, 0);
197         if (sockfd < 0) {
198                 fprintf(stderr, "ERROR opening socket");
199                 return -1;
200         }
201         
202         /* allow us to restart even if old sockets in TIME_WAIT */
203         setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
204
205         bzero((char *) &serv_addr, sizeof(serv_addr));
206         serv_addr.sin_family = AF_INET;
207         serv_addr.sin_addr.s_addr = INADDR_ANY;
208         serv_addr.sin_port = htons(port);
209         n = bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
210         if (n < 0) {
211               fprintf(stderr, "ERROR on binding to port %d (%d %d)\n", port, n,
212                                                                          errno);
213               return -1;
214         }
215  
216         /* fork off a master server for this websocket server */
217  
218         n = fork();
219         if (n < 0) {
220                 fprintf(stderr, "Failed on forking server thread: %d\n", n);
221                 return -1;
222         }
223         
224         /* we are done as far as the caller is concerned */
225         
226         if (n)
227                 return sockfd;
228  
229         // drop any root privs for this thread
230
231         if (gid != -1)
232                 if (setgid(gid))
233                         fprintf(stderr, "setgid: %s\n", strerror(errno));
234         if (uid != -1)
235                 if (setuid(uid))
236                         fprintf(stderr, "setuid: %s\n", strerror(errno));
237
238         /* we are running in a forked subprocess now */
239  
240         listen(sockfd, 5);
241         fprintf(stderr, " Listening on port %d\n", port);
242         
243         fds[0].fd = sockfd;
244         fds_count = 1;
245         fds[0].events = POLLIN;
246     
247         while (1) {
248
249                 n = poll(fds, fds_count, 50);
250                 if (n < 0 || fds[0].revents & (POLLERR | POLLHUP)) {
251 //                      fprintf(stderr, "Listen Socket dead\n");
252                         goto fatal;
253                 }
254                 if (n == 0) /* poll timeout */
255                         goto poll_out;
256
257                 if (fds[0].revents & POLLIN) {
258
259                         /* listen socket got an unencrypted connection... */
260
261                         clilen = sizeof(cli_addr);
262                         fd  = accept(sockfd,
263                                      (struct sockaddr *)&cli_addr,
264                                                                &clilen);
265                         if (fd < 0) {
266                                 fprintf(stderr, "ERROR on accept");
267                                 continue;
268                         }
269
270                         if (fds_count >= MAX_CLIENTS) {
271                                 fprintf(stderr, "too busy");
272                                 close(fd);
273                                 continue;
274                         }
275
276                         wsi[fds_count] = malloc(sizeof(struct libwebsocket) +
277                                                                 user_area_size);
278                         if (!wsi[fds_count])
279                                 return -1;
280
281
282 #ifdef LWS_OPENSSL_SUPPORT
283                         if (use_ssl) {
284
285                                 wsi[fds_count]->ssl = SSL_new(ssl_ctx);
286                                 if (wsi[fds_count]->ssl == NULL) {
287                                         fprintf(stderr, "SSL_new failed: %s\n",
288                                             ERR_error_string(SSL_get_error(
289                                                 wsi[fds_count]->ssl, 0), NULL));
290                                         free(wsi[fds_count]);
291                                         continue;
292                                 }
293
294                                 SSL_set_fd(wsi[fds_count]->ssl, fd);
295
296                                 n = SSL_accept(wsi[fds_count]->ssl);
297                                 if (n != 1) {
298                                         /*
299                                          * browsers seem to probe with various
300                                          * ssl params which fail then retry
301                                          * and succeed
302                                          */
303                                         debug("SSL_accept failed skt %u: %s\n",
304                                                 fd,
305                                                 ERR_error_string(SSL_get_error(
306                                                 wsi[fds_count]->ssl, n), NULL));
307                                         SSL_free(wsi[fds_count]->ssl);
308                                         free(wsi[fds_count]);
309                                         continue;
310                                 }
311                                 debug("accepted new SSL conn  "
312                                       "port %u on fd=%d SSL ver %s\n",
313                                         ntohs(cli_addr.sin_port), fd,
314                                           SSL_get_version(wsi[fds_count]->ssl));
315                                 
316                         } else {
317 //                      fprintf(stderr, "accepted new conn  port %u on fd=%d\n",
318 //                                                ntohs(cli_addr.sin_port), fd);
319                         }
320 #endif
321                         
322                         /* intialize the instance struct */
323
324                         wsi[fds_count]->sock = fd;
325                         wsi[fds_count]->state = WSI_STATE_HTTP;
326                         wsi[fds_count]->name_buffer_pos = 0;
327
328                         for (n = 0; n < WSI_TOKEN_COUNT; n++) {
329                                 wsi[fds_count]->utf8_token[n].token = NULL;
330                                 wsi[fds_count]->utf8_token[n].token_len = 0;
331                         }
332
333                         wsi[fds_count]->callback = callback;
334                         /*
335                          * Default protocol is 76
336                          * After 76, there's a header specified to inform which
337                          * draft the client wants
338                          */
339                         wsi[fds_count]->ietf_spec_revision = 76;
340
341                         fds[fds_count].events = POLLIN;
342                         fds[fds_count++].fd = fd;
343                 }
344                 
345                 /* check for activity on client sockets */
346                 
347                 for (client = 1; client < fds_count; client++) {
348                         
349                         /* handle session socket closed */
350                         
351                         if (fds[client].revents & (POLLERR | POLLHUP)) {
352                                 
353                                 fprintf(stderr, "Session Socket dead\n");
354
355                                 libwebsocket_close_and_free_session(
356                                                                    wsi[client]);
357                                 goto nuke_this;
358                         }
359                         
360                         /* any incoming data ready? */
361
362                         if (!(fds[client].revents & POLLIN))
363                                 continue;
364                                 
365 //                      fprintf(stderr, "POLLIN\n");
366
367 #ifdef LWS_OPENSSL_SUPPORT
368                         if (use_ssl)
369                                 n = SSL_read(wsi[client]->ssl, buf, sizeof buf);
370                         else
371 #endif
372                                 n = recv(fds[client].fd, buf, sizeof(buf), 0);
373
374 //                      fprintf(stderr, "read returned %d\n", n);
375
376                         if (n < 0) {
377                                 fprintf(stderr, "Socket read returned %d\n", n);
378                                 continue;
379                         }
380                         if (!n) {
381 //                              fprintf(stderr, "POLLIN with 0 len waiting\n");
382                                 libwebsocket_close_and_free_session(
383                                                                    wsi[client]);
384                                 goto nuke_this;
385                         }
386                         
387                         /* service incoming data */
388
389                         if (libwebsocket_read(wsi[client], buf, n) >= 0)
390                                 continue;
391                         
392                         /* it closed and nuked wsi[client] */
393 nuke_this:
394                         for (n = client; n < fds_count - 1; n++) {
395                                 fds[n] = fds[n + 1];
396                                 wsi[n] = wsi[n + 1];
397                         }
398                         fds_count--;
399                         client--;
400                 }
401
402 poll_out:               
403                 for (client = 1; client < fds_count; client++) {
404
405                         if (wsi[client]->state != WSI_STATE_ESTABLISHED)
406                                 continue;
407                                                 
408                         if (!wsi[client]->callback)
409                                 continue;
410
411                         wsi[client]->callback(wsi[client], LWS_CALLBACK_SEND, 
412                                           &wsi[client]->user_space[0], NULL, 0);
413                 }
414                 
415                 continue;               
416         }
417         
418 fatal:
419         /* listening socket */
420         close(fds[0].fd);
421         for (client = 1; client < fds_count; client++)
422                 libwebsocket_close_and_free_session(wsi[client]);
423
424 #ifdef LWS_OPENSSL_SUPPORT
425         SSL_CTX_free(ssl_ctx);
426 #endif
427         kill(0, SIGTERM);
428         
429         return 0;
430 }
431
432