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