bus: Assign a serial number for messages from the driver
[platform/upstream/dbus.git] / test / corrupt.c
1 /* Regression test for being disconnected by a corrupt message (fd.o #15578)
2  *
3  * Author: Simon McVittie <simon.mcvittie@collabora.co.uk>
4  * Copyright © 2010-2011 Nokia Corporation
5  *
6  * Permission is hereby granted, free of charge, to any person
7  * obtaining a copy of this software and associated documentation files
8  * (the "Software"), to deal in the Software without restriction,
9  * including without limitation the rights to use, copy, modify, merge,
10  * publish, distribute, sublicense, and/or sell copies of the Software,
11  * and to permit persons to whom the Software is furnished to do so,
12  * subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
21  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24  * SOFTWARE.
25  */
26
27 #include <config.h>
28
29 #include <glib.h>
30 #include <gio/gio.h>
31
32 #include <dbus/dbus.h>
33
34 #include "test-utils-glib.h"
35
36 typedef struct {
37     DBusError e;
38     TestMainContext *ctx;
39     gboolean skip;
40
41     DBusServer *server;
42     DBusConnection *server_conn;
43     /* queue of DBusMessage */
44     GQueue client_messages;
45
46     DBusConnection *client_conn;
47 } Fixture;
48
49 static void
50 assert_no_error (const DBusError *e)
51 {
52   if (G_UNLIKELY (dbus_error_is_set (e)))
53     g_error ("expected success but got error: %s: %s", e->name, e->message);
54 }
55
56 static DBusHandlerResult
57 client_message_cb (DBusConnection *client_conn,
58     DBusMessage *message,
59     void *data)
60 {
61   Fixture *f = data;
62
63   g_assert (client_conn == f->client_conn);
64   g_queue_push_tail (&f->client_messages, dbus_message_ref (message));
65
66   return DBUS_HANDLER_RESULT_HANDLED;
67 }
68
69 static void
70 new_conn_cb (DBusServer *server,
71     DBusConnection *server_conn,
72     void *data)
73 {
74   Fixture *f = data;
75
76   g_assert (f->server_conn == NULL);
77   f->server_conn = dbus_connection_ref (server_conn);
78   test_connection_setup (f->ctx, server_conn);
79 }
80
81 static void
82 setup (Fixture *f,
83     gconstpointer addr)
84 {
85   f->ctx = test_main_context_get ();
86   dbus_error_init (&f->e);
87   g_queue_init (&f->client_messages);
88
89   if ((g_str_has_prefix (addr, "tcp:") ||
90        g_str_has_prefix (addr, "nonce-tcp:")) &&
91       !test_check_tcp_works ())
92     {
93       f->skip = TRUE;
94       return;
95     }
96
97   f->server = dbus_server_listen (addr, &f->e);
98   assert_no_error (&f->e);
99   g_assert (f->server != NULL);
100
101   dbus_server_set_new_connection_function (f->server,
102       new_conn_cb, f, NULL);
103   test_server_setup (f->ctx, f->server);
104 }
105
106 static void
107 test_connect (Fixture *f,
108     gconstpointer addr G_GNUC_UNUSED)
109 {
110   dbus_bool_t have_mem;
111   char *address = NULL;
112
113   if (f->skip)
114     return;
115
116   g_assert (f->server_conn == NULL);
117
118   address = dbus_server_get_address (f->server);
119   f->client_conn = dbus_connection_open_private (address, &f->e);
120   assert_no_error (&f->e);
121   g_assert (f->client_conn != NULL);
122   test_connection_setup (f->ctx, f->client_conn);
123   dbus_free (address);
124
125   while (f->server_conn == NULL)
126     {
127       test_progress ('.');
128       test_main_context_iterate (f->ctx, TRUE);
129     }
130
131   have_mem = dbus_connection_add_filter (f->client_conn,
132       client_message_cb, f, NULL);
133   g_assert (have_mem);
134 }
135
136 static void
137 test_message (Fixture *f,
138     gconstpointer addr)
139 {
140   dbus_bool_t have_mem;
141   dbus_uint32_t serial;
142   DBusMessage *outgoing, *incoming;
143
144   if (f->skip)
145     return;
146
147   test_connect (f, addr);
148
149   outgoing = dbus_message_new_signal ("/com/example/Hello",
150       "com.example.Hello", "Greeting");
151   g_assert (outgoing != NULL);
152
153   have_mem = dbus_connection_send (f->server_conn, outgoing, &serial);
154   g_assert (have_mem);
155   g_assert (serial != 0);
156
157   while (g_queue_is_empty (&f->client_messages))
158     {
159       test_progress ('.');
160       test_main_context_iterate (f->ctx, TRUE);
161     }
162
163   g_assert_cmpuint (g_queue_get_length (&f->client_messages), ==, 1);
164
165   incoming = g_queue_pop_head (&f->client_messages);
166
167   g_assert (!dbus_message_contains_unix_fds (incoming));
168   g_assert_cmpstr (dbus_message_get_destination (incoming), ==, NULL);
169   g_assert_cmpstr (dbus_message_get_error_name (incoming), ==, NULL);
170   g_assert_cmpstr (dbus_message_get_interface (incoming), ==,
171       "com.example.Hello");
172   g_assert_cmpstr (dbus_message_get_member (incoming), ==, "Greeting");
173   g_assert_cmpstr (dbus_message_get_sender (incoming), ==, NULL);
174   g_assert_cmpstr (dbus_message_get_signature (incoming), ==, "");
175   g_assert_cmpstr (dbus_message_get_path (incoming), ==, "/com/example/Hello");
176   g_assert_cmpuint (dbus_message_get_serial (incoming), ==, serial);
177
178   dbus_message_unref (incoming);
179
180   dbus_message_unref (outgoing);
181 }
182
183 static void
184 send_n_bytes (GSocket *socket,
185               const gchar *blob,
186               gssize blob_len)
187 {
188   gssize len, total_sent;
189   GError *gerror = NULL;
190
191   total_sent = 0;
192
193   while (total_sent < blob_len)
194     {
195       len = g_socket_send (socket,
196                            blob + total_sent,
197                            blob_len - total_sent,
198                            NULL, &gerror);
199
200       /* this is NULL-safe: a NULL error does not match */
201       if (g_error_matches (gerror, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
202         {
203           /* we could wait for G_IO_OUT, but life's too short; just sleep */
204           g_clear_error (&gerror);
205           g_usleep (G_USEC_PER_SEC / 10);
206           continue;
207         }
208
209       g_assert_no_error (gerror);
210       g_assert (len >= 0);
211       total_sent += len;
212     }
213 }
214
215 /* Enough bytes for it to be obvious that this connection is broken */
216 #define CORRUPT_LEN 1024
217
218 /* All-zero is not a valid D-Bus message header - for a start, this is
219  * protocol version 1, not 0 */
220 static const gchar not_a_dbus_message[CORRUPT_LEN] = { 0 };
221
222 static void
223 test_corrupt (Fixture *f,
224     gconstpointer addr)
225 {
226   GSocket *socket;
227   GError *gerror = NULL;
228   int fd;
229   DBusMessage *incoming;
230
231   if (f->skip)
232     return;
233
234   test_message (f, addr);
235
236   dbus_connection_flush (f->server_conn);
237
238   /* OK, now the connection is working, let's break it! Don't try this
239    * at home; splicing arbitrary bytes into the middle of the stream is
240    * specifically documented as not a valid thing to do. Who'd have thought? */
241   if (!dbus_connection_get_socket (f->server_conn, &fd))
242     g_error ("failed to steal fd from server connection");
243
244   socket = g_socket_new_from_fd (fd, &gerror);
245   g_assert_no_error (gerror);
246   g_assert (socket != NULL);
247
248   send_n_bytes (socket, not_a_dbus_message, CORRUPT_LEN);
249
250   /* Now spin on the client connection: the server just sent it complete
251    * rubbish, so it should disconnect */
252   while (g_queue_is_empty (&f->client_messages))
253     {
254       test_progress ('.');
255       test_main_context_iterate (f->ctx, TRUE);
256     }
257
258   incoming = g_queue_pop_head (&f->client_messages);
259
260   g_assert (!dbus_message_contains_unix_fds (incoming));
261   g_assert_cmpstr (dbus_message_get_destination (incoming), ==, NULL);
262   g_assert_cmpstr (dbus_message_get_error_name (incoming), ==, NULL);
263   g_assert_cmpstr (dbus_message_get_interface (incoming), ==,
264       "org.freedesktop.DBus.Local");
265   g_assert_cmpstr (dbus_message_get_member (incoming), ==, "Disconnected");
266   g_assert_cmpstr (dbus_message_get_sender (incoming), ==, NULL);
267   g_assert_cmpstr (dbus_message_get_signature (incoming), ==, "");
268   g_assert_cmpstr (dbus_message_get_path (incoming), ==,
269       "/org/freedesktop/DBus/Local");
270
271   dbus_message_unref (incoming);
272
273   /* Free the DBusConnection before the GSocket, because GSocket is
274    * going to close our fd. GSocket tolerates closing an already-closed
275    * fd, whereas DBusLoop + DBusSocketSetEpoll doesn't. On Unix
276    * we could use dup() but that isn't portable to Windows :-(
277    */
278   dbus_connection_close (f->server_conn);
279   dbus_connection_unref (f->server_conn);
280   f->server_conn = NULL;
281
282   g_object_unref (socket);
283 }
284
285 static void
286 test_byte_order (Fixture *f,
287     gconstpointer addr)
288 {
289   GSocket *socket;
290   GError *gerror = NULL;
291   int fd;
292   char *blob;
293   const gchar *arg = not_a_dbus_message;
294   int blob_len;
295   DBusMessage *message;
296   dbus_bool_t mem;
297
298   if (f->skip)
299     return;
300
301   test_message (f, addr);
302
303   message = dbus_message_new_signal ("/", "a.b", "c");
304   g_assert (message != NULL);
305   /* Append 0xFF bytes, so that the length of the body when byte-swapped
306    * is 0xFF000000, which is invalid */
307   mem = dbus_message_append_args (message,
308       DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &arg, 0xFF,
309       DBUS_TYPE_INVALID);
310   g_assert (mem);
311   mem = dbus_message_marshal (message, &blob, &blob_len);
312   g_assert (mem);
313   g_assert_cmpuint (blob_len, >, 0xFF);
314   g_assert (blob != NULL);
315
316   dbus_message_unref (message);
317
318   /* Break the message by changing its claimed byte order, without actually
319    * byteswapping anything. We happen to know that byte order is the first
320    * byte. */
321   if (blob[0] == 'B')
322     blob[0] = 'l';
323   else
324     blob[0] = 'B';
325
326   /* OK, now the connection is working, let's break it */
327
328   dbus_connection_flush (f->server_conn);
329
330   if (!dbus_connection_get_socket (f->server_conn, &fd))
331     g_error ("failed to steal fd from server connection");
332
333   socket = g_socket_new_from_fd (fd, &gerror);
334   g_assert_no_error (gerror);
335   g_assert (socket != NULL);
336
337   send_n_bytes (socket, blob, blob_len);
338
339   dbus_free (blob);
340
341   /* Now spin on the client connection: the server just sent it a faulty
342    * message, so it should disconnect */
343   while (g_queue_is_empty (&f->client_messages))
344     {
345       test_progress ('.');
346       test_main_context_iterate (f->ctx, TRUE);
347     }
348
349   message = g_queue_pop_head (&f->client_messages);
350
351   g_assert (!dbus_message_contains_unix_fds (message));
352   g_assert_cmpstr (dbus_message_get_destination (message), ==, NULL);
353   g_assert_cmpstr (dbus_message_get_error_name (message), ==, NULL);
354   g_assert_cmpstr (dbus_message_get_interface (message), ==,
355       "org.freedesktop.DBus.Local");
356   g_assert_cmpstr (dbus_message_get_member (message), ==, "Disconnected");
357   g_assert_cmpstr (dbus_message_get_sender (message), ==, NULL);
358   g_assert_cmpstr (dbus_message_get_signature (message), ==, "");
359   g_assert_cmpstr (dbus_message_get_path (message), ==,
360       "/org/freedesktop/DBus/Local");
361
362   dbus_message_unref (message);
363
364   /* Free the DBusConnection before the GSocket, as above. */
365   dbus_connection_close (f->server_conn);
366   dbus_connection_unref (f->server_conn);
367   f->server_conn = NULL;
368
369   g_object_unref (socket);
370 }
371
372 static void
373 teardown (Fixture *f,
374     gconstpointer addr G_GNUC_UNUSED)
375 {
376   if (f->client_conn != NULL)
377     {
378       test_connection_shutdown (f->ctx, f->client_conn);
379       dbus_connection_close (f->client_conn);
380       dbus_connection_unref (f->client_conn);
381       f->client_conn = NULL;
382     }
383
384   if (f->server_conn != NULL)
385     {
386       test_connection_shutdown (f->ctx, f->server_conn);
387       dbus_connection_close (f->server_conn);
388       dbus_connection_unref (f->server_conn);
389       f->server_conn = NULL;
390     }
391
392   if (f->server != NULL)
393     {
394       dbus_server_disconnect (f->server);
395       dbus_server_unref (f->server);
396       f->server = NULL;
397     }
398
399   test_main_context_unref (f->ctx);
400 }
401
402 int
403 main (int argc,
404     char **argv)
405 {
406   test_init (&argc, &argv);
407
408   g_test_add ("/corrupt/tcp", Fixture, "tcp:host=127.0.0.1", setup,
409       test_corrupt, teardown);
410
411 #ifdef DBUS_UNIX
412   g_test_add ("/corrupt/unix", Fixture, "unix:tmpdir=/tmp", setup,
413       test_corrupt, teardown);
414 #endif
415
416   g_test_add ("/corrupt/byte-order/tcp", Fixture, "tcp:host=127.0.0.1", setup,
417       test_byte_order, teardown);
418
419 #ifdef DBUS_UNIX
420   g_test_add ("/corrupt/byte-order/unix", Fixture, "unix:tmpdir=/tmp", setup,
421       test_byte_order, teardown);
422 #endif
423
424   return g_test_run ();
425 }