]> Pileus Git - ~andy/gtk/blob - gdk/broadway/gdkdisplay-broadway.c
861560ef48fb80a3c53d5d3290cfd61e3f91e781
[~andy/gtk] / gdk / broadway / gdkdisplay-broadway.c
1 /* GDK - The GIMP Drawing Kit
2  * gdkdisplay-broadway.c
3  * 
4  * Copyright 2001 Sun Microsystems Inc.
5  * Copyright (C) 2004 Nokia Corporation
6  *
7  * Erwann Chenede <erwann.chenede@sun.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24
25 #include "config.h"
26
27 #include "gdkdisplay-broadway.h"
28
29 #include "gdkdisplay.h"
30 #include "gdkeventsource.h"
31 #include "gdkscreen.h"
32 #include "gdkscreen-broadway.h"
33 #include "gdkinternals.h"
34 #include "gdkdeviceprivate.h"
35 #include "gdkdevicemanager-broadway.h"
36
37 #include <glib.h>
38 #include <glib/gprintf.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <errno.h>
42 #include <unistd.h>
43 #include <sys/types.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <netinet/tcp.h>
47
48 static void   gdk_broadway_display_dispose            (GObject            *object);
49 static void   gdk_broadway_display_finalize           (GObject            *object);
50
51 #if 0
52 #define DEBUG_WEBSOCKETS 1
53 #endif
54
55 G_DEFINE_TYPE (GdkBroadwayDisplay, gdk_broadway_display, GDK_TYPE_DISPLAY)
56
57 static void
58 gdk_broadway_display_init (GdkBroadwayDisplay *display)
59 {
60   _gdk_broadway_display_manager_add_display (gdk_display_manager_get (),
61                                              GDK_DISPLAY_OBJECT (display));
62   display->id_ht = g_hash_table_new (NULL, NULL);
63 }
64
65 static void
66 gdk_event_init (GdkDisplay *display)
67 {
68   GdkBroadwayDisplay *broadway_display;
69
70   broadway_display = GDK_BROADWAY_DISPLAY (display);
71   broadway_display->event_source = _gdk_broadway_event_source_new (display);
72   broadway_display->saved_serial = 1;
73   broadway_display->last_seen_time = 1;
74 }
75
76 static void
77 gdk_broadway_display_init_input (GdkDisplay *display)
78 {
79   GdkBroadwayDisplay *broadway_display;
80   GdkDeviceManager *device_manager;
81   GdkDevice *device;
82   GList *list, *l;
83
84   broadway_display = GDK_BROADWAY_DISPLAY (display);
85   device_manager = gdk_display_get_device_manager (display);
86
87   /* For backwards compatibility, just add
88    * floating devices that are not keyboards.
89    */
90   list = gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_FLOATING);
91
92   for (l = list; l; l = l->next)
93     {
94       device = l->data;
95
96       if (gdk_device_get_source (device) == GDK_SOURCE_KEYBOARD)
97         continue;
98
99       broadway_display->input_devices = g_list_prepend (broadway_display->input_devices,
100                                                    g_object_ref (l->data));
101     }
102
103   g_list_free (list);
104
105   /* Now set "core" pointer to the first
106    * master device that is a pointer.
107    */
108   list = gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_MASTER);
109
110   for (l = list; l; l = l->next)
111     {
112       device = list->data;
113
114       if (gdk_device_get_source (device) != GDK_SOURCE_MOUSE)
115         continue;
116
117       display->core_pointer = device;
118       break;
119     }
120
121   /* Add the core pointer to the devices list */
122   broadway_display->input_devices = g_list_prepend (broadway_display->input_devices,
123                                                g_object_ref (display->core_pointer));
124
125   g_list_free (list);
126 }
127
128 typedef struct HttpRequest {
129   GdkDisplay *display;
130   GSocketConnection *connection;
131   GDataInputStream *data;
132   GString *request;
133 }  HttpRequest;
134
135 static void start_output (HttpRequest *request, gboolean proto_v7_plus);
136
137 static void
138 http_request_free (HttpRequest *request)
139 {
140   g_object_unref (request->connection);
141   g_object_unref (request->data);
142   g_string_free (request->request, TRUE);
143   g_free (request);
144 }
145
146 struct BroadwayInput {
147   GdkDisplay *display;
148   GSocketConnection *connection;
149   GByteArray *buffer;
150   GSource *source;
151   gboolean seen_time;
152   gint64 time_base;
153   gboolean proto_v7_plus;
154 };
155
156 static void
157 broadway_input_free (BroadwayInput *input)
158 {
159   g_object_unref (input->connection);
160   g_byte_array_free (input->buffer, FALSE);
161   g_source_destroy (input->source);
162   g_free (input);
163 }
164
165 static void
166 process_input_messages (GdkBroadwayDisplay *broadway_display)
167 {
168   BroadwayInputMsg *message;
169
170   while (broadway_display->input_messages)
171     {
172       message = broadway_display->input_messages->data;
173       broadway_display->input_messages =
174         g_list_delete_link (broadway_display->input_messages,
175                             broadway_display->input_messages);
176
177       _gdk_broadway_events_got_input (GDK_DISPLAY (broadway_display), message);
178       g_free (message);
179     }
180 }
181
182 static char *
183 parse_pointer_data (char *p, BroadwayInputPointerMsg *data)
184 {
185   data->mouse_window_id = strtol (p, &p, 10);
186   p++; /* Skip , */
187   data->event_window_id = strtol (p, &p, 10);
188   p++; /* Skip , */
189   data->root_x = strtol (p, &p, 10);
190   p++; /* Skip , */
191   data->root_y = strtol (p, &p, 10);
192   p++; /* Skip , */
193   data->win_x = strtol (p, &p, 10);
194   p++; /* Skip , */
195   data->win_y = strtol (p, &p, 10);
196   p++; /* Skip , */
197   data->state = strtol (p, &p, 10);
198
199   return p;
200 }
201
202 static void
203 update_future_pointer_info (GdkBroadwayDisplay *broadway_display, BroadwayInputPointerMsg *data)
204 {
205   broadway_display->future_root_x = data->root_x;
206   broadway_display->future_root_y = data->root_y;
207   broadway_display->future_state = data->state;
208   broadway_display->future_mouse_in_toplevel = data->mouse_window_id;
209 }
210
211 static void
212 parse_input_message (BroadwayInput *input, const char *message)
213 {
214   GdkBroadwayDisplay *broadway_display;
215   BroadwayInputMsg msg;
216   char *p;
217   gint64 time_;
218
219   broadway_display = GDK_BROADWAY_DISPLAY (input->display);
220
221   p = (char *)message;
222   msg.base.type = *p++;
223   msg.base.serial = (guint32)strtol (p, &p, 10);
224   p++; /* Skip , */
225   time_ = strtol(p, &p, 10);
226   p++; /* Skip , */
227
228   if (time_ == 0) {
229     time_ = broadway_display->last_seen_time;
230   } else {
231     if (!input->seen_time) {
232       input->seen_time = TRUE;
233       /* Calculate time base so that any following times are normalized to start
234          5 seconds after last_seen_time, to avoid issues that could appear when
235          a long hiatus due to a reconnect seems to be instant */
236       input->time_base = time_ - (broadway_display->last_seen_time + 5000);
237     }
238     time_ = time_ - input->time_base;
239   }
240
241   broadway_display->last_seen_time = time_;
242
243   msg.base.time = time_;
244
245   switch (msg.base.type) {
246   case 'e': /* Enter */
247   case 'l': /* Leave */
248     p = parse_pointer_data (p, &msg.pointer);
249     update_future_pointer_info (broadway_display, &msg.pointer);
250     p++; /* Skip , */
251     msg.crossing.mode = strtol(p, &p, 10);
252     break;
253
254   case 'm': /* Mouse move */
255     p = parse_pointer_data (p, &msg.pointer);
256     update_future_pointer_info (broadway_display, &msg.pointer);
257     break;
258
259   case 'b':
260   case 'B':
261     p = parse_pointer_data (p, &msg.pointer);
262     update_future_pointer_info (broadway_display, &msg.pointer);
263     p++; /* Skip , */
264     msg.button.button = strtol(p, &p, 10);
265     break;
266
267   case 's':
268     p = parse_pointer_data (p, &msg.pointer);
269     update_future_pointer_info (broadway_display, &msg.pointer);
270     p++; /* Skip , */
271     msg.scroll.dir = strtol(p, &p, 10);
272     break;
273
274   case 'k':
275   case 'K':
276     msg.key.key = strtol(p, &p, 10);
277     p++; /* Skip , */
278     msg.key.state = strtol(p, &p, 10);
279     break;
280
281   case 'g':
282   case 'u':
283     msg.grab_reply.res = strtol(p, &p, 10);
284     break;
285
286   case 'w':
287     msg.configure_notify.id = strtol(p, &p, 10);
288     p++; /* Skip , */
289     msg.configure_notify.x = strtol (p, &p, 10);
290     p++; /* Skip , */
291     msg.configure_notify.y = strtol (p, &p, 10);
292     p++; /* Skip , */
293     msg.configure_notify.width = strtol (p, &p, 10);
294     p++; /* Skip , */
295     msg.configure_notify.height = strtol (p, &p, 10);
296     break;
297
298   case 'W':
299     msg.delete_notify.id = strtol(p, &p, 10);
300     break;
301
302   case 'd':
303     msg.screen_resize_notify.width = strtol (p, &p, 10);
304     p++; /* Skip , */
305     msg.screen_resize_notify.height = strtol (p, &p, 10);
306     break;
307
308   default:
309     g_printerr ("Unknown input command %s\n", message);
310     break;
311   }
312
313   broadway_display->input_messages = g_list_append (broadway_display->input_messages, g_memdup (&msg, sizeof (msg)));
314
315 }
316
317 static inline void
318 hex_dump (guchar *data, gsize len)
319 {
320 #ifdef DEBUG_WEBSOCKETS
321   gsize i, j;
322   for (j = 0; j < len + 15; j += 16)
323     {
324       fprintf (stderr, "0x%.4x  ", j);
325       for (i = 0; i < 16; i++)
326         {
327             if ((j + i) < len)
328               fprintf (stderr, "%.2x ", data[j+i]);
329             else
330               fprintf (stderr, "  ");
331             if (i == 8)
332               fprintf (stderr, " ");
333         }
334       fprintf (stderr, " | ");
335
336       for (i = 0; i < 16; i++)
337         if ((j + i) < len && g_ascii_isalnum(data[j+i]))
338           fprintf (stderr, "%c", data[j+i]);
339         else
340           fprintf (stderr, ".");
341       fprintf (stderr, "\n");
342     }
343 #endif
344 }
345
346 static void
347 parse_input (BroadwayInput *input)
348 {
349   GdkBroadwayDisplay *broadway_display;
350
351   broadway_display = GDK_BROADWAY_DISPLAY (input->display);
352
353   if (!input->buffer->len)
354     return;
355
356   if (input->proto_v7_plus)
357     {
358       hex_dump (input->buffer->data, input->buffer->len);
359
360       while (input->buffer->len > 2)
361         {
362           gsize len, payload_len;
363           BroadwayWSOpCode code;
364           gboolean is_mask, fin;
365           guchar *buf, *data, *mask;
366
367           buf = input->buffer->data;
368           len = input->buffer->len;
369
370 #ifdef DEBUG_WEBSOCKETS
371           g_print ("Parse input first byte 0x%2x 0x%2x\n", buf[0], buf[1]);
372 #endif
373
374           fin = buf[0] & 0x80;
375           code = buf[0] & 0x0f;
376           payload_len = buf[1] & 0x7f;
377           is_mask = buf[1] & 0x80;
378           data = buf + 2;
379
380           if (payload_len > 125)
381             {
382               if (len < 4)
383                 return;
384               payload_len = GUINT16_FROM_BE( *(guint16 *) data );
385               data += 2;
386             }
387           else if (payload_len > 126)
388             {
389               if (len < 10)
390                 return;
391               payload_len = GUINT64_FROM_BE( *(guint64 *) data );
392               data += 8;
393             }
394
395           mask = NULL;
396           if (is_mask)
397             {
398               if (data - buf + 4 > len)
399                 return;
400               mask = data;
401               data += 4;
402             }
403
404           if (data - buf + payload_len > len)
405             return; /* wait to accumulate more */
406
407           if (is_mask)
408             {
409               gsize i;
410               for (i = 0; i < payload_len; i++)
411                 data[i] ^= mask[i%4];
412             }
413
414           switch (code) {
415           case BROADWAY_WS_CNX_CLOSE:
416             break; /* hang around anyway */
417           case BROADWAY_WS_TEXT:
418             if (!fin)
419               {
420 #ifdef DEBUG_WEBSOCKETS
421                 g_warning ("can't yet accept fragmented input");
422 #endif
423               }
424             else
425               parse_input_message (input, (char *)data);
426             break;
427           case BROADWAY_WS_CNX_PING:
428             broadway_output_pong (broadway_display->output);
429             break;
430           case BROADWAY_WS_CNX_PONG:
431             break; /* we never send pings, but tolerate pongs */
432           case BROADWAY_WS_BINARY:
433           case BROADWAY_WS_CONTINUATION:
434           default:
435             {
436               g_warning ("fragmented or unknown input code 0x%2x with fin set", code);
437               break;
438             }
439           }
440
441           g_byte_array_remove_range (input->buffer, 0, data - buf + payload_len);
442         }
443     }
444   else /* old style protocol */
445     {
446       char *buf, *ptr;
447       gsize len;
448
449       buf = (char *)input->buffer->data;
450       len = input->buffer->len;
451
452       if (buf[0] != 0)
453         {
454           broadway_display->input = NULL;
455           broadway_input_free (input);
456           return;
457         }
458
459       while ((ptr = memchr (buf, 0xff, len)) != NULL)
460         {
461           *ptr = 0;
462           ptr++;
463
464           parse_input_message (input, buf + 1);
465
466           len -= ptr - buf;
467           buf = ptr;
468
469           if (len > 0 && buf[0] != 0)
470             {
471               broadway_display->input = NULL;
472               broadway_input_free (input);
473               break;
474             }
475         }
476       g_byte_array_remove_range (input->buffer, 0, buf - (char *)input->buffer->data);
477     }
478 }
479
480
481 static gboolean
482 process_input_idle_cb (GdkBroadwayDisplay *display)
483 {
484   display->process_input_idle = 0;
485   process_input_messages (display);
486   return G_SOURCE_REMOVE;
487 }
488
489 static void
490 queue_process_input_at_idle (GdkBroadwayDisplay *broadway_display)
491 {
492   if (broadway_display->process_input_idle == 0)
493     broadway_display->process_input_idle =
494       g_idle_add_full (GDK_PRIORITY_EVENTS, (GSourceFunc)process_input_idle_cb, broadway_display, NULL);
495 }
496
497 static void
498 _gdk_broadway_display_read_all_input_nonblocking (GdkDisplay *display)
499 {
500   GdkBroadwayDisplay *broadway_display;
501   GInputStream *in;
502   gssize res;
503   guint8 buffer[1024];
504   GError *error;
505   BroadwayInput *input;
506
507   broadway_display = GDK_BROADWAY_DISPLAY (display);
508   if (broadway_display->input == NULL)
509     return;
510
511   input = broadway_display->input;
512
513   in = g_io_stream_get_input_stream (G_IO_STREAM (input->connection));
514
515   error = NULL;
516   res = g_pollable_input_stream_read_nonblocking (G_POLLABLE_INPUT_STREAM (in),
517                                                   buffer, sizeof (buffer), NULL, &error);
518
519   if (res <= 0)
520     {
521       if (res < 0 &&
522           g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
523         {
524           g_error_free (error);
525           return;
526         }
527
528       broadway_display->input = NULL;
529       broadway_input_free (input);
530       if (res < 0)
531         {
532           g_print ("input error %s\n", error->message);
533           g_error_free (error);
534         }
535       return;
536     }
537
538   g_byte_array_append (input->buffer, buffer, res);
539
540   parse_input (input);
541 }
542
543 void
544 _gdk_broadway_display_consume_all_input (GdkDisplay *display)
545 {
546   GdkBroadwayDisplay *broadway_display;
547
548   broadway_display = GDK_BROADWAY_DISPLAY (display);
549   _gdk_broadway_display_read_all_input_nonblocking (display);
550
551   /* Since we're parsing input but not processing the resulting messages
552      we might not get a readable callback on the stream, so queue an idle to
553      process the messages */
554   queue_process_input_at_idle (broadway_display);
555 }
556
557
558 static gboolean
559 input_data_cb (GObject  *stream,
560                BroadwayInput *input)
561 {
562   GdkBroadwayDisplay *broadway_display;
563
564   broadway_display = GDK_BROADWAY_DISPLAY (input->display);
565   _gdk_broadway_display_read_all_input_nonblocking (input->display);
566
567   process_input_messages (broadway_display);
568
569   return TRUE;
570 }
571
572 /* Note: This may be called while handling a message (i.e. sorta recursively) */
573 BroadwayInputMsg *
574 _gdk_broadway_display_block_for_input (GdkDisplay *display, char op,
575                                        guint32 serial, gboolean remove_message)
576 {
577   GdkBroadwayDisplay *broadway_display;
578   BroadwayInputMsg *message;
579   gssize res;
580   guint8 buffer[1024];
581   BroadwayInput *input;
582   GInputStream *in;
583   GList *l;
584
585   gdk_display_flush (display);
586
587   broadway_display = GDK_BROADWAY_DISPLAY (display);
588   if (broadway_display->input == NULL)
589     return NULL;
590
591   input = broadway_display->input;
592
593   while (TRUE) {
594     /* Check for existing reply in queue */
595
596     for (l = broadway_display->input_messages; l != NULL; l = l->next)
597       {
598         message = l->data;
599
600         if (message->base.type == op)
601           {
602             if (message->base.serial == serial)
603               {
604                 if (remove_message)
605                   broadway_display->input_messages =
606                     g_list_delete_link (broadway_display->input_messages, l);
607                 return message;
608               }
609           }
610       }
611
612     /* Not found, read more, blocking */
613
614     in = g_io_stream_get_input_stream (G_IO_STREAM (input->connection));
615     res = g_input_stream_read (in, buffer, sizeof (buffer), NULL, NULL);
616     if (res <= 0)
617       return NULL;
618     g_byte_array_append (input->buffer, buffer, res);
619
620     parse_input (input);
621
622     /* Since we're parsing input but not processing the resulting messages
623        we might not get a readable callback on the stream, so queue an idle to
624        process the messages */
625     queue_process_input_at_idle (broadway_display);
626   }
627 }
628
629 static char *
630 parse_line (char *line, char *key)
631 {
632   char *p;
633
634   if (!g_str_has_prefix (line, key))
635     return NULL;
636   p = line + strlen (key);
637   if (*p != ':')
638     return NULL;
639   p++;
640   /* Skip optional initial space */
641   if (*p == ' ')
642     p++;
643   return p;
644 }
645 static void
646 send_error (HttpRequest *request,
647             int error_code,
648             const char *reason)
649 {
650   char *res;
651
652   res = g_strdup_printf ("HTTP/1.0 %d %s\r\n\r\n"
653                          "<html><head><title>%d %s</title></head>"
654                          "<body>%s</body></html>",
655                          error_code, reason,
656                          error_code, reason,
657                          reason);
658   /* TODO: This should really be async */
659   g_output_stream_write_all (g_io_stream_get_output_stream (G_IO_STREAM (request->connection)),
660                              res, strlen (res), NULL, NULL, NULL);
661   g_free (res);
662   http_request_free (request);
663 }
664
665 /* magic from: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17 */
666 #define SEC_WEB_SOCKET_KEY_MAGIC "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
667
668 /* 'x3JJHMbDL1EzLkh9GBhXDw==' generates 'HSmrc0sMlYUkAGmm5OPpG2HaGWk=' */
669 static gchar *
670 generate_handshake_response_wsietf_v7 (const gchar *key)
671 {
672   gsize digest_len = 20;
673   guchar digest[digest_len];
674   GChecksum *checksum;
675
676   checksum = g_checksum_new (G_CHECKSUM_SHA1);
677   if (!checksum)
678     return NULL;
679
680   g_checksum_update (checksum, (guchar *)key, -1);
681   g_checksum_update (checksum, (guchar *)SEC_WEB_SOCKET_KEY_MAGIC, -1);
682
683   g_checksum_get_digest (checksum, digest, &digest_len);
684   g_checksum_free (checksum);
685
686   g_assert (digest_len == 20);
687
688   return g_base64_encode (digest, digest_len);
689 }
690
691 static void
692 start_input (HttpRequest *request)
693 {
694   char **lines;
695   char *p;
696   int num_key1, num_key2;
697   guint64 key1, key2;
698   int num_space;
699   int i;
700   guint8 challenge[16];
701   char *res;
702   gsize len;
703   GChecksum *checksum;
704   char *origin, *host;
705   GdkBroadwayDisplay *broadway_display;
706   BroadwayInput *input;
707   const void *data_buffer;
708   gsize data_buffer_size;
709   GInputStream *in;
710   char *key_v7;
711   gboolean proto_v7_plus;
712
713   broadway_display = GDK_BROADWAY_DISPLAY (request->display);
714
715   if (broadway_display->input != NULL)
716     {
717       send_error (request, 409, "Input already handled");
718       return;
719     }
720
721 #ifdef DEBUG_WEBSOCKETS
722   g_print ("incoming request:\n%s\n", request->request->str);
723 #endif
724   lines = g_strsplit (request->request->str, "\n", 0);
725
726   num_key1 = 0;
727   num_key2 = 0;
728   key1 = 0;
729   key2 = 0;
730   key_v7 = NULL;
731   origin = NULL;
732   host = NULL;
733   for (i = 0; lines[i] != NULL; i++)
734     {
735       if ((p = parse_line (lines[i], "Sec-WebSocket-Key1")))
736         {
737           num_space = 0;
738           while (*p != 0)
739             {
740               if (g_ascii_isdigit (*p))
741                 key1 = key1 * 10 + g_ascii_digit_value (*p);
742               else if (*p == ' ')
743                 num_space++;
744
745               p++;
746             }
747           key1 /= num_space;
748           num_key1++;
749         }
750       else if ((p = parse_line (lines[i], "Sec-WebSocket-Key2")))
751         {
752           num_space = 0;
753           while (*p != 0)
754             {
755               if (g_ascii_isdigit (*p))
756                 key2 = key2 * 10 + g_ascii_digit_value (*p);
757               else if (*p == ' ')
758                 num_space++;
759
760               p++;
761             }
762           key2 /= num_space;
763           num_key2++;
764         }
765       else if ((p = parse_line (lines[i], "Sec-WebSocket-Key")))
766         {
767           key_v7 = p;
768         }
769       else if ((p = parse_line (lines[i], "Origin")))
770         {
771           origin = p;
772         }
773       else if ((p = parse_line (lines[i], "Host")))
774         {
775           host = p;
776         }
777       else if ((p = parse_line (lines[i], "Sec-WebSocket-Origin")))
778         {
779           origin = p;
780         }
781     }
782
783   if (origin == NULL || host == NULL)
784     {
785       g_strfreev (lines);
786       send_error (request, 400, "Bad websocket request");
787       return;
788     }
789
790   if (key_v7 != NULL)
791     {
792       char* accept = generate_handshake_response_wsietf_v7 (key_v7);
793       res = g_strdup_printf ("HTTP/1.1 101 Switching Protocols\r\n"
794                              "Upgrade: websocket\r\n"
795                              "Connection: Upgrade\r\n"
796                              "Sec-WebSocket-Accept: %s\r\n"
797                              "Sec-WebSocket-Origin: %s\r\n"
798                              "Sec-WebSocket-Location: ws://%s/socket\r\n"
799                              "Sec-WebSocket-Protocol: broadway\r\n"
800                              "\r\n", accept, origin, host);
801       g_free (accept);
802
803 #ifdef DEBUG_WEBSOCKETS
804       g_print ("v7 proto response:\n%s", res);
805 #endif
806
807       g_output_stream_write_all (g_io_stream_get_output_stream (G_IO_STREAM (request->connection)),
808                                  res, strlen (res), NULL, NULL, NULL);
809       g_free (res);
810       proto_v7_plus = TRUE;
811     }
812   else
813     {
814       if (num_key1 != 1 || num_key2 != 1)
815         {
816           g_strfreev (lines);
817           send_error (request, 400, "Bad websocket request");
818           return;
819         }
820
821       challenge[0] = (key1 >> 24) & 0xff;
822       challenge[1] = (key1 >> 16) & 0xff;
823       challenge[2] = (key1 >>  8) & 0xff;
824       challenge[3] = (key1 >>  0) & 0xff;
825       challenge[4] = (key2 >> 24) & 0xff;
826       challenge[5] = (key2 >> 16) & 0xff;
827       challenge[6] = (key2 >>  8) & 0xff;
828       challenge[7] = (key2 >>  0) & 0xff;
829
830       if (!g_input_stream_read_all (G_INPUT_STREAM (request->data), challenge+8, 8, NULL, NULL, NULL))
831         {
832           g_strfreev (lines);
833           send_error (request, 400, "Bad websocket request");
834           return;
835         }
836
837       checksum = g_checksum_new (G_CHECKSUM_MD5);
838       g_checksum_update (checksum, challenge, 16);
839       len = 16;
840       g_checksum_get_digest (checksum, challenge, &len);
841       g_checksum_free (checksum);
842
843       res = g_strdup_printf ("HTTP/1.1 101 WebSocket Protocol Handshake\r\n"
844                              "Upgrade: WebSocket\r\n"
845                              "Connection: Upgrade\r\n"
846                              "Sec-WebSocket-Origin: %s\r\n"
847                              "Sec-WebSocket-Location: ws://%s/socket\r\n"
848                              "Sec-WebSocket-Protocol: broadway\r\n"
849                              "\r\n",
850                              origin, host);
851
852 #ifdef DEBUG_WEBSOCKETS
853       g_print ("legacy response:\n%s", res);
854 #endif
855       g_output_stream_write_all (g_io_stream_get_output_stream (G_IO_STREAM (request->connection)),
856                                  res, strlen (res), NULL, NULL, NULL);
857       g_free (res);
858       g_output_stream_write_all (g_io_stream_get_output_stream (G_IO_STREAM (request->connection)),
859                                  challenge, 16, NULL, NULL, NULL);
860       proto_v7_plus = FALSE;
861     }
862
863   input = g_new0 (BroadwayInput, 1);
864
865   input->display = request->display;
866   input->connection = g_object_ref (request->connection);
867   input->proto_v7_plus = proto_v7_plus;
868
869   data_buffer = g_buffered_input_stream_peek_buffer (G_BUFFERED_INPUT_STREAM (request->data), &data_buffer_size);
870   input->buffer = g_byte_array_sized_new (data_buffer_size);
871   g_byte_array_append (input->buffer, data_buffer, data_buffer_size);
872
873   broadway_display->input = input;
874
875   start_output (request, proto_v7_plus);
876
877   /* This will free and close the data input stream, but we got all the buffered content already */
878   http_request_free (request);
879
880   in = g_io_stream_get_input_stream (G_IO_STREAM (input->connection));
881   input->source = g_pollable_input_stream_create_source (G_POLLABLE_INPUT_STREAM (in), NULL);
882   g_source_set_callback (input->source, (GSourceFunc)input_data_cb, input, NULL);
883   g_source_attach (input->source, NULL);
884
885   /* Process any data in the pipe already */
886   parse_input (input);
887   process_input_messages (broadway_display);
888
889   g_strfreev (lines);
890 }
891
892 static void
893 start_output (HttpRequest *request, gboolean proto_v7_plus)
894 {
895   GSocket *socket;
896   GdkBroadwayDisplay *broadway_display;
897   int flag = 1;
898
899   socket = g_socket_connection_get_socket (request->connection);
900   setsockopt(g_socket_get_fd (socket), IPPROTO_TCP,
901              TCP_NODELAY, (char *) &flag, sizeof(int));
902
903   broadway_display = GDK_BROADWAY_DISPLAY (request->display);
904
905   if (broadway_display->output)
906     {
907       broadway_display->saved_serial = broadway_output_get_next_serial (broadway_display->output);
908       broadway_output_free (broadway_display->output);
909     }
910
911   broadway_display->output =
912     broadway_output_new (g_io_stream_get_output_stream (G_IO_STREAM (request->connection)),
913                          broadway_display->saved_serial, proto_v7_plus);
914
915   _gdk_broadway_resync_windows ();
916
917   if (broadway_display->pointer_grab_window)
918     broadway_output_grab_pointer (broadway_display->output,
919                                   GDK_WINDOW_IMPL_BROADWAY (broadway_display->pointer_grab_window->impl)->id,
920                                   broadway_display->pointer_grab_owner_events);
921 }
922
923 static void
924 send_data (HttpRequest *request,
925              const char *mimetype,
926              const char *data, gsize len)
927 {
928   char *res;
929
930   res = g_strdup_printf ("HTTP/1.0 200 OK\r\n"
931                          "Content-Type: %s\r\n"
932                          "Content-Length: %"G_GSIZE_FORMAT"\r\n"
933                          "\r\n",
934                          mimetype, len);
935   /* TODO: This should really be async */
936   g_output_stream_write_all (g_io_stream_get_output_stream (G_IO_STREAM (request->connection)),
937                              res, strlen (res), NULL, NULL, NULL);
938   g_free (res);
939   g_output_stream_write_all (g_io_stream_get_output_stream (G_IO_STREAM (request->connection)),
940                              data, len, NULL, NULL, NULL);
941   http_request_free (request);
942 }
943
944 #include "clienthtml.h"
945 #include "broadwayjs.h"
946
947 static void
948 got_request (HttpRequest *request)
949 {
950   char *start, *escaped, *tmp, *version, *query;
951
952   if (!g_str_has_prefix (request->request->str, "GET "))
953     {
954       send_error (request, 501, "Only GET implemented");
955       return;
956     }
957
958   start = request->request->str + 4; /* Skip "GET " */
959
960   while (*start == ' ')
961     start++;
962
963   for (tmp = start; *tmp != 0 && *tmp != ' ' && *tmp != '\n'; tmp++)
964     ;
965   escaped = g_strndup (start, tmp - start);
966   version = NULL;
967   if (*tmp == ' ')
968     {
969       start = tmp;
970       while (*start == ' ')
971         start++;
972       for (tmp = start; *tmp != 0 && *tmp != ' ' && *tmp != '\n'; tmp++)
973         ;
974       version = g_strndup (start, tmp - start);
975     }
976
977   query = strchr (escaped, '?');
978   if (query)
979     *query = 0;
980
981   if (strcmp (escaped, "/client.html") == 0 || strcmp (escaped, "/") == 0)
982     send_data (request, "text/html", client_html, G_N_ELEMENTS(client_html) - 1);
983   else if (strcmp (escaped, "/broadway.js") == 0)
984     send_data (request, "text/javascript", broadway_js, G_N_ELEMENTS(broadway_js) - 1);
985   else if (strcmp (escaped, "/socket") == 0)
986     start_input (request);
987   else
988     send_error (request, 404, "File not found");
989
990   g_free (escaped);
991   g_free (version);
992 }
993
994 static void
995 got_http_request_line (GInputStream *stream,
996                        GAsyncResult *result,
997                        HttpRequest *request)
998 {
999   char *line;
1000
1001   line = g_data_input_stream_read_line_finish (G_DATA_INPUT_STREAM (stream), result, NULL, NULL);
1002   if (line == NULL)
1003     {
1004       http_request_free (request);
1005       g_printerr ("Error reading request lines\n");
1006       return;
1007     }
1008   if (strlen (line) == 0)
1009     got_request (request);
1010   else
1011     {
1012       /* Protect against overflow in request length */
1013       if (request->request->len > 1024 * 5)
1014         {
1015           send_error (request, 400, "Request to long");
1016         }
1017       else
1018         {
1019           g_string_append_printf (request->request, "%s\n", line);
1020           g_data_input_stream_read_line_async (request->data, 0, NULL,
1021                                                (GAsyncReadyCallback)got_http_request_line, request);
1022         }
1023     }
1024   g_free (line);
1025 }
1026
1027 static gboolean
1028 handle_incoming_connection (GSocketService    *service,
1029                             GSocketConnection *connection,
1030                             GObject           *source_object)
1031 {
1032   HttpRequest *request;
1033   GInputStream *in;
1034
1035   request = g_new0 (HttpRequest, 1);
1036   request->connection = g_object_ref (connection);
1037   request->display = (GdkDisplay *) source_object;
1038   request->request = g_string_new ("");
1039
1040   in = g_io_stream_get_input_stream (G_IO_STREAM (connection));
1041
1042   request->data = g_data_input_stream_new (in);
1043   g_filter_input_stream_set_close_base_stream (G_FILTER_INPUT_STREAM (request->data), FALSE);
1044   /* Be tolerant of input */
1045   g_data_input_stream_set_newline_type (request->data, G_DATA_STREAM_NEWLINE_TYPE_ANY);
1046
1047   g_data_input_stream_read_line_async (request->data, 0, NULL,
1048                                        (GAsyncReadyCallback)got_http_request_line, request);
1049   return TRUE;
1050 }
1051
1052 GdkDisplay *
1053 _gdk_broadway_display_open (const gchar *display_name)
1054 {
1055   GdkDisplay *display;
1056   GdkBroadwayDisplay *broadway_display;
1057   GError *error;
1058   int port;
1059
1060   display = g_object_new (GDK_TYPE_BROADWAY_DISPLAY, NULL);
1061   broadway_display = GDK_BROADWAY_DISPLAY (display);
1062
1063   broadway_display->output = NULL;
1064
1065   /* initialize the display's screens */
1066   broadway_display->screens = g_new (GdkScreen *, 1);
1067   broadway_display->screens[0] = _gdk_broadway_screen_new (display, 0);
1068
1069   /* We need to initialize events after we have the screen
1070    * structures in places
1071    */
1072   _gdk_broadway_screen_events_init (broadway_display->screens[0]);
1073
1074   /*set the default screen */
1075   broadway_display->default_screen = broadway_display->screens[0];
1076
1077   display->device_manager = _gdk_broadway_device_manager_new (display);
1078
1079   gdk_event_init (display);
1080
1081   gdk_broadway_display_init_input (display);
1082   _gdk_broadway_display_init_dnd (display);
1083
1084   _gdk_broadway_screen_setup (broadway_display->screens[0]);
1085
1086   if (display_name == NULL)
1087     display_name = g_getenv ("BROADWAY_DISPLAY");
1088
1089   port = 0;
1090   if (display_name != NULL)
1091     port = strtol(display_name, NULL, 10);
1092   if (port == 0)
1093     port = 8080;
1094
1095   broadway_display->service = g_socket_service_new ();
1096   if (!g_socket_listener_add_inet_port (G_SOCKET_LISTENER (broadway_display->service),
1097                                         port,
1098                                         G_OBJECT (display),
1099                                         &error))
1100     {
1101       g_printerr ("Unable to listen to port %d: %s\n", 8080, error->message);
1102       g_error_free (error);
1103       return NULL;
1104     }
1105   g_signal_connect (broadway_display->service, "incoming", G_CALLBACK (handle_incoming_connection), NULL);
1106
1107   g_signal_emit_by_name (display, "opened");
1108   g_signal_emit_by_name (gdk_display_manager_get (), "display-opened", display);
1109
1110   return display;
1111 }
1112
1113
1114 static const gchar *
1115 gdk_broadway_display_get_name (GdkDisplay *display)
1116 {
1117   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
1118
1119   return (gchar *) "Broadway";
1120 }
1121
1122 static gint
1123 gdk_broadway_display_get_n_screens (GdkDisplay *display)
1124 {
1125   g_return_val_if_fail (GDK_IS_DISPLAY (display), 0);
1126
1127   return 1;
1128 }
1129
1130 static GdkScreen *
1131 gdk_broadway_display_get_screen (GdkDisplay *display,
1132                                  gint        screen_num)
1133 {
1134   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
1135   g_return_val_if_fail (screen_num == 0, NULL);
1136
1137   return GDK_BROADWAY_DISPLAY (display)->screens[screen_num];
1138 }
1139
1140 static GdkScreen *
1141 gdk_broadway_display_get_default_screen (GdkDisplay *display)
1142 {
1143   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
1144
1145   return GDK_BROADWAY_DISPLAY (display)->default_screen;
1146 }
1147
1148 static void
1149 gdk_broadway_display_beep (GdkDisplay *display)
1150 {
1151   g_return_if_fail (GDK_IS_DISPLAY (display));
1152 }
1153
1154 static void
1155 gdk_broadway_display_sync (GdkDisplay *display)
1156 {
1157   g_return_if_fail (GDK_IS_DISPLAY (display));
1158
1159 }
1160
1161 static void
1162 gdk_broadway_display_flush (GdkDisplay *display)
1163 {
1164   GdkBroadwayDisplay *broadway_display = GDK_BROADWAY_DISPLAY (display);
1165
1166   g_return_if_fail (GDK_IS_DISPLAY (display));
1167
1168   if (broadway_display->output &&
1169       !broadway_output_flush (broadway_display->output))
1170     {
1171       broadway_display->saved_serial = broadway_output_get_next_serial (broadway_display->output);
1172       broadway_output_free (broadway_display->output);
1173       broadway_display->output = NULL;
1174     }
1175 }
1176
1177 static gboolean
1178 gdk_broadway_display_has_pending (GdkDisplay *display)
1179 {
1180   return FALSE;
1181 }
1182
1183 static GdkWindow *
1184 gdk_broadway_display_get_default_group (GdkDisplay *display)
1185 {
1186   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
1187
1188   return NULL;
1189 }
1190
1191 static void
1192 gdk_broadway_display_dispose (GObject *object)
1193 {
1194   GdkBroadwayDisplay *broadway_display = GDK_BROADWAY_DISPLAY (object);
1195
1196   _gdk_broadway_display_manager_remove_display (gdk_display_manager_get (),
1197                                                 GDK_DISPLAY_OBJECT (object));
1198
1199   g_list_foreach (broadway_display->input_devices, (GFunc) g_object_run_dispose, NULL);
1200
1201   _gdk_screen_close (broadway_display->screens[0]);
1202
1203   if (broadway_display->event_source)
1204     {
1205       g_source_destroy (broadway_display->event_source);
1206       g_source_unref (broadway_display->event_source);
1207       broadway_display->event_source = NULL;
1208     }
1209
1210   G_OBJECT_CLASS (gdk_broadway_display_parent_class)->dispose (object);
1211 }
1212
1213 static void
1214 gdk_broadway_display_finalize (GObject *object)
1215 {
1216   GdkBroadwayDisplay *broadway_display = GDK_BROADWAY_DISPLAY (object);
1217
1218   /* Keymap */
1219   if (broadway_display->keymap)
1220     g_object_unref (broadway_display->keymap);
1221
1222   _gdk_broadway_cursor_display_finalize (GDK_DISPLAY_OBJECT(broadway_display));
1223
1224   /* input GdkDevice list */
1225   g_list_free_full (broadway_display->input_devices, g_object_unref);
1226   /* Free all GdkScreens */
1227   g_object_unref (broadway_display->screens[0]);
1228   g_free (broadway_display->screens);
1229
1230   G_OBJECT_CLASS (gdk_broadway_display_parent_class)->finalize (object);
1231 }
1232
1233 void
1234 _gdk_broadway_display_make_default (GdkDisplay *display)
1235 {
1236 }
1237
1238 static void
1239 gdk_broadway_display_notify_startup_complete (GdkDisplay  *display,
1240                                               const gchar *startup_id)
1241 {
1242 }
1243
1244 static gboolean
1245 gdk_broadway_display_supports_selection_notification (GdkDisplay *display)
1246 {
1247   return FALSE;
1248 }
1249
1250 static gboolean
1251 gdk_broadway_display_request_selection_notification (GdkDisplay *display,
1252                                                      GdkAtom     selection)
1253
1254 {
1255     return FALSE;
1256 }
1257
1258 static gboolean
1259 gdk_broadway_display_supports_clipboard_persistence (GdkDisplay *display)
1260 {
1261   return FALSE;
1262 }
1263
1264 static void
1265 gdk_broadway_display_store_clipboard (GdkDisplay    *display,
1266                                       GdkWindow     *clipboard_window,
1267                                       guint32        time_,
1268                                       const GdkAtom *targets,
1269                                       gint           n_targets)
1270 {
1271 }
1272
1273 static gboolean
1274 gdk_broadway_display_supports_shapes (GdkDisplay *display)
1275 {
1276   return FALSE;
1277 }
1278
1279 static gboolean
1280 gdk_broadway_display_supports_input_shapes (GdkDisplay *display)
1281 {
1282   return FALSE;
1283 }
1284
1285 static gboolean
1286 gdk_broadway_display_supports_composite (GdkDisplay *display)
1287 {
1288   return FALSE;
1289 }
1290
1291 static GList *
1292 gdk_broadway_display_list_devices (GdkDisplay *display)
1293 {
1294   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
1295
1296   return GDK_BROADWAY_DISPLAY (display)->input_devices;
1297 }
1298
1299 static gulong
1300 gdk_broadway_display_get_next_serial (GdkDisplay *display)
1301 {
1302   GdkBroadwayDisplay *broadway_display;
1303   broadway_display = GDK_BROADWAY_DISPLAY (display);
1304   if (broadway_display->output)
1305     return broadway_output_get_next_serial (broadway_display->output);
1306   return broadway_display->saved_serial;
1307 }
1308
1309
1310 static void
1311 gdk_broadway_display_event_data_copy (GdkDisplay    *display,
1312                                       const GdkEvent *src,
1313                                       GdkEvent       *dst)
1314 {
1315 }
1316
1317 static void
1318 gdk_broadway_display_event_data_free (GdkDisplay    *display,
1319                                       GdkEvent *event)
1320 {
1321 }
1322
1323 static void
1324 gdk_broadway_display_class_init (GdkBroadwayDisplayClass * class)
1325 {
1326   GObjectClass *object_class = G_OBJECT_CLASS (class);
1327   GdkDisplayClass *display_class = GDK_DISPLAY_CLASS (class);
1328
1329   object_class->dispose = gdk_broadway_display_dispose;
1330   object_class->finalize = gdk_broadway_display_finalize;
1331
1332   display_class->window_type = GDK_TYPE_BROADWAY_WINDOW;
1333
1334   display_class->get_name = gdk_broadway_display_get_name;
1335   display_class->get_n_screens = gdk_broadway_display_get_n_screens;
1336   display_class->get_screen = gdk_broadway_display_get_screen;
1337   display_class->get_default_screen = gdk_broadway_display_get_default_screen;
1338   display_class->beep = gdk_broadway_display_beep;
1339   display_class->sync = gdk_broadway_display_sync;
1340   display_class->flush = gdk_broadway_display_flush;
1341   display_class->has_pending = gdk_broadway_display_has_pending;
1342   display_class->queue_events = _gdk_broadway_display_queue_events;
1343   display_class->get_default_group = gdk_broadway_display_get_default_group;
1344   display_class->supports_selection_notification = gdk_broadway_display_supports_selection_notification;
1345   display_class->request_selection_notification = gdk_broadway_display_request_selection_notification;
1346   display_class->supports_clipboard_persistence = gdk_broadway_display_supports_clipboard_persistence;
1347   display_class->store_clipboard = gdk_broadway_display_store_clipboard;
1348   display_class->supports_shapes = gdk_broadway_display_supports_shapes;
1349   display_class->supports_input_shapes = gdk_broadway_display_supports_input_shapes;
1350   display_class->supports_composite = gdk_broadway_display_supports_composite;
1351   display_class->list_devices = gdk_broadway_display_list_devices;
1352   display_class->get_cursor_for_type = _gdk_broadway_display_get_cursor_for_type;
1353   display_class->get_cursor_for_name = _gdk_broadway_display_get_cursor_for_name;
1354   display_class->get_cursor_for_pixbuf = _gdk_broadway_display_get_cursor_for_pixbuf;
1355   display_class->get_default_cursor_size = _gdk_broadway_display_get_default_cursor_size;
1356   display_class->get_maximal_cursor_size = _gdk_broadway_display_get_maximal_cursor_size;
1357   display_class->supports_cursor_alpha = _gdk_broadway_display_supports_cursor_alpha;
1358   display_class->supports_cursor_color = _gdk_broadway_display_supports_cursor_color;
1359
1360   display_class->before_process_all_updates = _gdk_broadway_display_before_process_all_updates;
1361   display_class->after_process_all_updates = _gdk_broadway_display_after_process_all_updates;
1362   display_class->get_next_serial = gdk_broadway_display_get_next_serial;
1363   display_class->notify_startup_complete = gdk_broadway_display_notify_startup_complete;
1364   display_class->event_data_copy = gdk_broadway_display_event_data_copy;
1365   display_class->event_data_free = gdk_broadway_display_event_data_free;
1366   display_class->create_window_impl = _gdk_broadway_display_create_window_impl;
1367   display_class->get_keymap = _gdk_broadway_display_get_keymap;
1368   display_class->get_selection_owner = _gdk_broadway_display_get_selection_owner;
1369   display_class->set_selection_owner = _gdk_broadway_display_set_selection_owner;
1370   display_class->send_selection_notify = _gdk_broadway_display_send_selection_notify;
1371   display_class->get_selection_property = _gdk_broadway_display_get_selection_property;
1372   display_class->convert_selection = _gdk_broadway_display_convert_selection;
1373   display_class->text_property_to_utf8_list = _gdk_broadway_display_text_property_to_utf8_list;
1374   display_class->utf8_to_string_target = _gdk_broadway_display_utf8_to_string_target;
1375 }
1376