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