Change LGPL-2.1+ to LGPL-2.1-or-later
[platform/upstream/glib.git] / gio / tests / socket.c
1 /* GLib testing framework examples and tests
2  *
3  * Copyright (C) 2008-2011 Red Hat, Inc.
4  *
5  * SPDX-License-Identifier: LGPL-2.1-or-later
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General
18  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <gio/gio.h>
22 #include <glib/gstdio.h>
23 #include "glib-private.h"
24
25 #include <gio/gcredentialsprivate.h>
26 #include <gio/gunixconnection.h>
27
28 #ifdef G_OS_UNIX
29 #include <errno.h>
30 #include <sys/wait.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <gio/gnetworking.h>
34 #endif
35
36 #ifdef G_OS_WIN32
37 #include "giowin32-afunix.h"
38 #include <io.h>
39 #endif
40
41 #include "gnetworkingprivate.h"
42
43 static gboolean ipv6_supported;
44
45 typedef struct {
46   GSocket *server;
47   GSocket *client;
48   GSocketFamily family;
49   GThread *thread;
50   GMainLoop *loop;
51   GCancellable *cancellable; /* to shut down dgram echo server thread */
52 } IPTestData;
53
54 static gpointer
55 echo_server_dgram_thread (gpointer user_data)
56 {
57   IPTestData *data = user_data;
58   GSocketAddress *sa;
59   GCancellable *cancellable = data->cancellable;
60   GSocket *sock;
61   GError *error = NULL;
62   gssize nread, nwrote;
63   gchar buf[128];
64
65   sock = data->server;
66
67   while (TRUE)
68     {
69       nread = g_socket_receive_from (sock, &sa, buf, sizeof (buf), cancellable, &error);
70       if (error && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
71         break;
72       g_assert_no_error (error);
73       g_assert_cmpint (nread, >=, 0);
74
75       nwrote = g_socket_send_to (sock, sa, buf, nread, cancellable, &error);
76       if (error && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
77         break;
78       g_assert_no_error (error);
79       g_assert_cmpint (nwrote, ==, nread);
80
81       g_object_unref (sa);
82     }
83
84   g_clear_error (&error);
85
86   return NULL;
87 }
88
89 static gpointer
90 echo_server_thread (gpointer user_data)
91 {
92   IPTestData *data = user_data;
93   GSocket *sock;
94   GError *error = NULL;
95   gssize nread, nwrote;
96   gchar buf[128];
97
98   sock = g_socket_accept (data->server, NULL, &error);
99   g_assert_no_error (error);
100
101   while (TRUE)
102     {
103       nread = g_socket_receive (sock, buf, sizeof (buf), NULL, &error);
104       g_assert_no_error (error);
105       g_assert_cmpint (nread, >=, 0);
106
107       if (nread == 0)
108         break;
109
110       nwrote = g_socket_send (sock, buf, nread, NULL, &error);
111       g_assert_no_error (error);
112       g_assert_cmpint (nwrote, ==, nread);
113     }
114
115   g_socket_close (sock, &error);
116   g_assert_no_error (error);
117   g_object_unref (sock);
118   return NULL;
119 }
120
121 static IPTestData *
122 create_server_full (GSocketFamily   family,
123                     GSocketType     socket_type,
124                     GThreadFunc     server_thread,
125                     gboolean        v4mapped,
126                     GError        **error)
127 {
128   IPTestData *data;
129   GSocket *server;
130   GSocketAddress *addr;
131   GInetAddress *iaddr;
132
133   data = g_slice_new (IPTestData);
134   data->family = family;
135
136   data->server = server = g_socket_new (family,
137                                         socket_type,
138                                         G_SOCKET_PROTOCOL_DEFAULT,
139                                         error);
140   if (server == NULL)
141     goto error;
142
143   g_assert_cmpint (g_socket_get_family (server), ==, family);
144   g_assert_cmpint (g_socket_get_socket_type (server), ==, socket_type);
145   g_assert_cmpint (g_socket_get_protocol (server), ==, G_SOCKET_PROTOCOL_DEFAULT);
146 #ifdef G_OS_WIN32
147   g_assert (GLIB_PRIVATE_CALL (g_win32_handle_is_socket) ((HANDLE)(gintptr) g_socket_get_fd (server)));
148 #endif
149
150   g_socket_set_blocking (server, TRUE);
151
152 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
153   if (v4mapped)
154     {
155       g_socket_set_option (data->server, IPPROTO_IPV6, IPV6_V6ONLY, FALSE, NULL);
156       if (!g_socket_speaks_ipv4 (data->server))
157         {
158           g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
159                                "IPv6-only server cannot speak IPv4");
160           goto error;
161         }
162     }
163 #endif
164
165   if (v4mapped)
166     iaddr = g_inet_address_new_any (family);
167   else
168     iaddr = g_inet_address_new_loopback (family);
169   addr = g_inet_socket_address_new (iaddr, 0);
170   g_object_unref (iaddr);
171
172   g_assert_cmpint (g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr)), ==, 0);
173   if (!g_socket_bind (server, addr, TRUE, error))
174     {
175       g_object_unref (addr);
176       goto error;
177     }
178   g_object_unref (addr);
179
180   addr = g_socket_get_local_address (server, error);
181   if (addr == NULL)
182     goto error;
183   g_assert_cmpint (g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr)), !=, 0);
184   g_object_unref (addr);
185
186   if (socket_type == G_SOCKET_TYPE_STREAM)
187     {
188       if (!g_socket_listen (server, error))
189         goto error;
190     }
191   else
192     {
193       data->cancellable = g_cancellable_new ();
194     }
195
196   data->thread = g_thread_new ("server", server_thread, data);
197
198   return data;
199
200 error:
201   g_clear_object (&data->server);
202   g_slice_free (IPTestData, data);
203
204   return NULL;
205 }
206
207 static IPTestData *
208 create_server (GSocketFamily   family,
209                GThreadFunc     server_thread,
210                gboolean        v4mapped,
211                GError        **error)
212 {
213   return create_server_full (family, G_SOCKET_TYPE_STREAM, server_thread, v4mapped, error);
214 }
215
216 static const gchar *testbuf = "0123456789abcdef";
217
218 static gboolean
219 test_ip_async_read_ready (GSocket      *client,
220                           GIOCondition  cond,
221                           gpointer      user_data)
222 {
223   IPTestData *data = user_data;
224   GError *error = NULL;
225   gssize len;
226   gchar buf[128];
227
228   g_assert_cmpint (cond, ==, G_IO_IN);
229
230   len = g_socket_receive (client, buf, sizeof (buf), NULL, &error);
231   g_assert_no_error (error);
232   g_assert_cmpint (len, ==, strlen (testbuf) + 1);
233
234   g_assert_cmpstr (testbuf, ==, buf);
235
236   g_main_loop_quit (data->loop);
237
238   return FALSE;
239 }
240
241 static gboolean
242 test_ip_async_write_ready (GSocket      *client,
243                            GIOCondition  cond,
244                            gpointer      user_data)
245 {
246   IPTestData *data = user_data;
247   GError *error = NULL;
248   GSource *source;
249   gssize len;
250
251   g_assert_cmpint (cond, ==, G_IO_OUT);
252
253   len = g_socket_send (client, testbuf, strlen (testbuf) + 1, NULL, &error);
254   g_assert_no_error (error);
255   g_assert_cmpint (len, ==, strlen (testbuf) + 1);
256
257   source = g_socket_create_source (client, G_IO_IN, NULL);
258   g_source_set_callback (source, (GSourceFunc)test_ip_async_read_ready,
259                          data, NULL);
260   g_source_attach (source, NULL);
261   g_source_unref (source);
262
263   return FALSE;
264 }
265
266 static gboolean
267 test_ip_async_timed_out (GSocket      *client,
268                          GIOCondition  cond,
269                          gpointer      user_data)
270 {
271   IPTestData *data = user_data;
272   GError *error = NULL;
273   GSource *source;
274   gssize len;
275   gchar buf[128];
276
277   if (data->family == G_SOCKET_FAMILY_IPV4)
278     {
279       g_assert_cmpint (cond, ==, G_IO_IN);
280       len = g_socket_receive (client, buf, sizeof (buf), NULL, &error);
281       g_assert_cmpint (len, ==, -1);
282       g_assert_error (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT);
283       g_clear_error (&error);
284     }
285
286   source = g_socket_create_source (client, G_IO_OUT, NULL);
287   g_source_set_callback (source, (GSourceFunc)test_ip_async_write_ready,
288                          data, NULL);
289   g_source_attach (source, NULL);
290   g_source_unref (source);
291
292   return FALSE;
293 }
294
295 static gboolean
296 test_ip_async_connected (GSocket      *client,
297                          GIOCondition  cond,
298                          gpointer      user_data)
299 {
300   IPTestData *data = user_data;
301   GError *error = NULL;
302   GSource *source;
303   gssize len;
304   gchar buf[128];
305
306   g_socket_check_connect_result (client, &error);
307   g_assert_no_error (error);
308   /* We do this after the check_connect_result, since that will give a
309    * more useful assertion in case of error.
310    */
311   g_assert_cmpint (cond, ==, G_IO_OUT);
312
313   g_assert (g_socket_is_connected (client));
314
315   /* This adds 1 second to "make check", so let's just only do it once. */
316   if (data->family == G_SOCKET_FAMILY_IPV4)
317     {
318       len = g_socket_receive (client, buf, sizeof (buf), NULL, &error);
319       g_assert_cmpint (len, ==, -1);
320       g_assert_error (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK);
321       g_clear_error (&error);
322
323       source = g_socket_create_source (client, G_IO_IN, NULL);
324       g_source_set_callback (source, (GSourceFunc)test_ip_async_timed_out,
325                              data, NULL);
326       g_source_attach (source, NULL);
327       g_source_unref (source);
328     }
329   else
330     test_ip_async_timed_out (client, 0, data);
331
332   return FALSE;
333 }
334
335 static gboolean
336 idle_test_ip_async_connected (gpointer user_data)
337 {
338   IPTestData *data = user_data;
339
340   return test_ip_async_connected (data->client, G_IO_OUT, data);
341 }
342
343 static void
344 test_ip_async (GSocketFamily family)
345 {
346   IPTestData *data;
347   GError *error = NULL;
348   GSocket *client;
349   GSocketAddress *addr;
350   GSource *source;
351   gssize len;
352   gchar buf[128];
353
354   data = create_server (family, echo_server_thread, FALSE, &error);
355   if (error != NULL)
356     {
357       g_test_skip_printf ("Failed to create server: %s", error->message);
358       g_clear_error (&error);
359       return;
360     }
361   g_assert_nonnull (data);
362
363   addr = g_socket_get_local_address (data->server, &error);
364   g_assert_no_error (error);
365
366   client = g_socket_new (family,
367                          G_SOCKET_TYPE_STREAM,
368                          G_SOCKET_PROTOCOL_DEFAULT,
369                          &error);
370   g_assert_no_error (error);
371   data->client = client;
372
373   g_assert_cmpint (g_socket_get_family (client), ==, family);
374   g_assert_cmpint (g_socket_get_socket_type (client), ==, G_SOCKET_TYPE_STREAM);
375   g_assert_cmpint (g_socket_get_protocol (client), ==, G_SOCKET_PROTOCOL_DEFAULT);
376
377   g_socket_set_blocking (client, FALSE);
378   g_socket_set_timeout (client, 1);
379
380   if (g_socket_connect (client, addr, NULL, &error))
381     {
382       g_assert_no_error (error);
383       g_idle_add (idle_test_ip_async_connected, data);
384     }
385   else
386     {
387       g_assert_error (error, G_IO_ERROR, G_IO_ERROR_PENDING);
388       g_clear_error (&error);
389       source = g_socket_create_source (client, G_IO_OUT, NULL);
390       g_source_set_callback (source, (GSourceFunc)test_ip_async_connected,
391                              data, NULL);
392       g_source_attach (source, NULL);
393       g_source_unref (source);
394     }
395   g_object_unref (addr);
396
397   data->loop = g_main_loop_new (NULL, TRUE);
398   g_main_loop_run (data->loop);
399   g_main_loop_unref (data->loop);
400
401   g_socket_shutdown (client, FALSE, TRUE, &error);
402   g_assert_no_error (error);
403
404   g_thread_join (data->thread);
405
406   if (family == G_SOCKET_FAMILY_IPV4)
407     {
408       /* Test that reading on a remote-closed socket gets back 0 bytes. */
409       len = g_socket_receive_with_blocking (client, buf, sizeof (buf),
410                                             TRUE, NULL, &error);
411       g_assert_no_error (error);
412       g_assert_cmpint (len, ==, 0);
413     }
414   else
415     {
416       /* Test that writing to a remote-closed socket gets back CONNECTION_CLOSED. */
417       len = g_socket_send_with_blocking (client, testbuf, strlen (testbuf) + 1,
418                                          TRUE, NULL, &error);
419       g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CONNECTION_CLOSED);
420       g_assert_cmpint (len, ==, -1);
421       g_clear_error (&error);
422     }
423
424   g_socket_close (client, &error);
425   g_assert_no_error (error);
426   g_socket_close (data->server, &error);
427   g_assert_no_error (error);
428
429   g_object_unref (data->server);
430   g_object_unref (client);
431
432   g_slice_free (IPTestData, data);
433 }
434
435 static void
436 test_ipv4_async (void)
437 {
438   test_ip_async (G_SOCKET_FAMILY_IPV4);
439 }
440
441 static void
442 test_ipv6_async (void)
443 {
444   if (!ipv6_supported)
445     {
446       g_test_skip ("No support for IPv6");
447       return;
448     }
449
450   test_ip_async (G_SOCKET_FAMILY_IPV6);
451 }
452
453 static const gchar testbuf2[] = "0123456789abcdefghijklmnopqrstuvwxyz";
454
455 static void
456 test_ip_sync (GSocketFamily family)
457 {
458   IPTestData *data;
459   GError *error = NULL;
460   GSocket *client;
461   GSocketAddress *addr;
462   gssize len;
463   gchar buf[128];
464
465   data = create_server (family, echo_server_thread, FALSE, &error);
466   if (error != NULL)
467     {
468       g_test_skip_printf ("Failed to create server: %s", error->message);
469       g_clear_error (&error);
470       return;
471     }
472
473   addr = g_socket_get_local_address (data->server, &error);
474   g_assert_no_error (error);
475
476   client = g_socket_new (family,
477                          G_SOCKET_TYPE_STREAM,
478                          G_SOCKET_PROTOCOL_DEFAULT,
479                          &error);
480   g_assert_no_error (error);
481
482   g_assert_cmpint (g_socket_get_family (client), ==, family);
483   g_assert_cmpint (g_socket_get_socket_type (client), ==, G_SOCKET_TYPE_STREAM);
484   g_assert_cmpint (g_socket_get_protocol (client), ==, G_SOCKET_PROTOCOL_DEFAULT);
485 #ifdef G_OS_WIN32
486   g_assert (GLIB_PRIVATE_CALL (g_win32_handle_is_socket) ((HANDLE)(gintptr) g_socket_get_fd (client)));
487 #endif
488   g_socket_set_blocking (client, TRUE);
489   g_socket_set_timeout (client, 1);
490
491   g_socket_connect (client, addr, NULL, &error);
492   g_assert_no_error (error);
493   g_assert (g_socket_is_connected (client));
494   g_object_unref (addr);
495
496   /* This adds 1 second to "make check", so let's just only do it once. */
497   if (family == G_SOCKET_FAMILY_IPV4)
498     {
499       len = g_socket_receive (client, buf, sizeof (buf), NULL, &error);
500       g_assert_cmpint (len, ==, -1);
501       g_assert_error (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT);
502       g_clear_error (&error);
503     }
504
505   len = g_socket_send (client, testbuf, strlen (testbuf) + 1, NULL, &error);
506   g_assert_no_error (error);
507   g_assert_cmpint (len, ==, strlen (testbuf) + 1);
508   
509   len = g_socket_receive (client, buf, sizeof (buf), NULL, &error);
510   g_assert_no_error (error);
511   g_assert_cmpint (len, ==, strlen (testbuf) + 1);
512
513   g_assert_cmpstr (testbuf, ==, buf);
514
515   {
516     GOutputVector v[7] = { { NULL, 0 }, };
517
518     v[0].buffer = testbuf2 + 0;
519     v[0].size = 3;
520     v[1].buffer = testbuf2 + 3;
521     v[1].size = 5;
522     v[2].buffer = testbuf2 + 3 + 5;
523     v[2].size = 0;
524     v[3].buffer = testbuf2 + 3 + 5;
525     v[3].size = 6;
526     v[4].buffer = testbuf2 + 3 + 5 + 6;
527     v[4].size = 2;
528     v[5].buffer = testbuf2 + 3 + 5 + 6 + 2;
529     v[5].size = 1;
530     v[6].buffer = testbuf2 + 3 + 5 + 6 + 2 + 1;
531     v[6].size = strlen (testbuf2) - (3 + 5 + 6 + 2 + 1);
532
533     len = g_socket_send_message (client, NULL, v, G_N_ELEMENTS (v), NULL, 0, 0, NULL, &error);
534     g_assert_no_error (error);
535     g_assert_cmpint (len, ==, strlen (testbuf2));
536
537     memset (buf, 0, sizeof (buf));
538     len = g_socket_receive (client, buf, sizeof (buf), NULL, &error);
539     g_assert_no_error (error);
540     g_assert_cmpint (len, ==, strlen (testbuf2));
541     g_assert_cmpstr (testbuf2, ==, buf);
542   }
543
544   g_socket_shutdown (client, FALSE, TRUE, &error);
545   g_assert_no_error (error);
546
547   g_thread_join (data->thread);
548
549   if (family == G_SOCKET_FAMILY_IPV4)
550     {
551       /* Test that reading on a remote-closed socket gets back 0 bytes. */
552       len = g_socket_receive (client, buf, sizeof (buf), NULL, &error);
553       g_assert_no_error (error);
554       g_assert_cmpint (len, ==, 0);
555     }
556   else
557     {
558       /* Test that writing to a remote-closed socket gets back CONNECTION_CLOSED. */
559       len = g_socket_send (client, testbuf, strlen (testbuf) + 1, NULL, &error);
560       g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CONNECTION_CLOSED);
561       g_assert_cmpint (len, ==, -1);
562       g_clear_error (&error);
563     }
564
565   g_socket_close (client, &error);
566   g_assert_no_error (error);
567   g_socket_close (data->server, &error);
568   g_assert_no_error (error);
569
570   g_object_unref (data->server);
571   g_object_unref (client);
572
573   g_slice_free (IPTestData, data);
574 }
575
576 static void
577 test_ipv4_sync (void)
578 {
579   test_ip_sync (G_SOCKET_FAMILY_IPV4);
580 }
581
582 static void
583 test_ipv6_sync (void)
584 {
585   if (!ipv6_supported)
586     {
587       g_test_skip ("No support for IPv6");
588       return;
589     }
590
591   test_ip_sync (G_SOCKET_FAMILY_IPV6);
592 }
593
594 static void
595 test_ip_sync_dgram (GSocketFamily family)
596 {
597   IPTestData *data;
598   GError *error = NULL;
599   GSocket *client;
600   GSocketAddress *dest_addr;
601   gssize len;
602   gchar buf[128];
603
604   data = create_server_full (family, G_SOCKET_TYPE_DATAGRAM,
605                              echo_server_dgram_thread, FALSE, &error);
606   if (error != NULL)
607     {
608       g_test_skip_printf ("Failed to create server: %s", error->message);
609       g_clear_error (&error);
610       return;
611     }
612
613   dest_addr = g_socket_get_local_address (data->server, &error);
614
615   client = g_socket_new (family,
616                          G_SOCKET_TYPE_DATAGRAM,
617                          G_SOCKET_PROTOCOL_DEFAULT,
618                          &error);
619   g_assert_no_error (error);
620
621   g_assert_cmpint (g_socket_get_family (client), ==, family);
622   g_assert_cmpint (g_socket_get_socket_type (client), ==, G_SOCKET_TYPE_DATAGRAM);
623   g_assert_cmpint (g_socket_get_protocol (client), ==, G_SOCKET_PROTOCOL_DEFAULT);
624 #ifdef G_OS_WIN32
625   g_assert (GLIB_PRIVATE_CALL (g_win32_handle_is_socket) ((HANDLE)(gintptr) g_socket_get_fd (client)));
626 #endif
627
628   g_socket_set_blocking (client, TRUE);
629   g_socket_set_timeout (client, 1);
630
631   len = g_socket_send_to (client, dest_addr, testbuf, strlen (testbuf) + 1, NULL, &error);
632   g_assert_no_error (error);
633   g_assert_cmpint (len, ==, strlen (testbuf) + 1);
634
635   len = g_socket_receive_from (client, NULL, buf, sizeof (buf), NULL, &error);
636   g_assert_no_error (error);
637   g_assert_cmpint (len, ==, strlen (testbuf) + 1);
638
639   g_assert_cmpstr (testbuf, ==, buf);
640
641   {
642     GOutputMessage m[3] = { { NULL, NULL, 0, 0, NULL, 0 }, };
643     GInputMessage im[3] = { { NULL, NULL, 0, 0, 0, NULL, 0 }, };
644     GOutputVector v[7] = { { NULL, 0 }, };
645     GInputVector iv[7] = { { NULL, 0 }, };
646
647     v[0].buffer = testbuf2 + 0;
648     v[0].size = 3;
649     v[1].buffer = testbuf2 + 3;
650     v[1].size = 5;
651     v[2].buffer = testbuf2 + 3 + 5;
652     v[2].size = 0;
653     v[3].buffer = testbuf2 + 3 + 5;
654     v[3].size = 6;
655     v[4].buffer = testbuf2 + 3 + 5 + 6;
656     v[4].size = 2;
657     v[5].buffer = testbuf2 + 3 + 5 + 6 + 2;
658     v[5].size = 1;
659     v[6].buffer = testbuf2 + 3 + 5 + 6 + 2 + 1;
660     v[6].size = strlen (testbuf2) - (3 + 5 + 6 + 2 + 1);
661
662     iv[0].buffer = buf + 0;
663     iv[0].size = 3;
664     iv[1].buffer = buf + 3;
665     iv[1].size = 5;
666     iv[2].buffer = buf + 3 + 5;
667     iv[2].size = 0;
668     iv[3].buffer = buf + 3 + 5;
669     iv[3].size = 6;
670     iv[4].buffer = buf + 3 + 5 + 6;
671     iv[4].size = 2;
672     iv[5].buffer = buf + 3 + 5 + 6 + 2;
673     iv[5].size = 1;
674     iv[6].buffer = buf + 3 + 5 + 6 + 2 + 1;
675     iv[6].size = sizeof (buf) - (3 + 5 + 6 + 2 + 1);
676
677     len = g_socket_send_message (client, dest_addr, v, G_N_ELEMENTS (v), NULL, 0, 0, NULL, &error);
678     g_assert_no_error (error);
679     g_assert_cmpint (len, ==, strlen (testbuf2));
680
681     memset (buf, 0, sizeof (buf));
682     len = g_socket_receive_from (client, NULL, buf, sizeof (buf), NULL, &error);
683     g_assert_no_error (error);
684     g_assert_cmpint (len, ==, strlen (testbuf2));
685     g_assert_cmpstr (testbuf2, ==, buf);
686
687     m[0].vectors = &v[0];
688     m[0].num_vectors = 1;
689     m[0].address = dest_addr;
690     m[1].vectors = &v[0];
691     m[1].num_vectors = 6;
692     m[1].address = dest_addr;
693     m[2].vectors = &v[6];
694     m[2].num_vectors = 1;
695     m[2].address = dest_addr;
696
697     len = g_socket_send_messages (client, m, G_N_ELEMENTS (m), 0, NULL, &error);
698     g_assert_no_error (error);
699     g_assert_cmpint (len, ==, G_N_ELEMENTS (m));
700     g_assert_cmpint (m[0].bytes_sent, ==, 3);
701     g_assert_cmpint (m[1].bytes_sent, ==, 17);
702     g_assert_cmpint (m[2].bytes_sent, ==, v[6].size);
703
704     memset (buf, 0, sizeof (buf));
705     len = g_socket_receive_from (client, NULL, buf, sizeof (buf), NULL, &error);
706     g_assert_no_error (error);
707     g_assert_cmpint (len, ==, 3);
708
709     memset (buf, 0, sizeof (buf));
710     len = g_socket_receive_from (client, NULL, buf, sizeof (buf), NULL, &error);
711     g_assert_no_error (error);
712     /* v[0].size + v[1].size + v[2].size + v[3].size + v[4].size + v[5].size */
713     g_assert_cmpint (len, ==, 17);
714     g_assert (memcmp (testbuf2, buf, 17) == 0);
715
716     memset (buf, 0, sizeof (buf));
717     len = g_socket_receive_from (client, NULL, buf, sizeof (buf), NULL, &error);
718     g_assert_no_error (error);
719     g_assert_cmpint (len, ==, v[6].size);
720     g_assert_cmpstr (buf, ==, v[6].buffer);
721
722     /* reset since we're re-using the message structs */
723     m[0].bytes_sent = 0;
724     m[1].bytes_sent = 0;
725     m[2].bytes_sent = 0;
726
727     /* now try receiving multiple messages */
728     len = g_socket_send_messages (client, m, G_N_ELEMENTS (m), 0, NULL, &error);
729     g_assert_no_error (error);
730     g_assert_cmpint (len, ==, G_N_ELEMENTS (m));
731     g_assert_cmpint (m[0].bytes_sent, ==, 3);
732     g_assert_cmpint (m[1].bytes_sent, ==, 17);
733     g_assert_cmpint (m[2].bytes_sent, ==, v[6].size);
734
735     im[0].vectors = &iv[0];
736     im[0].num_vectors = 1;
737     im[1].vectors = &iv[0];
738     im[1].num_vectors = 6;
739     im[2].vectors = &iv[6];
740     im[2].num_vectors = 1;
741
742     memset (buf, 0, sizeof (buf));
743     len = g_socket_receive_messages (client, im, G_N_ELEMENTS (im), 0,
744                                      NULL, &error);
745     g_assert_no_error (error);
746     g_assert_cmpint (len, ==, G_N_ELEMENTS (im));
747
748     g_assert_cmpuint (im[0].bytes_received, ==, 3);
749     /* v[0].size + v[1].size + v[2].size + v[3].size + v[4].size + v[5].size */
750     g_assert_cmpuint (im[1].bytes_received, ==, 17);
751     g_assert_cmpuint (im[2].bytes_received, ==, v[6].size);
752
753     /* reset since we're re-using the message structs */
754     m[0].bytes_sent = 0;
755     m[1].bytes_sent = 0;
756     m[2].bytes_sent = 0;
757
758     /* now try to generate an early return by omitting the destination address on [1] */
759     m[1].address = NULL;
760     len = g_socket_send_messages (client, m, G_N_ELEMENTS (m), 0, NULL, &error);
761     g_assert_no_error (error);
762     g_assert_cmpint (len, ==, 1);
763
764     g_assert_cmpint (m[0].bytes_sent, ==, 3);
765     g_assert_cmpint (m[1].bytes_sent, ==, 0);
766     g_assert_cmpint (m[2].bytes_sent, ==, 0);
767
768     /* reset since we're re-using the message structs */
769     m[0].bytes_sent = 0;
770     m[1].bytes_sent = 0;
771     m[2].bytes_sent = 0;
772
773     /* now try to generate an error by omitting all destination addresses */
774     m[0].address = NULL;
775     m[1].address = NULL;
776     m[2].address = NULL;
777     len = g_socket_send_messages (client, m, G_N_ELEMENTS (m), 0, NULL, &error);
778     /* This error code may vary between platforms and over time; it is not guaranteed API: */
779 #ifndef G_OS_WIN32
780     g_assert_error (error, G_IO_ERROR, G_IO_ERROR_FAILED);
781 #else
782     g_assert_error (error, G_IO_ERROR, G_IO_ERROR_NOT_CONNECTED);
783 #endif
784     g_clear_error (&error);
785     g_assert_cmpint (len, ==, -1);
786
787     g_assert_cmpint (m[0].bytes_sent, ==, 0);
788     g_assert_cmpint (m[1].bytes_sent, ==, 0);
789     g_assert_cmpint (m[2].bytes_sent, ==, 0);
790
791     len = g_socket_receive_from (client, NULL, buf, sizeof (buf), NULL, &error);
792     g_assert_cmpint (len, ==, 3);
793   }
794
795   g_cancellable_cancel (data->cancellable);
796
797   g_thread_join (data->thread);
798
799   g_socket_close (client, &error);
800   g_assert_no_error (error);
801   g_socket_close (data->server, &error);
802   g_assert_no_error (error);
803
804   g_object_unref (data->server);
805   g_object_unref (data->cancellable);
806   g_object_unref (client);
807   g_object_unref (dest_addr);
808
809   g_slice_free (IPTestData, data);
810 }
811
812 static void
813 test_ipv4_sync_dgram (void)
814 {
815   test_ip_sync_dgram (G_SOCKET_FAMILY_IPV4);
816 }
817
818 static void
819 test_ipv6_sync_dgram (void)
820 {
821   if (!ipv6_supported)
822     {
823       g_test_skip ("No support for IPv6");
824       return;
825     }
826
827   test_ip_sync_dgram (G_SOCKET_FAMILY_IPV6);
828 }
829
830 static gpointer
831 cancellable_thread_cb (gpointer data)
832 {
833   GCancellable *cancellable = data;
834
835   g_usleep (0.1 * G_USEC_PER_SEC);
836   g_cancellable_cancel (cancellable);
837   g_object_unref (cancellable);
838
839   return NULL;
840 }
841
842 static void
843 test_ip_sync_dgram_timeouts (GSocketFamily family)
844 {
845   GError *error = NULL;
846   GSocket *client = NULL;
847   GCancellable *cancellable = NULL;
848   GThread *cancellable_thread = NULL;
849   gssize len;
850 #ifdef G_OS_WIN32
851   GInetAddress *iaddr;
852   GSocketAddress *addr;
853 #endif
854
855   client = g_socket_new (family,
856                          G_SOCKET_TYPE_DATAGRAM,
857                          G_SOCKET_PROTOCOL_DEFAULT,
858                          &error);
859   g_assert_no_error (error);
860
861   g_assert_cmpint (g_socket_get_family (client), ==, family);
862   g_assert_cmpint (g_socket_get_socket_type (client), ==, G_SOCKET_TYPE_DATAGRAM);
863   g_assert_cmpint (g_socket_get_protocol (client), ==, G_SOCKET_PROTOCOL_DEFAULT);
864 #ifdef G_OS_WIN32
865   g_assert (GLIB_PRIVATE_CALL (g_win32_handle_is_socket) ((HANDLE)(gintptr) g_socket_get_fd (client)));
866 #endif
867
868 #ifdef G_OS_WIN32
869   /* Winsock can't recv() on unbound udp socket */
870   iaddr = g_inet_address_new_loopback (family);
871   addr = g_inet_socket_address_new (iaddr, 0);
872   g_object_unref (iaddr);
873   g_socket_bind (client, addr, TRUE, &error);
874   g_object_unref (addr);
875   g_assert_no_error (error);
876 #endif
877
878   /* No overall timeout: test the per-operation timeouts instead. */
879   g_socket_set_timeout (client, 0);
880
881   cancellable = g_cancellable_new ();
882
883   /* Check for timeouts when no server is running. */
884   {
885     gint64 start_time;
886     GInputMessage im = { NULL, NULL, 0, 0, 0, NULL, 0 };
887     GInputVector iv = { NULL, 0 };
888     guint8 buf[128];
889
890     iv.buffer = buf;
891     iv.size = sizeof (buf);
892
893     im.vectors = &iv;
894     im.num_vectors = 1;
895
896     memset (buf, 0, sizeof (buf));
897
898     /* Try a non-blocking read. */
899     g_socket_set_blocking (client, FALSE);
900     len = g_socket_receive_messages (client, &im, 1, 0  /* flags */,
901                                      NULL, &error);
902     g_assert_error (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK);
903     g_assert_cmpint (len, ==, -1);
904     g_clear_error (&error);
905
906     /* Try a timeout read. Can’t really validate the time taken more than
907      * checking it’s positive. */
908     g_socket_set_timeout (client, 1);
909     g_socket_set_blocking (client, TRUE);
910     start_time = g_get_monotonic_time ();
911     len = g_socket_receive_messages (client, &im, 1, 0  /* flags */,
912                                      NULL, &error);
913     g_assert_error (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT);
914     g_assert_cmpint (len, ==, -1);
915     g_assert_cmpint (g_get_monotonic_time () - start_time, >, 0);
916     g_clear_error (&error);
917
918     /* Try a blocking read, cancelled from another thread. */
919     g_socket_set_timeout (client, 0);
920     cancellable_thread = g_thread_new ("cancellable",
921                                        cancellable_thread_cb,
922                                        g_object_ref (cancellable));
923
924     start_time = g_get_monotonic_time ();
925     len = g_socket_receive_messages (client, &im, 1, 0  /* flags */,
926                                      cancellable, &error);
927     g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CANCELLED);
928     g_assert_cmpint (len, ==, -1);
929     g_assert_cmpint (g_get_monotonic_time () - start_time, >, 0);
930     g_clear_error (&error);
931
932     g_thread_join (cancellable_thread);
933   }
934
935   g_socket_close (client, &error);
936   g_assert_no_error (error);
937
938   g_object_unref (client);
939   g_object_unref (cancellable);
940 }
941
942 static void
943 test_ipv4_sync_dgram_timeouts (void)
944 {
945   test_ip_sync_dgram_timeouts (G_SOCKET_FAMILY_IPV4);
946 }
947
948 static void
949 test_ipv6_sync_dgram_timeouts (void)
950 {
951   if (!ipv6_supported)
952     {
953       g_test_skip ("No support for IPv6");
954       return;
955     }
956
957   test_ip_sync_dgram_timeouts (G_SOCKET_FAMILY_IPV6);
958 }
959
960 static gpointer
961 graceful_server_thread (gpointer user_data)
962 {
963   IPTestData *data = user_data;
964   GSocket *sock;
965   GError *error = NULL;
966   gssize len;
967
968   sock = g_socket_accept (data->server, NULL, &error);
969   g_assert_no_error (error);
970
971   len = g_socket_send (sock, testbuf, strlen (testbuf) + 1, NULL, &error);
972   g_assert_no_error (error);
973   g_assert_cmpint (len, ==, strlen (testbuf) + 1);
974
975   return sock;
976 }
977
978 static void
979 test_close_graceful (void)
980 {
981   GSocketFamily family = G_SOCKET_FAMILY_IPV4;
982   IPTestData *data;
983   GError *error = NULL;
984   GSocket *client, *server;
985   GSocketAddress *addr;
986   gssize len;
987   gchar buf[128];
988
989   data = create_server (family, graceful_server_thread, FALSE, &error);
990   if (error != NULL)
991     {
992       g_test_skip_printf ("Failed to create server: %s", error->message);
993       g_clear_error (&error);
994       return;
995     }
996
997   addr = g_socket_get_local_address (data->server, &error);
998   g_assert_no_error (error);
999
1000   client = g_socket_new (family,
1001                          G_SOCKET_TYPE_STREAM,
1002                          G_SOCKET_PROTOCOL_DEFAULT,
1003                          &error);
1004   g_assert_no_error (error);
1005
1006   g_assert_cmpint (g_socket_get_family (client), ==, family);
1007   g_assert_cmpint (g_socket_get_socket_type (client), ==, G_SOCKET_TYPE_STREAM);
1008   g_assert_cmpint (g_socket_get_protocol (client), ==, G_SOCKET_PROTOCOL_DEFAULT);
1009 #ifdef G_OS_WIN32
1010   g_assert (GLIB_PRIVATE_CALL (g_win32_handle_is_socket) ((HANDLE)(gintptr) g_socket_get_fd (client)));
1011 #endif
1012
1013   g_socket_set_blocking (client, TRUE);
1014   g_socket_set_timeout (client, 1);
1015
1016   g_socket_connect (client, addr, NULL, &error);
1017   g_assert_no_error (error);
1018   g_assert (g_socket_is_connected (client));
1019   g_object_unref (addr);
1020
1021   server = g_thread_join (data->thread);
1022
1023   /* similar to g_tcp_connection_set_graceful_disconnect(), but explicit */
1024   g_socket_shutdown (server, FALSE, TRUE, &error);
1025   g_assert_no_error (error);
1026
1027   /* we must timeout */
1028   g_socket_condition_wait (client, G_IO_HUP, NULL, &error);
1029   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT);
1030   g_clear_error (&error);
1031
1032   /* check that the remaining data is received */
1033   len = g_socket_receive (client, buf, strlen (testbuf) + 1, NULL, &error);
1034   g_assert_no_error (error);
1035   g_assert_cmpint (len, ==, strlen (testbuf) + 1);
1036
1037   /* and only then the connection is closed */
1038   len = g_socket_receive (client, buf, sizeof (buf), NULL, &error);
1039   g_assert_no_error (error);
1040   g_assert_cmpint (len, ==, 0);
1041
1042   g_socket_close (server, &error);
1043   g_assert_no_error (error);
1044
1045   g_socket_close (client, &error);
1046   g_assert_no_error (error);
1047
1048   g_object_unref (server);
1049   g_object_unref (data->server);
1050   g_object_unref (client);
1051
1052   g_slice_free (IPTestData, data);
1053 }
1054
1055 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1056 static gpointer
1057 v4mapped_server_thread (gpointer user_data)
1058 {
1059   IPTestData *data = user_data;
1060   GSocket *sock;
1061   GError *error = NULL;
1062   GSocketAddress *addr;
1063
1064   sock = g_socket_accept (data->server, NULL, &error);
1065   g_assert_no_error (error);
1066
1067   g_assert_cmpint (g_socket_get_family (sock), ==, G_SOCKET_FAMILY_IPV6);
1068
1069   addr = g_socket_get_local_address (sock, &error);
1070   g_assert_no_error (error);
1071   g_assert_cmpint (g_socket_address_get_family (addr), ==, G_SOCKET_FAMILY_IPV4);
1072   g_object_unref (addr);
1073
1074   addr = g_socket_get_remote_address (sock, &error);
1075   g_assert_no_error (error);
1076   g_assert_cmpint (g_socket_address_get_family (addr), ==, G_SOCKET_FAMILY_IPV4);
1077   g_object_unref (addr);
1078
1079   g_socket_close (sock, &error);
1080   g_assert_no_error (error);
1081   g_object_unref (sock);
1082   return NULL;
1083 }
1084
1085 static void
1086 test_ipv6_v4mapped (void)
1087 {
1088   IPTestData *data;
1089   GError *error = NULL;
1090   GSocket *client;
1091   GSocketAddress *addr, *v4addr;
1092   GInetAddress *iaddr;
1093
1094   if (!ipv6_supported)
1095     {
1096       g_test_skip ("No support for IPv6");
1097       return;
1098     }
1099
1100   data = create_server (G_SOCKET_FAMILY_IPV6, v4mapped_server_thread, TRUE, &error);
1101   if (error != NULL)
1102     {
1103       g_test_skip_printf ("Failed to create server: %s", error->message);
1104       g_clear_error (&error);
1105       return;
1106     }
1107
1108   client = g_socket_new (G_SOCKET_FAMILY_IPV4,
1109                          G_SOCKET_TYPE_STREAM,
1110                          G_SOCKET_PROTOCOL_DEFAULT,
1111                          &error);
1112   g_assert_no_error (error);
1113
1114   g_socket_set_blocking (client, TRUE);
1115   g_socket_set_timeout (client, 1);
1116
1117   addr = g_socket_get_local_address (data->server, &error);
1118   g_assert_no_error (error);
1119   iaddr = g_inet_address_new_loopback (G_SOCKET_FAMILY_IPV4);
1120   v4addr = g_inet_socket_address_new (iaddr, g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr)));
1121   g_object_unref (iaddr);
1122   g_object_unref (addr);
1123
1124   g_socket_connect (client, v4addr, NULL, &error);
1125   g_assert_no_error (error);
1126   g_assert (g_socket_is_connected (client));
1127
1128   g_thread_join (data->thread);
1129
1130   g_socket_close (client, &error);
1131   g_assert_no_error (error);
1132   g_socket_close (data->server, &error);
1133   g_assert_no_error (error);
1134
1135   g_object_unref (data->server);
1136   g_object_unref (client);
1137   g_object_unref (v4addr);
1138
1139   g_slice_free (IPTestData, data);
1140 }
1141 #endif
1142
1143 static void
1144 test_timed_wait (void)
1145 {
1146   IPTestData *data;
1147   GError *error = NULL;
1148   GSocket *client;
1149   GSocketAddress *addr;
1150   gint64 start_time;
1151   gint poll_duration;
1152
1153   if (!g_test_thorough ())
1154     {
1155       g_test_skip ("Not running timing heavy test");
1156       return;
1157     }
1158
1159   data = create_server (G_SOCKET_FAMILY_IPV4, echo_server_thread, FALSE, &error);
1160   if (error != NULL)
1161     {
1162       g_test_skip_printf ("Failed to create server: %s", error->message);
1163       g_clear_error (&error);
1164       return;
1165     }
1166
1167   addr = g_socket_get_local_address (data->server, &error);
1168   g_assert_no_error (error);
1169
1170   client = g_socket_new (G_SOCKET_FAMILY_IPV4,
1171                          G_SOCKET_TYPE_STREAM,
1172                          G_SOCKET_PROTOCOL_DEFAULT,
1173                          &error);
1174   g_assert_no_error (error);
1175
1176   g_socket_set_blocking (client, TRUE);
1177   g_socket_set_timeout (client, 1);
1178
1179   g_socket_connect (client, addr, NULL, &error);
1180   g_assert_no_error (error);
1181   g_object_unref (addr);
1182
1183   start_time = g_get_monotonic_time ();
1184   g_socket_condition_timed_wait (client, G_IO_IN, 100000 /* 100 ms */,
1185                                  NULL, &error);
1186   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT);
1187   g_clear_error (&error);
1188   poll_duration = g_get_monotonic_time () - start_time;
1189
1190   g_assert_cmpint (poll_duration, >=, 98000);
1191   g_assert_cmpint (poll_duration, <, 112000);
1192
1193   g_socket_close (client, &error);
1194   g_assert_no_error (error);
1195
1196   g_thread_join (data->thread);
1197
1198   g_socket_close (data->server, &error);
1199   g_assert_no_error (error);
1200
1201   g_object_unref (data->server);
1202   g_object_unref (client);
1203
1204   g_slice_free (IPTestData, data);
1205 }
1206
1207 static int
1208 duplicate_socket_fd (int fd)
1209 {
1210 #ifdef G_OS_WIN32
1211   WSAPROTOCOL_INFO info;
1212
1213   if (WSADuplicateSocket ((SOCKET)fd,
1214                           GetCurrentProcessId (),
1215                           &info))
1216     {
1217       gchar *emsg = g_win32_error_message (WSAGetLastError ());
1218       g_test_message ("Error duplicating socket: %s", emsg);
1219       g_free (emsg);
1220       return -1;
1221     }
1222
1223   return (int)WSASocket (FROM_PROTOCOL_INFO,
1224                          FROM_PROTOCOL_INFO,
1225                          FROM_PROTOCOL_INFO,
1226                          &info, 0, 0);
1227 #else
1228   return dup (fd);
1229 #endif
1230 }
1231
1232 static void
1233 test_fd_reuse (void)
1234 {
1235   IPTestData *data;
1236   GError *error = NULL;
1237   GSocket *client;
1238   GSocket *client2;
1239   GSocketAddress *addr;
1240   int fd;
1241   gssize len;
1242   gchar buf[128];
1243
1244   g_test_bug ("https://bugzilla.gnome.org/show_bug.cgi?id=741707");
1245
1246   data = create_server (G_SOCKET_FAMILY_IPV4, echo_server_thread, FALSE, &error);
1247   if (error != NULL)
1248     {
1249       g_test_skip_printf ("Failed to create server: %s", error->message);
1250       g_clear_error (&error);
1251       return;
1252     }
1253
1254   addr = g_socket_get_local_address (data->server, &error);
1255   g_assert_no_error (error);
1256
1257   client = g_socket_new (G_SOCKET_FAMILY_IPV4,
1258                          G_SOCKET_TYPE_STREAM,
1259                          G_SOCKET_PROTOCOL_DEFAULT,
1260                          &error);
1261   g_assert_no_error (error);
1262
1263   g_socket_set_blocking (client, TRUE);
1264   g_socket_set_timeout (client, 1);
1265
1266   g_socket_connect (client, addr, NULL, &error);
1267   g_assert_no_error (error);
1268   g_assert (g_socket_is_connected (client));
1269   g_object_unref (addr);
1270
1271   /* we have to dup otherwise the fd gets closed twice on unref */
1272   fd = duplicate_socket_fd (g_socket_get_fd (client));
1273   client2 = g_socket_new_from_fd (fd, &error);
1274   g_assert_no_error (error);
1275
1276   g_assert_cmpint (g_socket_get_family (client2), ==, g_socket_get_family (client));
1277   g_assert_cmpint (g_socket_get_socket_type (client2), ==, g_socket_get_socket_type (client));
1278   g_assert_cmpint (g_socket_get_protocol (client2), ==, G_SOCKET_PROTOCOL_TCP);
1279 #ifdef G_OS_WIN32
1280   g_assert (GLIB_PRIVATE_CALL (g_win32_handle_is_socket) ((HANDLE)(gintptr) g_socket_get_fd (client)));
1281 #endif
1282
1283   len = g_socket_send (client2, testbuf, strlen (testbuf) + 1, NULL, &error);
1284   g_assert_no_error (error);
1285   g_assert_cmpint (len, ==, strlen (testbuf) + 1);
1286
1287   len = g_socket_receive (client2, buf, sizeof (buf), NULL, &error);
1288   g_assert_no_error (error);
1289   g_assert_cmpint (len, ==, strlen (testbuf) + 1);
1290
1291   g_assert_cmpstr (testbuf, ==, buf);
1292
1293   g_socket_shutdown (client, FALSE, TRUE, &error);
1294   g_assert_no_error (error);
1295   /* The semantics of dup()+shutdown() are ambiguous; this call will succeed
1296    * on Linux, but return ENOTCONN on OS X.
1297    */
1298   g_socket_shutdown (client2, FALSE, TRUE, NULL);
1299
1300   g_thread_join (data->thread);
1301
1302   g_socket_close (client, &error);
1303   g_assert_no_error (error);
1304   g_socket_close (client2, &error);
1305   g_assert_no_error (error);
1306   g_socket_close (data->server, &error);
1307   g_assert_no_error (error);
1308
1309   g_assert_cmpint (g_socket_get_fd (client), ==, -1);
1310   g_assert_cmpint (g_socket_get_fd (client2), ==, -1);
1311   g_assert_cmpint (g_socket_get_fd (data->server), ==, -1);
1312
1313   g_object_unref (data->server);
1314   g_object_unref (client);
1315   g_object_unref (client2);
1316
1317   g_slice_free (IPTestData, data);
1318 }
1319
1320 static void
1321 test_sockaddr (void)
1322 {
1323   struct sockaddr_in6 sin6, gsin6;
1324   GSocketAddress *saddr;
1325   GInetSocketAddress *isaddr;
1326   GInetAddress *iaddr;
1327   GError *error = NULL;
1328
1329   memset (&sin6, 0, sizeof (sin6));
1330   sin6.sin6_family = AF_INET6;
1331   sin6.sin6_addr = in6addr_loopback;
1332   sin6.sin6_port = g_htons (42);
1333   sin6.sin6_scope_id = 17;
1334   sin6.sin6_flowinfo = 1729;
1335
1336   saddr = g_socket_address_new_from_native (&sin6, sizeof (sin6));
1337   g_assert (G_IS_INET_SOCKET_ADDRESS (saddr));
1338
1339   isaddr = G_INET_SOCKET_ADDRESS (saddr);
1340   iaddr = g_inet_socket_address_get_address (isaddr);
1341   g_assert_cmpint (g_inet_address_get_family (iaddr), ==, G_SOCKET_FAMILY_IPV6);
1342   g_assert (g_inet_address_get_is_loopback (iaddr));
1343
1344   g_assert_cmpint (g_inet_socket_address_get_port (isaddr), ==, 42);
1345   g_assert_cmpint (g_inet_socket_address_get_scope_id (isaddr), ==, 17);
1346   g_assert_cmpint (g_inet_socket_address_get_flowinfo (isaddr), ==, 1729);
1347
1348   g_socket_address_to_native (saddr, &gsin6, sizeof (gsin6), &error);
1349   g_assert_no_error (error);
1350
1351   g_assert (memcmp (&sin6.sin6_addr, &gsin6.sin6_addr, sizeof (struct in6_addr)) == 0);
1352   g_assert_cmpint (sin6.sin6_port, ==, gsin6.sin6_port);
1353   g_assert_cmpint (sin6.sin6_scope_id, ==, gsin6.sin6_scope_id);
1354   g_assert_cmpint (sin6.sin6_flowinfo, ==, gsin6.sin6_flowinfo);
1355
1356   g_object_unref (saddr);
1357 }
1358
1359 static void
1360 bind_win32_unixfd (int fd)
1361 {
1362 #ifdef G_OS_WIN32
1363   gint len, ret;
1364   struct sockaddr_un addr;
1365
1366   memset (&addr, 0, sizeof addr);
1367   addr.sun_family = AF_UNIX;
1368   len = g_snprintf (addr.sun_path, sizeof addr.sun_path, "%s" G_DIR_SEPARATOR_S "%d.sock", g_get_tmp_dir (), fd);
1369   g_assert_cmpint (len, <=, sizeof addr.sun_path);
1370   ret = bind (fd, (struct sockaddr *)&addr, sizeof addr);
1371   g_assert_cmpint (ret, ==, 0);
1372   g_remove (addr.sun_path);
1373 #endif
1374 }
1375
1376 static void
1377 test_unix_from_fd (void)
1378 {
1379   gint fd;
1380   GError *error;
1381   GSocket *s;
1382
1383   fd = socket (AF_UNIX, SOCK_STREAM, 0);
1384 #ifdef G_OS_WIN32
1385   if (fd == -1)
1386     {
1387       g_test_skip ("AF_UNIX not supported on this Windows system.");
1388       return;
1389     }
1390 #endif
1391   g_assert_cmpint (fd, !=, -1);
1392
1393   bind_win32_unixfd (fd);
1394
1395   error = NULL;
1396   s = g_socket_new_from_fd (fd, &error);
1397   g_assert_no_error (error);
1398   g_assert_cmpint (g_socket_get_family (s), ==, G_SOCKET_FAMILY_UNIX);
1399   g_assert_cmpint (g_socket_get_socket_type (s), ==, G_SOCKET_TYPE_STREAM);
1400   g_assert_cmpint (g_socket_get_protocol (s), ==, G_SOCKET_PROTOCOL_DEFAULT);
1401 #ifdef G_OS_WIN32
1402   g_assert (GLIB_PRIVATE_CALL (g_win32_handle_is_socket) ((HANDLE)(gintptr) g_socket_get_fd (s)));
1403 #endif
1404   g_object_unref (s);
1405 }
1406
1407 static void
1408 test_unix_connection (void)
1409 {
1410   gint fd;
1411   GError *error;
1412   GSocket *s;
1413   GSocketConnection *c;
1414
1415   fd = socket (AF_UNIX, SOCK_STREAM, 0);
1416 #ifdef G_OS_WIN32
1417   if (fd == -1)
1418     {
1419       g_test_skip ("AF_UNIX not supported on this Windows system.");
1420       return;
1421     }
1422 #endif
1423   g_assert_cmpint (fd, !=, -1);
1424
1425   bind_win32_unixfd (fd);
1426
1427   error = NULL;
1428   s = g_socket_new_from_fd (fd, &error);
1429   g_assert_no_error (error);
1430   c = g_socket_connection_factory_create_connection (s);
1431   g_assert (G_IS_UNIX_CONNECTION (c));
1432   g_object_unref (c);
1433   g_object_unref (s);
1434 }
1435
1436 #ifdef G_OS_UNIX
1437 static GSocketConnection *
1438 create_connection_for_fd (int fd)
1439 {
1440   GError *err = NULL;
1441   GSocket *socket;
1442   GSocketConnection *connection;
1443
1444   socket = g_socket_new_from_fd (fd, &err);
1445   g_assert_no_error (err);
1446   g_assert (G_IS_SOCKET (socket));
1447   connection = g_socket_connection_factory_create_connection (socket);
1448   g_assert (G_IS_UNIX_CONNECTION (connection));
1449   g_object_unref (socket);
1450   return connection;
1451 }
1452
1453 #define TEST_DATA "failure to say failure to say 'i love gnome-panel!'."
1454
1455 static void
1456 test_unix_connection_ancillary_data (void)
1457 {
1458   GError *err = NULL;
1459   gint pv[2], sv[3];
1460   gint status, fd, len;
1461   char buffer[1024];
1462   pid_t pid;
1463
1464   status = pipe (pv);
1465   g_assert_cmpint (status, ==, 0);
1466
1467   status = socketpair (PF_UNIX, SOCK_STREAM, 0, sv);
1468   g_assert_cmpint (status, ==, 0);
1469
1470   pid = fork ();
1471   g_assert_cmpint (pid, >=, 0);
1472
1473   /* Child: close its copy of the write end of the pipe, receive it
1474    * again from the parent over the socket, and write some text to it.
1475    *
1476    * Parent: send the write end of the pipe (still open for the
1477    * parent) over the socket, close it, and read some text from the
1478    * read end of the pipe.
1479    */
1480   if (pid == 0)
1481     {
1482       GSocketConnection *connection;
1483
1484       close (sv[1]);
1485       connection = create_connection_for_fd (sv[0]);
1486
1487       status = close (pv[1]);
1488       g_assert_cmpint (status, ==, 0);
1489
1490       err = NULL;
1491       fd = g_unix_connection_receive_fd (G_UNIX_CONNECTION (connection), NULL,
1492                                          &err);
1493       g_assert_no_error (err);
1494       g_assert_cmpint (fd, >, -1);
1495       g_object_unref (connection);
1496
1497       do
1498         len = write (fd, TEST_DATA, sizeof (TEST_DATA));
1499       while (len == -1 && errno == EINTR);
1500       g_assert_cmpint (len, ==, sizeof (TEST_DATA));
1501       exit (0);
1502     }
1503   else
1504     {
1505       GSocketConnection *connection;
1506
1507       close (sv[0]);
1508       connection = create_connection_for_fd (sv[1]);
1509
1510       err = NULL;
1511       g_unix_connection_send_fd (G_UNIX_CONNECTION (connection), pv[1], NULL,
1512                                  &err);
1513       g_assert_no_error (err);
1514       g_object_unref (connection);
1515
1516       status = close (pv[1]);
1517       g_assert_cmpint (status, ==, 0);
1518
1519       memset (buffer, 0xff, sizeof buffer);
1520       do
1521         len = read (pv[0], buffer, sizeof buffer);
1522       while (len == -1 && errno == EINTR);
1523
1524       g_assert_cmpint (len, ==, sizeof (TEST_DATA));
1525       g_assert_cmpstr (buffer, ==, TEST_DATA);
1526
1527       waitpid (pid, &status, 0);
1528       g_assert (WIFEXITED (status));
1529       g_assert_cmpint (WEXITSTATUS (status), ==, 0);
1530     }
1531
1532   /* TODO: add test for g_unix_connection_send_credentials() and
1533    * g_unix_connection_receive_credentials().
1534    */
1535 }
1536 #endif
1537
1538 #ifdef G_OS_WIN32
1539 static void
1540 test_handle_not_socket (void)
1541 {
1542   GError *err = NULL;
1543   gchar *name = NULL;
1544   HANDLE hReadPipe, hWritePipe, h;
1545   int fd;
1546
1547   g_assert_true (CreatePipe (&hReadPipe, &hWritePipe, NULL, 2048));
1548   g_assert_false (GLIB_PRIVATE_CALL (g_win32_handle_is_socket) (hReadPipe));
1549   g_assert_false (GLIB_PRIVATE_CALL (g_win32_handle_is_socket) (hWritePipe));
1550   CloseHandle (hReadPipe);
1551   CloseHandle (hWritePipe);
1552
1553   h = (HANDLE) _get_osfhandle (1);
1554   g_assert_false (GLIB_PRIVATE_CALL (g_win32_handle_is_socket) (h));
1555
1556   fd = g_file_open_tmp (NULL, &name, &err);
1557   g_assert_no_error (err);
1558   h = (HANDLE) _get_osfhandle (fd);
1559   g_assert_false (GLIB_PRIVATE_CALL (g_win32_handle_is_socket) (h));
1560   g_close (fd, &err);
1561   g_assert_no_error (err);
1562   g_unlink (name);
1563   g_free (name);
1564 }
1565 #endif
1566
1567 static gboolean
1568 postmortem_source_cb (GSocket      *socket,
1569                       GIOCondition  condition,
1570                       gpointer      user_data)
1571 {
1572   gboolean *been_here = user_data;
1573
1574   g_assert_cmpint (condition, ==, G_IO_NVAL);
1575
1576   *been_here = TRUE;
1577   return FALSE;
1578 }
1579
1580 static void
1581 test_source_postmortem (void)
1582 {
1583   GMainContext *context;
1584   GSocket *socket;
1585   GSource *source;
1586   GError *error = NULL;
1587   gboolean callback_visited = FALSE;
1588
1589   socket = g_socket_new (G_SOCKET_FAMILY_UNIX, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_DEFAULT, &error);
1590 #ifdef G_OS_WIN32
1591   if (error)
1592     {
1593       g_test_skip_printf ("AF_UNIX not supported on this Windows system: %s", error->message);
1594       g_clear_error (&error);
1595       return;
1596     }
1597 #endif
1598   g_assert_no_error (error);
1599
1600   context = g_main_context_new ();
1601
1602   source = g_socket_create_source (socket, G_IO_IN, NULL);
1603   g_source_set_callback (source, (GSourceFunc) postmortem_source_cb,
1604                          &callback_visited, NULL);
1605   g_source_attach (source, context);
1606   g_source_unref (source);
1607
1608   g_socket_close (socket, &error);
1609   g_assert_no_error (error);
1610   g_object_unref (socket);
1611
1612   /* Test that, after a socket is closed, its source callback should be called
1613    * exactly once. */
1614   g_main_context_iteration (context, FALSE);
1615   g_assert (callback_visited);
1616   g_assert (!g_main_context_pending (context));
1617
1618   g_main_context_unref (context);
1619 }
1620
1621 static void
1622 test_reuse_tcp (void)
1623 {
1624   GSocket *sock1, *sock2;
1625   GError *error = NULL;
1626   GInetAddress *iaddr;
1627   GSocketAddress *addr;
1628
1629   sock1 = g_socket_new (G_SOCKET_FAMILY_IPV4,
1630                         G_SOCKET_TYPE_STREAM,
1631                         G_SOCKET_PROTOCOL_DEFAULT,
1632                         &error);
1633   g_assert_no_error (error);
1634
1635   iaddr = g_inet_address_new_loopback (G_SOCKET_FAMILY_IPV4);
1636   addr = g_inet_socket_address_new (iaddr, 0);
1637   g_object_unref (iaddr);
1638   g_socket_bind (sock1, addr, TRUE, &error);
1639   g_object_unref (addr);
1640   g_assert_no_error (error);
1641
1642   g_socket_listen (sock1, &error);
1643   g_assert_no_error (error);
1644
1645   sock2 = g_socket_new (G_SOCKET_FAMILY_IPV4,
1646                         G_SOCKET_TYPE_STREAM,
1647                         G_SOCKET_PROTOCOL_DEFAULT,
1648                         &error);
1649   g_assert_no_error (error);
1650
1651   addr = g_socket_get_local_address (sock1, &error);
1652   g_assert_no_error (error);
1653   g_socket_bind (sock2, addr, TRUE, &error);
1654   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_ADDRESS_IN_USE);
1655   g_clear_error (&error);
1656   g_object_unref (addr);
1657
1658   g_object_unref (sock1);
1659   g_object_unref (sock2);
1660 }
1661
1662 static void
1663 test_reuse_udp (void)
1664 {
1665   GSocket *sock1, *sock2;
1666   GError *error = NULL;
1667   GInetAddress *iaddr;
1668   GSocketAddress *addr;
1669
1670   sock1 = g_socket_new (G_SOCKET_FAMILY_IPV4,
1671                         G_SOCKET_TYPE_DATAGRAM,
1672                         G_SOCKET_PROTOCOL_DEFAULT,
1673                         &error);
1674   g_assert_no_error (error);
1675
1676   iaddr = g_inet_address_new_loopback (G_SOCKET_FAMILY_IPV4);
1677   addr = g_inet_socket_address_new (iaddr, 0);
1678   g_object_unref (iaddr);
1679   g_socket_bind (sock1, addr, TRUE, &error);
1680   g_object_unref (addr);
1681   g_assert_no_error (error);
1682
1683   sock2 = g_socket_new (G_SOCKET_FAMILY_IPV4,
1684                         G_SOCKET_TYPE_DATAGRAM,
1685                         G_SOCKET_PROTOCOL_DEFAULT,
1686                         &error);
1687   g_assert_no_error (error);
1688
1689   addr = g_socket_get_local_address (sock1, &error);
1690   g_assert_no_error (error);
1691   g_socket_bind (sock2, addr, TRUE, &error);
1692   g_object_unref (addr);
1693   g_assert_no_error (error);
1694
1695   g_object_unref (sock1);
1696   g_object_unref (sock2);
1697 }
1698
1699 static void
1700 test_get_available (gconstpointer user_data)
1701 {
1702   GSocketType socket_type = GPOINTER_TO_UINT (user_data);
1703   GError *err = NULL;
1704   GSocket *listener, *server, *client;
1705   GInetAddress *addr;
1706   GSocketAddress *saddr, *boundaddr;
1707   gchar data[] = "0123456789abcdef";
1708   gchar buf[34];
1709   gssize nread;
1710
1711   listener = g_socket_new (G_SOCKET_FAMILY_IPV4,
1712                            socket_type,
1713                            G_SOCKET_PROTOCOL_DEFAULT,
1714                            &err);
1715   g_assert_no_error (err);
1716   g_assert (G_IS_SOCKET (listener));
1717
1718   client = g_socket_new (G_SOCKET_FAMILY_IPV4,
1719                          socket_type,
1720                          G_SOCKET_PROTOCOL_DEFAULT,
1721                          &err);
1722   g_assert_no_error (err);
1723   g_assert (G_IS_SOCKET (client));
1724
1725   if (socket_type == G_SOCKET_TYPE_STREAM)
1726     {
1727       g_socket_set_option (client, IPPROTO_TCP, TCP_NODELAY, TRUE, &err);
1728       g_assert_no_error (err);
1729     }
1730
1731   addr = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
1732   saddr = g_inet_socket_address_new (addr, 0);
1733
1734   g_socket_bind (listener, saddr, TRUE, &err);
1735   g_assert_no_error (err);
1736   g_object_unref (saddr);
1737   g_object_unref (addr);
1738
1739   boundaddr = g_socket_get_local_address (listener, &err);
1740   g_assert_no_error (err);
1741
1742   addr = g_inet_address_new_loopback (G_SOCKET_FAMILY_IPV4);
1743   saddr = g_inet_socket_address_new (addr, g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (boundaddr)));
1744   g_object_unref (addr);
1745   g_object_unref (boundaddr);
1746
1747   if (socket_type == G_SOCKET_TYPE_STREAM)
1748     {
1749       g_socket_listen (listener, &err);
1750       g_assert_no_error (err);
1751       g_socket_connect (client, saddr, NULL, &err);
1752       g_assert_no_error (err);
1753
1754       server = g_socket_accept (listener, NULL, &err);
1755       g_assert_no_error (err);
1756       g_socket_set_blocking (server, FALSE);
1757       g_object_unref (listener);
1758     }
1759   else
1760     server = listener;
1761
1762   g_socket_send_to (client, saddr, data, sizeof (data), NULL, &err);
1763   g_assert_no_error (err);
1764
1765   while (!g_socket_condition_wait (server, G_IO_IN, NULL, NULL))
1766     ;
1767   g_assert_cmpint (g_socket_get_available_bytes (server), ==, sizeof (data));
1768
1769   g_socket_send_to (client, saddr, data, sizeof (data), NULL, &err);
1770   g_assert_no_error (err);
1771
1772   /* We need to wait until the data has actually been copied into the
1773    * server socket's buffers, but g_socket_condition_wait() won't help
1774    * here since the socket is definitely already readable. So there's
1775    * a race condition in checking its available bytes. In the TCP
1776    * case, we poll for a bit until the new data shows up. In the UDP
1777    * case, there's not much we can do, but at least the failure mode
1778    * is passes-when-it-shouldn't, not fails-when-it-shouldn't.
1779    */
1780   if (socket_type == G_SOCKET_TYPE_STREAM)
1781     {
1782       int tries;
1783
1784       for (tries = 0; tries < 100; tries++)
1785         {
1786           gssize res = g_socket_get_available_bytes (server);
1787           if ((res == -1) || ((gsize) res > sizeof (data)))
1788             break;
1789           g_usleep (100000);
1790         }
1791
1792       g_assert_cmpint (g_socket_get_available_bytes (server), ==, 2 * sizeof (data));
1793     }
1794   else
1795     {
1796       g_usleep (100000);
1797       g_assert_cmpint (g_socket_get_available_bytes (server), ==, sizeof (data));
1798     }
1799
1800   g_assert_cmpint (sizeof (buf), >=, 2 * sizeof (data));
1801   nread = g_socket_receive (server, buf, sizeof (buf), NULL, &err);
1802   g_assert_no_error (err);
1803
1804   if (socket_type == G_SOCKET_TYPE_STREAM)
1805     {
1806       g_assert_cmpint (nread, ==, 2 * sizeof (data));
1807       g_assert_cmpint (g_socket_get_available_bytes (server), ==, 0);
1808     }
1809   else
1810     {
1811       g_assert_cmpint (nread, ==, sizeof (data));
1812       g_assert_cmpint (g_socket_get_available_bytes (server), ==, sizeof (data));
1813     }
1814
1815   nread = g_socket_receive (server, buf, sizeof (buf), NULL, &err);
1816   if (socket_type == G_SOCKET_TYPE_STREAM)
1817     {
1818       g_assert_cmpint (nread, ==, -1);
1819       g_assert_error (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK);
1820       g_clear_error (&err);
1821     }
1822   else
1823     {
1824       g_assert_cmpint (nread, ==, sizeof (data));
1825       g_assert_no_error (err);
1826     }
1827
1828   g_assert_cmpint (g_socket_get_available_bytes (server), ==, 0);
1829
1830   g_socket_close (server, &err);
1831   g_assert_no_error (err);
1832
1833   g_object_unref (saddr);
1834   g_object_unref (server);
1835   g_object_unref (client);
1836 }
1837
1838 typedef struct {
1839   GInputStream *is;
1840   GOutputStream *os;
1841   const guint8 *write_data;
1842   guint8 *read_data;
1843 } TestReadWriteData;
1844
1845 static gpointer
1846 test_read_write_write_thread (gpointer user_data)
1847 {
1848   TestReadWriteData *data = user_data;
1849   gsize bytes_written;
1850   GError *error = NULL;
1851   gboolean res;
1852
1853   res = g_output_stream_write_all (data->os, data->write_data, 1024, &bytes_written, NULL, &error);
1854   g_assert_true (res);
1855   g_assert_no_error (error);
1856   g_assert_cmpint (bytes_written, ==, 1024);
1857
1858   return NULL;
1859 }
1860
1861 static gpointer
1862 test_read_write_read_thread (gpointer user_data)
1863 {
1864   TestReadWriteData *data = user_data;
1865   gsize bytes_read;
1866   GError *error = NULL;
1867   gboolean res;
1868
1869   res = g_input_stream_read_all (data->is, data->read_data, 1024, &bytes_read, NULL, &error);
1870   g_assert_true (res);
1871   g_assert_no_error (error);
1872   g_assert_cmpint (bytes_read, ==, 1024);
1873
1874   return NULL;
1875 }
1876
1877 static gpointer
1878 test_read_write_writev_thread (gpointer user_data)
1879 {
1880   TestReadWriteData *data = user_data;
1881   gsize bytes_written;
1882   GError *error = NULL;
1883   gboolean res;
1884   GOutputVector vectors[3];
1885
1886   vectors[0].buffer = data->write_data;
1887   vectors[0].size = 256;
1888   vectors[1].buffer = data->write_data + 256;
1889   vectors[1].size = 256;
1890   vectors[2].buffer = data->write_data + 512;
1891   vectors[2].size = 512;
1892
1893   res = g_output_stream_writev_all (data->os, vectors, G_N_ELEMENTS (vectors), &bytes_written, NULL, &error);
1894   g_assert_true (res);
1895   g_assert_no_error (error);
1896   g_assert_cmpint (bytes_written, ==, 1024);
1897
1898   return NULL;
1899 }
1900
1901 /* test if normal read/write/writev via the GSocket*Streams works on TCP sockets */
1902 static void
1903 test_read_write (gconstpointer user_data)
1904 {
1905   gboolean writev = GPOINTER_TO_INT (user_data);
1906   GError *err = NULL;
1907   GSocket *listener, *server, *client;
1908   GInetAddress *addr;
1909   GSocketAddress *saddr, *boundaddr;
1910   TestReadWriteData data;
1911   guint8 data_write[1024], data_read[1024];
1912   GSocketConnection *server_stream, *client_stream;
1913   GThread *write_thread, *read_thread;
1914   guint i;
1915
1916   listener = g_socket_new (G_SOCKET_FAMILY_IPV4,
1917                            G_SOCKET_TYPE_STREAM,
1918                            G_SOCKET_PROTOCOL_DEFAULT,
1919                            &err);
1920   g_assert_no_error (err);
1921   g_assert (G_IS_SOCKET (listener));
1922
1923   client = g_socket_new (G_SOCKET_FAMILY_IPV4,
1924                          G_SOCKET_TYPE_STREAM,
1925                          G_SOCKET_PROTOCOL_DEFAULT,
1926                          &err);
1927   g_assert_no_error (err);
1928   g_assert (G_IS_SOCKET (client));
1929
1930   addr = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
1931   saddr = g_inet_socket_address_new (addr, 0);
1932
1933   g_socket_bind (listener, saddr, TRUE, &err);
1934   g_assert_no_error (err);
1935   g_object_unref (saddr);
1936   g_object_unref (addr);
1937
1938   boundaddr = g_socket_get_local_address (listener, &err);
1939   g_assert_no_error (err);
1940
1941   g_socket_listen (listener, &err);
1942   g_assert_no_error (err);
1943
1944   addr = g_inet_address_new_loopback (G_SOCKET_FAMILY_IPV4);
1945   saddr = g_inet_socket_address_new (addr, g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (boundaddr)));
1946   g_object_unref (addr);
1947   g_object_unref (boundaddr);
1948
1949   g_socket_connect (client, saddr, NULL, &err);
1950   g_assert_no_error (err);
1951
1952   server = g_socket_accept (listener, NULL, &err);
1953   g_assert_no_error (err);
1954   g_socket_set_blocking (server, FALSE);
1955   g_object_unref (listener);
1956
1957   server_stream = g_socket_connection_factory_create_connection (server);
1958   g_assert_nonnull (server_stream);
1959   client_stream = g_socket_connection_factory_create_connection (client);
1960   g_assert_nonnull (client_stream);
1961
1962   for (i = 0; i < sizeof (data_write); i++)
1963     data_write[i] = i;
1964
1965   data.is = g_io_stream_get_input_stream (G_IO_STREAM (server_stream));
1966   data.os = g_io_stream_get_output_stream (G_IO_STREAM (client_stream));
1967   data.read_data = data_read;
1968   data.write_data = data_write;
1969
1970   if (writev)
1971     write_thread = g_thread_new ("writer", test_read_write_writev_thread, &data);
1972   else
1973     write_thread = g_thread_new ("writer", test_read_write_write_thread, &data);
1974   read_thread = g_thread_new ("reader", test_read_write_read_thread, &data);
1975
1976   g_thread_join (write_thread);
1977   g_thread_join (read_thread);
1978
1979   g_assert_cmpmem (data_write, sizeof data_write, data_read, sizeof data_read);
1980
1981   g_socket_close (server, &err);
1982   g_assert_no_error (err);
1983
1984   g_object_unref (server_stream);
1985   g_object_unref (client_stream);
1986
1987   g_object_unref (saddr);
1988   g_object_unref (server);
1989   g_object_unref (client);
1990 }
1991
1992 #ifdef SO_NOSIGPIPE
1993 static void
1994 test_nosigpipe (void)
1995 {
1996   GSocket *sock;
1997   GError *error = NULL;
1998   gint value;
1999
2000   sock = g_socket_new (AF_INET,
2001                        G_SOCKET_TYPE_STREAM,
2002                        G_SOCKET_PROTOCOL_DEFAULT,
2003                        &error);
2004   g_assert_no_error (error);
2005
2006   g_socket_get_option (sock, SOL_SOCKET, SO_NOSIGPIPE, &value, &error);
2007   g_assert_no_error (error);
2008   g_assert_true (value);
2009
2010   g_object_unref (sock);
2011 }
2012 #endif
2013
2014 #if G_CREDENTIALS_SUPPORTED
2015 static gpointer client_setup_thread (gpointer user_data);
2016
2017 static void
2018 test_credentials_tcp_client (void)
2019 {
2020   const GSocketFamily family = G_SOCKET_FAMILY_IPV4;
2021   IPTestData *data;
2022   GError *error = NULL;
2023   GSocket *client;
2024   GSocketAddress *addr;
2025   GCredentials *creds;
2026
2027   data = create_server (family, echo_server_thread, FALSE, &error);
2028   if (error != NULL)
2029     {
2030       g_test_skip_printf ("Failed to create server: %s", error->message);
2031       g_clear_error (&error);
2032       return;
2033     }
2034
2035   addr = g_socket_get_local_address (data->server, &error);
2036   g_assert_no_error (error);
2037
2038   client = g_socket_new (family,
2039                          G_SOCKET_TYPE_STREAM,
2040                          G_SOCKET_PROTOCOL_DEFAULT,
2041                          &error);
2042   g_assert_no_error (error);
2043
2044   g_socket_set_blocking (client, TRUE);
2045   g_socket_set_timeout (client, 1);
2046
2047   g_socket_connect (client, addr, NULL, &error);
2048   g_assert_no_error (error);
2049   g_object_unref (addr);
2050
2051   creds = g_socket_get_credentials (client, &error);
2052   if (creds != NULL)
2053     {
2054       gchar *str = g_credentials_to_string (creds);
2055       g_test_message ("Supported on this OS: %s", str);
2056       g_free (str);
2057       g_clear_object (&creds);
2058     }
2059   else
2060     {
2061       g_assert_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED);
2062       g_test_message ("Unsupported on this OS: %s", error->message);
2063       g_clear_error (&error);
2064     }
2065
2066   g_socket_close (client, &error);
2067   g_assert_no_error (error);
2068
2069   g_thread_join (data->thread);
2070
2071   g_socket_close (data->server, &error);
2072   g_assert_no_error (error);
2073
2074   g_object_unref (data->server);
2075   g_object_unref (client);
2076
2077   g_slice_free (IPTestData, data);
2078 }
2079
2080 static void
2081 test_credentials_tcp_server (void)
2082 {
2083   const GSocketFamily family = G_SOCKET_FAMILY_IPV4;
2084   IPTestData *data;
2085   GSocket *server;
2086   GError *error = NULL;
2087   GSocketAddress *addr = NULL;
2088   GInetAddress *iaddr = NULL;
2089   GSocket *sock = NULL;
2090   GCredentials *creds;
2091
2092   data = g_slice_new0 (IPTestData);
2093   data->family = family;
2094   data->server = server = g_socket_new (family,
2095                                         G_SOCKET_TYPE_STREAM,
2096                                         G_SOCKET_PROTOCOL_DEFAULT,
2097                                         &error);
2098   if (error != NULL)
2099     goto skip;
2100
2101   g_socket_set_blocking (server, TRUE);
2102
2103   iaddr = g_inet_address_new_loopback (family);
2104   addr = g_inet_socket_address_new (iaddr, 0);
2105
2106   if (!g_socket_bind (server, addr, TRUE, &error))
2107     goto skip;
2108
2109   if (!g_socket_listen (server, &error))
2110     goto skip;
2111
2112   data->thread = g_thread_new ("client", client_setup_thread, data);
2113
2114   sock = g_socket_accept (server, NULL, &error);
2115   g_assert_no_error (error);
2116
2117   creds = g_socket_get_credentials (sock, &error);
2118   if (creds != NULL)
2119     {
2120       gchar *str = g_credentials_to_string (creds);
2121       g_test_message ("Supported on this OS: %s", str);
2122       g_free (str);
2123       g_clear_object (&creds);
2124     }
2125   else
2126     {
2127       g_assert_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED);
2128       g_test_message ("Unsupported on this OS: %s", error->message);
2129       g_clear_error (&error);
2130     }
2131
2132   goto beach;
2133
2134 skip:
2135   g_test_skip_printf ("Failed to create server: %s", error->message);
2136   goto beach;
2137
2138 beach:
2139   {
2140     g_clear_error (&error);
2141
2142     g_clear_object (&sock);
2143     g_clear_object (&addr);
2144     g_clear_object (&iaddr);
2145
2146     g_clear_pointer (&data->thread, g_thread_join);
2147     g_clear_object (&data->server);
2148     g_clear_object (&data->client);
2149
2150     g_slice_free (IPTestData, data);
2151   }
2152 }
2153
2154 static gpointer
2155 client_setup_thread (gpointer user_data)
2156 {
2157   IPTestData *data = user_data;
2158   GSocketAddress *addr;
2159   GSocket *client;
2160   GError *error = NULL;
2161
2162   addr = g_socket_get_local_address (data->server, &error);
2163   g_assert_no_error (error);
2164
2165   data->client = client = g_socket_new (data->family,
2166                                         G_SOCKET_TYPE_STREAM,
2167                                         G_SOCKET_PROTOCOL_DEFAULT,
2168                                         &error);
2169   g_assert_no_error (error);
2170
2171   g_socket_set_blocking (client, TRUE);
2172   g_socket_set_timeout (client, 1);
2173
2174   g_socket_connect (client, addr, NULL, &error);
2175   g_assert_no_error (error);
2176
2177   g_object_unref (addr);
2178
2179   return NULL;
2180 }
2181
2182 #ifdef G_OS_WIN32
2183 /*
2184  * _g_win32_socketpair:
2185  *
2186  * Create a pair of connected sockets, similar to POSIX/BSD socketpair().
2187  *
2188  * Windows does not (yet) provide a socketpair() function. However, since the
2189  * introduction of AF_UNIX sockets, it is possible to implement a fairly close
2190  * function.
2191  */
2192 static gint
2193 _g_win32_socketpair (gint            domain,
2194                      gint            type,
2195                      gint            protocol,
2196                      gint            sv[2])
2197 {
2198   struct sockaddr_un addr = { 0, };
2199   socklen_t socklen;
2200   SOCKET listener = INVALID_SOCKET;
2201   SOCKET client = INVALID_SOCKET;
2202   SOCKET server = INVALID_SOCKET;
2203   gchar *path = NULL;
2204   int tmpfd, rv = -1;
2205   u_long arg, br;
2206
2207   g_return_val_if_fail (sv != NULL, -1);
2208
2209   addr.sun_family = AF_UNIX;
2210   socklen = sizeof (addr);
2211
2212   tmpfd = g_file_open_tmp (NULL, &path, NULL);
2213   if (tmpfd == -1)
2214     {
2215       WSASetLastError (WSAEACCES);
2216       goto out;
2217     }
2218
2219   g_close (tmpfd, NULL);
2220
2221   if (strlen (path) >= sizeof (addr.sun_path))
2222     {
2223       WSASetLastError (WSAEACCES);
2224       goto out;
2225     }
2226
2227   strncpy (addr.sun_path, path, sizeof (addr.sun_path) - 1);
2228
2229   listener = socket (domain, type, protocol);
2230   if (listener == INVALID_SOCKET)
2231     goto out;
2232
2233   if (DeleteFile (path) == 0)
2234     {
2235       if (GetLastError () != ERROR_FILE_NOT_FOUND)
2236         goto out;
2237     }
2238
2239   if (bind (listener, (struct sockaddr *) &addr, socklen) == SOCKET_ERROR)
2240     goto out;
2241
2242   if (listen (listener, 1) == SOCKET_ERROR)
2243     goto out;
2244
2245   client = socket (domain, type, protocol);
2246   if (client == INVALID_SOCKET)
2247     goto out;
2248
2249   arg = 1;
2250   if (ioctlsocket (client, FIONBIO, &arg) == SOCKET_ERROR)
2251     goto out;
2252
2253   if (connect (client, (struct sockaddr *) &addr, socklen) == SOCKET_ERROR &&
2254       WSAGetLastError () != WSAEWOULDBLOCK)
2255     goto out;
2256
2257   server = accept (listener, NULL, NULL);
2258   if (server == INVALID_SOCKET)
2259     goto out;
2260
2261   arg = 0;
2262   if (ioctlsocket (client, FIONBIO, &arg) == SOCKET_ERROR)
2263     goto out;
2264
2265   if (WSAIoctl (server, SIO_AF_UNIX_GETPEERPID,
2266                 NULL, 0U,
2267                 &arg, sizeof (arg), &br,
2268                 NULL, NULL) == SOCKET_ERROR || arg != GetCurrentProcessId ())
2269     {
2270       WSASetLastError (WSAEACCES);
2271       goto out;
2272     }
2273
2274   sv[0] = server;
2275   server = INVALID_SOCKET;
2276   sv[1] = client;
2277   client = INVALID_SOCKET;
2278   rv = 0;
2279
2280  out:
2281   if (listener != INVALID_SOCKET)
2282     closesocket (listener);
2283   if (client != INVALID_SOCKET)
2284     closesocket (client);
2285   if (server != INVALID_SOCKET)
2286     closesocket (server);
2287
2288   DeleteFile (path);
2289   g_free (path);
2290   return rv;
2291 }
2292 #endif /* G_OS_WIN32 */
2293
2294 static void
2295 test_credentials_unix_socketpair (void)
2296 {
2297   gint fds[2];
2298   gint status;
2299   GSocket *sock[2];
2300   GError *error = NULL;
2301   GCredentials *creds;
2302
2303 #ifdef G_OS_WIN32
2304   status = _g_win32_socketpair (PF_UNIX, SOCK_STREAM, 0, fds);
2305   if (status != 0)
2306     {
2307       g_test_skip ("AF_UNIX not supported on this Windows system.");
2308       return;
2309     }
2310 #else
2311   status = socketpair (PF_UNIX, SOCK_STREAM, 0, fds);
2312 #endif
2313   g_assert_cmpint (status, ==, 0);
2314
2315   sock[0] = g_socket_new_from_fd (fds[0], &error);
2316   g_assert_no_error (error);
2317   sock[1] = g_socket_new_from_fd (fds[1], &error);
2318   g_assert_no_error (error);
2319
2320   creds = g_socket_get_credentials (sock[0], &error);
2321   if (creds != NULL)
2322     {
2323       gchar *str = g_credentials_to_string (creds);
2324       g_test_message ("Supported on this OS: %s", str);
2325       g_free (str);
2326       g_clear_object (&creds);
2327     }
2328   else
2329     {
2330       g_assert_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED);
2331       g_test_message ("Unsupported on this OS: %s", error->message);
2332       g_clear_error (&error);
2333     }
2334
2335   g_object_unref (sock[0]);
2336   g_object_unref (sock[1]);
2337 }
2338 #endif
2339
2340 int
2341 main (int   argc,
2342       char *argv[])
2343 {
2344   GSocket *sock;
2345   GError *error = NULL;
2346
2347   g_test_init (&argc, &argv, NULL);
2348
2349   sock = g_socket_new (G_SOCKET_FAMILY_IPV6,
2350                        G_SOCKET_TYPE_STREAM,
2351                        G_SOCKET_PROTOCOL_DEFAULT,
2352                        &error);
2353   if (sock != NULL)
2354     {
2355       ipv6_supported = TRUE;
2356       g_object_unref (sock);
2357     }
2358   else
2359     {
2360       g_assert_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED);
2361       g_clear_error (&error);
2362     }
2363
2364   g_test_add_func ("/socket/ipv4_sync", test_ipv4_sync);
2365   g_test_add_func ("/socket/ipv4_async", test_ipv4_async);
2366   g_test_add_func ("/socket/ipv6_sync", test_ipv6_sync);
2367   g_test_add_func ("/socket/ipv6_async", test_ipv6_async);
2368   g_test_add_func ("/socket/ipv4_sync/datagram", test_ipv4_sync_dgram);
2369   g_test_add_func ("/socket/ipv4_sync/datagram/timeouts", test_ipv4_sync_dgram_timeouts);
2370   g_test_add_func ("/socket/ipv6_sync/datagram", test_ipv6_sync_dgram);
2371   g_test_add_func ("/socket/ipv6_sync/datagram/timeouts", test_ipv6_sync_dgram_timeouts);
2372 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2373   g_test_add_func ("/socket/ipv6_v4mapped", test_ipv6_v4mapped);
2374 #endif
2375   g_test_add_func ("/socket/close_graceful", test_close_graceful);
2376   g_test_add_func ("/socket/timed_wait", test_timed_wait);
2377   g_test_add_func ("/socket/fd_reuse", test_fd_reuse);
2378   g_test_add_func ("/socket/address", test_sockaddr);
2379   g_test_add_func ("/socket/unix-from-fd", test_unix_from_fd);
2380   g_test_add_func ("/socket/unix-connection", test_unix_connection);
2381 #ifdef G_OS_UNIX
2382   g_test_add_func ("/socket/unix-connection-ancillary-data", test_unix_connection_ancillary_data);
2383 #endif
2384 #ifdef G_OS_WIN32
2385   g_test_add_func ("/socket/win32-handle-not-socket", test_handle_not_socket);
2386 #endif
2387   g_test_add_func ("/socket/source-postmortem", test_source_postmortem);
2388   g_test_add_func ("/socket/reuse/tcp", test_reuse_tcp);
2389   g_test_add_func ("/socket/reuse/udp", test_reuse_udp);
2390   g_test_add_data_func ("/socket/get_available/datagram", GUINT_TO_POINTER (G_SOCKET_TYPE_DATAGRAM),
2391                         test_get_available);
2392   g_test_add_data_func ("/socket/get_available/stream", GUINT_TO_POINTER (G_SOCKET_TYPE_STREAM),
2393                         test_get_available);
2394   g_test_add_data_func ("/socket/read_write", GUINT_TO_POINTER (FALSE),
2395                         test_read_write);
2396   g_test_add_data_func ("/socket/read_writev", GUINT_TO_POINTER (TRUE),
2397                         test_read_write);
2398 #ifdef SO_NOSIGPIPE
2399   g_test_add_func ("/socket/nosigpipe", test_nosigpipe);
2400 #endif
2401 #if G_CREDENTIALS_SUPPORTED
2402   g_test_add_func ("/socket/credentials/tcp_client", test_credentials_tcp_client);
2403   g_test_add_func ("/socket/credentials/tcp_server", test_credentials_tcp_server);
2404   g_test_add_func ("/socket/credentials/unix_socketpair", test_credentials_unix_socketpair);
2405 #endif
2406
2407   return g_test_run();
2408 }