force client ssl bio nonblocking
[profile/ivi/libwebsockets.git] / lib / client.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2013 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 <sys/un.h>
34 #include <sys/socket.h>
35 #include <netdb.h>
36 #endif
37
38 #ifdef LWS_OPENSSL_SUPPORT
39 extern int openssl_websocket_private_data_index;
40 #endif                            
41
42 int lws_client_socket_service(struct libwebsocket_context *context, struct libwebsocket *wsi, struct pollfd *pollfd)
43 {
44         int n;
45         char pkt[1024];
46         char *p = &pkt[0];
47         int len;
48         char c;
49 #ifdef LWS_OPENSSL_SUPPORT
50         char ssl_err_buf[512];
51 #endif
52
53         switch (wsi->mode) {
54
55         case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
56
57                 /* handle proxy hung up on us */
58
59                 if (pollfd->revents & (POLLERR | POLLHUP)) {
60
61                         lwsl_warn("Proxy connection %p (fd=%d) dead\n",
62                                 (void *)wsi, pollfd->fd);
63
64                         libwebsocket_close_and_free_session(context, wsi,
65                                                      LWS_CLOSE_STATUS_NOSTATUS);
66                         return 0;
67                 }
68
69                 n = recv(wsi->sock, pkt, sizeof pkt, 0);
70                 if (n < 0) {
71                         libwebsocket_close_and_free_session(context, wsi,
72                                                      LWS_CLOSE_STATUS_NOSTATUS);
73                         lwsl_err("ERROR reading from proxy socket\n");
74                         return 0;
75                 }
76
77                 pkt[13] = '\0';
78                 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
79                         libwebsocket_close_and_free_session(context, wsi,
80                                                      LWS_CLOSE_STATUS_NOSTATUS);
81                         lwsl_err("ERROR from proxy: %s\n", pkt);
82                         return 0;
83                 }
84
85                 /* clear his proxy connection timeout */
86
87                 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
88
89                 /* fallthru */
90
91         case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
92
93                 /*
94                  * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
95                  * timeout protection set in client-handshake.c
96                  */
97
98         #ifdef LWS_OPENSSL_SUPPORT
99
100                 /*
101                  * take care of our libwebsocket_callback_on_writable
102                  * happening at a time when there's no real connection yet
103                  */
104
105                 pollfd->events &= ~POLLOUT;
106
107                 /* external POLL support via protocol 0 */
108                 context->protocols[0].callback(context, wsi,
109                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
110                         (void *)(long)wsi->sock, NULL, POLLOUT);
111
112                 /* we can retry this... so just cook the SSL BIO the first time */
113
114                 if (wsi->use_ssl && !wsi->ssl) {
115
116                         wsi->ssl = SSL_new(context->ssl_client_ctx);
117                         wsi->client_bio = BIO_new_socket(wsi->sock,
118                                                                    BIO_NOCLOSE);
119
120                         SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
121
122                         BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */
123
124                         SSL_set_ex_data(wsi->ssl,
125                                         openssl_websocket_private_data_index,
126                                                                        context);
127                 }               
128
129                 if (wsi->use_ssl) {
130                         n = SSL_connect(wsi->ssl);
131
132                         if (n < 0) {
133                                 n = SSL_get_error(wsi->ssl, n);
134
135                                 if (n == SSL_ERROR_WANT_READ ||
136                                         n == SSL_ERROR_WANT_WRITE) {
137                                         /*
138                                          * wants us to retry connect due to state of the
139                                          * underlying ssl layer... but since it may be
140                                          * stalled on blocked write, no incoming data may
141                                          * arrive to trigger the retry.  Force (possibly
142                                          * many if the SSL state persists in returning the
143                                          * condition code, but other sockets are getting
144                                          * serviced inbetweentimes) us to get called back
145                                          * when writable.
146                                          */
147
148                                         lwsl_info("SSL_connect -> SSL_ERROR_WANT_... retrying\n");
149                                         libwebsocket_callback_on_writable(context, wsi);
150
151                                         return 0; /* no error */
152                                 }
153                                 n = -1;
154                         }
155
156                         if (n <= 0) {
157                                 /*
158                                  * retry if new data comes until we
159                                  * run into the connection timeout or win
160                                  */
161
162                                 lwsl_err("SSL connect error %s\n",
163                                         ERR_error_string(ERR_get_error(),
164                                                                   ssl_err_buf));
165                                 return 0;
166                         }
167
168                         n = SSL_get_verify_result(wsi->ssl);
169                         if ((n != X509_V_OK) && (
170                                 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
171                                                            wsi->use_ssl != 2)) {
172
173                                 lwsl_err("server's cert didn't "
174                                                            "look good %d\n", n);
175                                 libwebsocket_close_and_free_session(context,
176                                                 wsi, LWS_CLOSE_STATUS_NOSTATUS);
177                                 return 0;
178                         }
179                 } else
180                         wsi->ssl = NULL;
181         #endif
182
183                 p = libwebsockets_generate_client_handshake(context, wsi, p);
184                 if (p == NULL) {
185                         lwsl_err("Failed to generate handshake for client, closing it\n");
186                         libwebsocket_close_and_free_session(context, wsi,
187                                                      LWS_CLOSE_STATUS_NOSTATUS);
188                         return 0;
189                 }
190
191                 /* send our request to the server */
192
193         #ifdef LWS_OPENSSL_SUPPORT
194                 if (wsi->use_ssl)
195                         n = SSL_write(wsi->ssl, pkt, p - pkt);
196                 else
197         #endif
198                         n = send(wsi->sock, pkt, p - pkt, 0);
199
200                 if (n < 0) {
201                         lwsl_debug("ERROR writing to client socket\n");
202                         libwebsocket_close_and_free_session(context, wsi,
203                                                      LWS_CLOSE_STATUS_NOSTATUS);
204                         return 0;
205                 }
206
207                 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
208                 wsi->u.hdr.lextable_pos = 0;
209                 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
210                 libwebsocket_set_timeout(wsi,
211                                 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, AWAITING_TIMEOUT);
212
213                 break;
214
215         case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
216
217                 /* handle server hung up on us */
218
219                 if (pollfd->revents & (POLLERR | POLLHUP)) {
220
221                         lwsl_debug("Server connection %p (fd=%d) dead\n",
222                                 (void *)wsi, pollfd->fd);
223
224                         goto bail3;
225                 }
226
227
228                 /* interpret the server response */
229
230                 /*
231                  *  HTTP/1.1 101 Switching Protocols
232                  *  Upgrade: websocket
233                  *  Connection: Upgrade
234                  *  Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
235                  *  Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
236                  *  Sec-WebSocket-Protocol: chat
237                  */
238
239                 /*
240                  * we have to take some care here to only take from the
241                  * socket bytewise.  The browser may (and has been seen to
242                  * in the case that onopen() performs websocket traffic)
243                  * coalesce both handshake response and websocket traffic
244                  * in one packet, since at that point the connection is
245                  * definitively ready from browser pov.
246                  */
247
248                 len = 1;
249                 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE && len > 0) {
250 #ifdef LWS_OPENSSL_SUPPORT
251                         if (wsi->use_ssl)
252                                 len = SSL_read(wsi->ssl, &c, 1);
253                          else
254 #endif
255                                 len = recv(wsi->sock, &c, 1, 0);
256
257                         libwebsocket_parse(wsi, c);
258                 }
259
260                 /*
261                  * hs may also be coming in multiple packets, there is a 5-sec
262                  * libwebsocket timeout still active here too, so if parsing did
263                  * not complete just wait for next packet coming in this state
264                  */
265
266                 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
267                         break;
268
269                 /*
270                  * otherwise deal with the handshake.  If there's any
271                  * packet traffic already arrived we'll trigger poll() again
272                  * right away and deal with it that way
273                  */
274
275                 return lws_client_interpret_server_handshake(context, wsi);
276
277 bail3:
278                 if (wsi->c_protocol)
279                         free(wsi->c_protocol);
280                 libwebsocket_close_and_free_session(context, wsi,
281                                                     LWS_CLOSE_STATUS_NOSTATUS);
282                 return 0;
283
284         case LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT:
285                 lwsl_ext("LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT\n");
286                 break;
287
288         case LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD:
289                 lwsl_ext("LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD\n");
290                 break;
291         default:
292                 break;
293         }
294
295         return 0;
296 }
297
298
299 /*
300  * In-place str to lower case
301  */
302
303 static void
304 strtolower(char *s)
305 {
306         while (*s) {
307                 *s = tolower(*s);
308                 s++;
309         }
310 }
311
312 int
313 lws_client_interpret_server_handshake(struct libwebsocket_context *context,
314                 struct libwebsocket *wsi)
315 {
316         const char *pc;
317         int okay = 0;
318 #ifndef LWS_NO_EXTENSIONS
319         char ext_name[128];
320         struct libwebsocket_extension *ext;
321         void *v;
322         int more = 1;
323         const char *c;
324 #endif
325         int n;
326
327         /*
328          * well, what the server sent looked reasonable for syntax.
329          * Now let's confirm it sent all the necessary headers
330          */
331 #if 0
332         lwsl_parser("WSI_TOKEN_HTTP: %d\n",
333                                     wsi->utf8_token[WSI_TOKEN_HTTP].token_len);
334         lwsl_parser("WSI_TOKEN_UPGRADE: %d\n",
335                                  wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len);
336         lwsl_parser("WSI_TOKEN_CONNECTION: %d\n",
337                               wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len);
338         lwsl_parser("WSI_TOKEN_ACCEPT: %d\n",
339                                   wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len);
340         lwsl_parser("WSI_TOKEN_NONCE: %d\n",
341                                    wsi->utf8_token[WSI_TOKEN_NONCE].token_len);
342         lwsl_parser("WSI_TOKEN_PROTOCOL: %d\n",
343                                 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
344 #endif
345
346         strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
347         if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
348                 lwsl_warn("libwebsocket_client_handshake "
349                                 "server sent bad HTTP response '%s'\n",
350                                  wsi->utf8_token[WSI_TOKEN_HTTP].token);
351                 goto bail3;
352         }
353
354         strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
355         if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
356                                                          "websocket")) {
357                 lwsl_warn("libwebsocket_client_handshake server "
358                                 "sent bad Upgrade header '%s'\n",
359                                   wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
360                 goto bail3;
361         }
362
363         strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
364         if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
365                                                            "upgrade")) {
366                 lwsl_warn("libwebsocket_client_handshake server "
367                                 "sent bad Connection hdr '%s'\n",
368                            wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
369                 goto bail3;
370         }
371
372         pc = wsi->c_protocol;
373         if (pc == NULL)
374                 lwsl_parser("lws_client_interpret_server_handshake: "
375                                                           "NULL c_protocol\n");
376         else
377                 lwsl_parser("lws_client_interpret_server_handshake: "
378                                                       "cPprotocol='%s'\n", pc);
379
380         /*
381          * confirm the protocol the server wants to talk was in the list
382          * of protocols we offered
383          */
384
385         if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
386
387                 lwsl_info("lws_client_interpret_server_handshake "
388                                                "WSI_TOKEN_PROTOCOL is null\n");
389                 /*
390                  * no protocol name to work from,
391                  * default to first protocol
392                  */
393                 wsi->protocol = &context->protocols[0];
394                 wsi->c_callback = wsi->protocol->callback;
395                 free(wsi->c_protocol);
396
397                 goto check_extensions;
398         }
399
400         while (*pc && !okay) {
401                 if ((!strncmp(pc, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
402                  wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
403                  (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
404                   pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
405                         okay = 1;
406                         continue;
407                 }
408                 while (*pc && *pc != ',')
409                         pc++;
410                 while (*pc && *pc != ' ')
411                         pc++;
412         }
413
414         /* done with him now */
415
416         if (wsi->c_protocol)
417                 free(wsi->c_protocol);
418
419         if (!okay) {
420                 lwsl_err("libwebsocket_client_handshake server "
421                                         "sent bad protocol '%s'\n",
422                                  wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
423                 goto bail2;
424         }
425
426         /*
427          * identify the selected protocol struct and set it
428          */
429         n = 0;
430         wsi->protocol = NULL;
431         while (context->protocols[n].callback && !wsi->protocol) {  /* Stop after finding first one?? */
432                 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
433                                            context->protocols[n].name) == 0) {
434                         wsi->protocol = &context->protocols[n];
435                         wsi->c_callback = wsi->protocol->callback;
436                 }
437                 n++;
438         }
439
440         if (wsi->protocol == NULL) {
441                 lwsl_err("libwebsocket_client_handshake server "
442                                 "requested protocol '%s', which we "
443                                 "said we supported but we don't!\n",
444                                  wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
445                 goto bail2;
446         }
447
448
449 check_extensions:
450 #ifndef LWS_NO_EXTENSIONS
451         /* instantiate the accepted extensions */
452
453         if (!wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token_len) {
454                 lwsl_ext("no client extenstions allowed by server\n");
455                 goto check_accept;
456         }
457
458         /*
459          * break down the list of server accepted extensions
460          * and go through matching them or identifying bogons
461          */
462
463         c = wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token;
464         n = 0;
465         while (more) {
466
467                 if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
468                         ext_name[n] = *c++;
469                         if (n < sizeof(ext_name) - 1)
470                                 n++;
471                         continue;
472                 }
473                 ext_name[n] = '\0';
474                 if (!*c)
475                         more = 0;
476                 else {
477                         c++;
478                         if (!n)
479                                 continue;
480                 }
481
482                 /* check we actually support it */
483
484                 lwsl_ext("checking client ext %s\n", ext_name);
485
486                 n = 0;
487                 ext = wsi->protocol->owning_server->extensions;
488                 while (ext && ext->callback) {
489
490                         if (strcmp(ext_name, ext->name)) {
491                                 ext++;
492                                 continue;
493                         }
494
495                         n = 1;
496
497                         lwsl_ext("instantiating client ext %s\n", ext_name);
498
499                         /* instantiate the extension on this conn */
500
501                         wsi->active_extensions_user[
502                                 wsi->count_active_extensions] =
503                                          malloc(ext->per_session_data_size);
504                         if (wsi->active_extensions_user[
505                                 wsi->count_active_extensions] == NULL) {
506                                 lwsl_err("Out of mem\n");
507                                 goto bail2;
508                         }
509                         memset(wsi->active_extensions_user[
510                                 wsi->count_active_extensions], 0,
511                                                     ext->per_session_data_size);
512                         wsi->active_extensions[
513                                   wsi->count_active_extensions] = ext;
514
515                         /* allow him to construct his context */
516
517                         ext->callback(wsi->protocol->owning_server,
518                                 ext, wsi,
519                                    LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
520                                         wsi->active_extensions_user[
521                                          wsi->count_active_extensions],
522                                                                    NULL, 0);
523
524                         wsi->count_active_extensions++;
525
526                         ext++;
527                 }
528
529                 if (n == 0) {
530                         lwsl_warn("Server said we should use"
531                                   "an unknown extension '%s'!\n", ext_name);
532                         goto bail2;
533                 }
534
535                 n = 0;
536         }
537
538 check_accept:
539 #endif
540
541         /*
542          * Confirm his accept token is the one we precomputed
543          */
544
545         if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
546                                   wsi->u.hdr.initial_handshake_hash_base64)) {
547                 lwsl_warn("libwebsocket_client_handshake server "
548                         "sent bad ACCEPT '%s' vs computed '%s'\n",
549                         wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
550                                         wsi->u.hdr.initial_handshake_hash_base64);
551                 goto bail2;
552         }
553
554         /* allocate the per-connection user memory (if any) */
555         if (wsi->protocol->per_session_data_size &&
556                                           !libwebsocket_ensure_user_space(wsi))
557                 goto bail2;
558
559         /* clear his proxy connection timeout */
560
561         libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
562
563         /* mark him as being alive */
564
565         wsi->state = WSI_STATE_ESTABLISHED;
566         wsi->mode = LWS_CONNMODE_WS_CLIENT;
567
568         /* union transition */
569         memset(&wsi->u, 0, sizeof wsi->u);
570
571         lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);
572
573         /* call him back to inform him he is up */
574
575         wsi->protocol->callback(context, wsi,
576                                 LWS_CALLBACK_CLIENT_ESTABLISHED,
577                                                      wsi->user_space, NULL, 0);
578 #ifndef LWS_NO_EXTENSIONS
579         /*
580          * inform all extensions, not just active ones since they
581          * already know
582          */
583
584         ext = context->extensions;
585
586         while (ext && ext->callback) {
587                 v = NULL;
588                 for (n = 0; n < wsi->count_active_extensions; n++)
589                         if (wsi->active_extensions[n] == ext)
590                                 v = wsi->active_extensions_user[n];
591
592                 ext->callback(context, ext, wsi,
593                           LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0);
594                 ext++;
595         }
596 #endif
597
598         return 0;
599
600 bail3:
601         if (wsi->c_protocol)
602                 free(wsi->c_protocol);
603
604 bail2:
605         if (wsi->c_callback) wsi->c_callback(context, wsi,
606        LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
607                          wsi->user_space,
608                          NULL, 0);
609         libwebsocket_close_and_free_session(context, wsi,
610                                                  LWS_CLOSE_STATUS_NOSTATUS);  // But this should be LWS_CLOSE_STATUS_PROTOCOL_ERR
611
612         return 1;
613 }
614
615
616 char *
617 libwebsockets_generate_client_handshake(struct libwebsocket_context *context,
618                 struct libwebsocket *wsi, char *pkt)
619 {
620         char hash[20];
621         char key_b64[40];
622         char *p = pkt;
623         int n;
624 #ifndef LWS_NO_EXTENSIONS
625         struct libwebsocket_extension *ext;
626         struct libwebsocket_extension *ext1;
627         int ext_count = 0;
628 #endif
629         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
630                          MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
631         static const char magic_websocket_guid[] =
632                                          "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
633
634         /*
635          * create the random key
636          */
637
638         n = libwebsockets_get_random(context, hash, 16);
639         if (n != 16) {
640                 lwsl_err("Unable to read from random dev %s\n",
641                                                 SYSTEM_RANDOM_FILEPATH);
642                 free(wsi->c_path);
643                 free(wsi->c_host);
644                 if (wsi->c_origin)
645                         free(wsi->c_origin);
646                 if (wsi->c_protocol)
647                         free(wsi->c_protocol);
648                 libwebsocket_close_and_free_session(context, wsi,
649                                              LWS_CLOSE_STATUS_NOSTATUS);
650                 return NULL;
651         }
652
653         lws_b64_encode_string(hash, 16, key_b64, sizeof key_b64);
654
655         /*
656          * 00 example client handshake
657          *
658          * GET /socket.io/websocket HTTP/1.1
659          * Upgrade: WebSocket
660          * Connection: Upgrade
661          * Host: 127.0.0.1:9999
662          * Origin: http://127.0.0.1
663          * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7  92 ^
664          * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
665          * Cookie: socketio=websocket
666          *
667          * (Á®Ä0¶†≥
668          *
669          * 04 example client handshake
670          *
671          * GET /chat HTTP/1.1
672          * Host: server.example.com
673          * Upgrade: websocket
674          * Connection: Upgrade
675          * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
676          * Sec-WebSocket-Origin: http://example.com
677          * Sec-WebSocket-Protocol: chat, superchat
678          * Sec-WebSocket-Version: 4
679          */
680
681         p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
682
683         p += sprintf(p, "Pragma: no-cache\x0d\x0a"
684                                         "Cache-Control: no-cache\x0d\x0a");
685
686         p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
687         p += sprintf(p, "Upgrade: websocket\x0d\x0a"
688                                         "Connection: Upgrade\x0d\x0a"
689                                         "Sec-WebSocket-Key: ");
690         strcpy(p, key_b64);
691         p += strlen(key_b64);
692         p += sprintf(p, "\x0d\x0a");
693         if (wsi->c_origin) {
694                 if (wsi->ietf_spec_revision == 13)
695                         p += sprintf(p, "Origin: %s\x0d\x0a", wsi->c_origin);
696                 else
697                         p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
698                                                          wsi->c_origin);
699         }
700         if (wsi->c_protocol)
701                 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
702                                                        wsi->c_protocol);
703
704         /* tell the server what extensions we could support */
705
706         p += sprintf(p, "Sec-WebSocket-Extensions: ");
707 #ifndef LWS_NO_EXTENSIONS
708         ext = context->extensions;
709         while (ext && ext->callback) {
710
711                 n = 0;
712                 ext1 = context->extensions;
713
714                 while (ext1 && ext1->callback) {
715                         n |= ext1->callback(context, ext1, wsi,
716                                 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
717                                         NULL, (char *)ext->name, 0);
718
719                         ext1++;
720                 }
721
722                 if (n) { /* an extension vetos us */
723                         lwsl_ext("ext %s vetoed\n", (char *)ext->name);
724                         ext++;
725                         continue;
726                 }
727
728                 n = context->protocols[0].callback(context, wsi,
729                         LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
730                                 wsi->user_space, (char *)ext->name, 0);
731
732                 /*
733                  * zero return from callback means
734                  * go ahead and allow the extension,
735                  * it's what we get if the callback is
736                  * unhandled
737                  */
738
739                 if (n) {
740                         ext++;
741                         continue;
742                 }
743
744                 /* apply it */
745
746                 if (ext_count)
747                         *p++ = ',';
748                 p += sprintf(p, "%s", ext->name);
749                 ext_count++;
750
751                 ext++;
752         }
753 #endif
754         p += sprintf(p, "\x0d\x0a");
755
756         if (wsi->ietf_spec_revision)
757                 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
758                                                wsi->ietf_spec_revision);
759
760         /* give userland a chance to append, eg, cookies */
761
762         context->protocols[0].callback(context, wsi,
763                 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
764                 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
765
766         p += sprintf(p, "\x0d\x0a");
767
768         /* prepare the expected server accept response */
769
770         strcpy((char *)buf, key_b64);
771         strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
772
773         SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
774
775         lws_b64_encode_string(hash, 20,
776                         wsi->u.hdr.initial_handshake_hash_base64,
777                              sizeof wsi->u.hdr.initial_handshake_hash_base64);
778
779         /* done with these now */
780
781         free(wsi->c_path);
782         free(wsi->c_host);
783         if (wsi->c_origin)
784                 free(wsi->c_origin);
785
786         return p;
787 }
788