GSocket: add support for timeouts
[platform/upstream/glib.git] / gio / tests / socket-client.c
1 #include <gio/gio.h>
2 #include <gio/gunixsocketaddress.h>
3 #include <glib.h>
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <string.h>
7
8 #include "socket-common.c"
9
10 GMainLoop *loop;
11
12 gboolean verbose = FALSE;
13 gboolean non_blocking = FALSE;
14 gboolean use_udp = FALSE;
15 gboolean use_source = FALSE;
16 int cancel_timeout = 0;
17 int read_timeout = 0;
18 gboolean unix_socket = FALSE;
19
20 static GOptionEntry cmd_entries[] = {
21   {"cancel", 'c', 0, G_OPTION_ARG_INT, &cancel_timeout,
22    "Cancel any op after the specified amount of seconds", NULL},
23   {"udp", 'u', 0, G_OPTION_ARG_NONE, &use_udp,
24    "Use udp instead of tcp", NULL},
25   {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
26    "Be verbose", NULL},
27   {"non-blocking", 'n', 0, G_OPTION_ARG_NONE, &non_blocking,
28    "Enable non-blocking i/o", NULL},
29   {"use-source", 's', 0, G_OPTION_ARG_NONE, &use_source,
30    "Use GSource to wait for non-blocking i/o", NULL},
31 #ifdef G_OS_UNIX
32   {"unix", 'U', 0, G_OPTION_ARG_NONE, &unix_socket,
33    "Use a unix socket instead of IP", NULL},
34 #endif
35   {"timeout", 't', 0, G_OPTION_ARG_INT, &read_timeout,
36    "Time out reads after the specified number of seconds", NULL},
37   {NULL}
38 };
39
40 static gboolean
41 source_ready (gpointer data,
42               GIOCondition condition)
43 {
44   g_main_loop_quit (loop);
45   return FALSE;
46 }
47
48 static void
49 ensure_condition (GSocket *socket,
50                   const char *where,
51                   GCancellable *cancellable,
52                   GIOCondition condition)
53 {
54   GError *error = NULL;
55   GSource *source;
56
57   if (!non_blocking)
58     return;
59
60   if (use_source)
61     {
62       source = g_socket_create_source (socket,
63                                        condition,
64                                        cancellable);
65       g_source_set_callback (source,
66                              (GSourceFunc) source_ready,
67                              NULL, NULL);
68       g_source_attach (source, NULL);
69       g_source_unref (source);
70       g_main_loop_run (loop);
71     }
72   else
73     {
74       if (!g_socket_condition_wait (socket, condition, cancellable, &error))
75         {
76           g_printerr ("condition wait error for %s: %s\n",
77                       where,
78                       error->message);
79           exit (1);
80         }
81     }
82 }
83
84 static gpointer
85 cancel_thread (gpointer data)
86 {
87   GCancellable *cancellable = data;
88
89   g_usleep (1000*1000*cancel_timeout);
90   g_print ("Cancelling\n");
91   g_cancellable_cancel (cancellable);
92   return NULL;
93 }
94
95 int
96 main (int argc,
97       char *argv[])
98 {
99   GSocket *socket;
100   GSocketAddress *src_address;
101   GSocketAddress *address;
102   GSocketType socket_type;
103   GSocketFamily socket_family;
104   GError *error = NULL;
105   GOptionContext *context;
106   GCancellable *cancellable;
107   GSocketAddressEnumerator *enumerator;
108   GSocketConnectable *connectable;
109
110   g_thread_init (NULL);
111
112   g_type_init ();
113
114   context = g_option_context_new (" <hostname>[:port] - Test GSocket client stuff");
115   g_option_context_add_main_entries (context, cmd_entries, NULL);
116   if (!g_option_context_parse (context, &argc, &argv, &error))
117     {
118       g_printerr ("%s: %s\n", argv[0], error->message);
119       return 1;
120     }
121
122   if (argc != 2)
123     {
124       g_printerr ("%s: %s\n", argv[0], "Need to specify hostname / unix socket name");
125       return 1;
126     }
127
128   if (cancel_timeout)
129     {
130       cancellable = g_cancellable_new ();
131       g_thread_create (cancel_thread, cancellable, FALSE, NULL);
132     }
133   else
134     {
135       cancellable = NULL;
136     }
137
138   loop = g_main_loop_new (NULL, FALSE);
139
140   if (use_udp)
141     socket_type = G_SOCKET_TYPE_DATAGRAM;
142   else
143     socket_type = G_SOCKET_TYPE_STREAM;
144
145   if (unix_socket)
146     socket_family = G_SOCKET_FAMILY_UNIX;
147   else
148     socket_family = G_SOCKET_FAMILY_IPV4;
149
150   socket = g_socket_new (socket_family, socket_type, 0, &error);
151   if (socket == NULL)
152     {
153       g_printerr ("%s: %s\n", argv[0], error->message);
154       return 1;
155     }
156
157   if (read_timeout)
158     g_socket_set_timeout (socket, read_timeout);
159
160   if (unix_socket)
161     {
162       GSocketAddress *addr;
163
164       addr = socket_address_from_string (argv[1]);
165       if (addr == NULL)
166         {
167           g_printerr ("%s: Could not parse '%s' as unix socket name\n", argv[0], argv[1]);
168           return 1;
169         }
170       connectable = G_SOCKET_CONNECTABLE (addr);
171     }
172   else
173     {
174       connectable = g_network_address_parse (argv[1], 7777, &error);
175       if (connectable == NULL)
176         {
177           g_printerr ("%s: %s\n", argv[0], error->message);
178           return 1;
179         }
180     }
181
182   enumerator = g_socket_connectable_enumerate (connectable);
183   while (TRUE)
184     {
185       address = g_socket_address_enumerator_next (enumerator, cancellable, &error);
186       if (address == NULL)
187         {
188           if (error == NULL)
189             g_printerr ("%s: No more addresses to try\n", argv[0]);
190           else
191             g_printerr ("%s: %s\n", argv[0], error->message);
192           return 1;
193         }
194
195       if (g_socket_connect (socket, address, cancellable, &error))
196         break;
197       g_printerr ("%s: Connection to %s failed: %s, trying next\n", argv[0], socket_address_to_string (address), error->message);
198       g_error_free (error);
199       error = NULL;
200
201       g_object_unref (address);
202     }
203   g_object_unref (enumerator);
204   g_object_unref (connectable);
205
206   g_print ("Connected to %s\n",
207            socket_address_to_string (address));
208
209   /* TODO: Test non-blocking connect */
210   if (non_blocking)
211     g_socket_set_blocking (socket, FALSE);
212
213   src_address = g_socket_get_local_address (socket, &error);
214   if (!src_address)
215     {
216       g_printerr ("Error getting local address: %s\n",
217                   error->message);
218       return 1;
219     }
220   g_print ("local address: %s\n",
221            socket_address_to_string (src_address));
222   g_object_unref (src_address);
223
224   while (TRUE)
225     {
226       gchar buffer[4096] = { };
227       gssize size;
228       gsize to_send;
229
230       if (fgets (buffer, sizeof buffer, stdin) == NULL)
231         break;
232
233       to_send = strlen (buffer);
234       while (to_send > 0)
235         {
236           ensure_condition (socket, "send", cancellable, G_IO_OUT);
237           if (use_udp)
238             size = g_socket_send_to (socket, address,
239                                      buffer, to_send,
240                                      cancellable, &error);
241           else
242             size = g_socket_send (socket, buffer, to_send,
243                                   cancellable, &error);
244
245           if (size < 0)
246             {
247               if (g_error_matches (error,
248                                    G_IO_ERROR,
249                                    G_IO_ERROR_WOULD_BLOCK))
250                 {
251                   g_print ("socket send would block, handling\n");
252                   g_error_free (error);
253                   error = NULL;
254                   continue;
255                 }
256               else
257                 {
258                   g_printerr ("Error sending to socket: %s\n",
259                               error->message);
260                   return 1;
261                 }
262             }
263
264           g_print ("sent %" G_GSSIZE_FORMAT " bytes of data\n", size);
265
266           if (size == 0)
267             {
268               g_printerr ("Unexpected short write\n");
269               return 1;
270             }
271
272           to_send -= size;
273         }
274
275       ensure_condition (socket, "receive", cancellable, G_IO_IN);
276       if (use_udp)
277         size = g_socket_receive_from (socket, &src_address,
278                                       buffer, sizeof buffer,
279                                       cancellable, &error);
280       else
281         size = g_socket_receive (socket, buffer, sizeof buffer,
282                                  cancellable, &error);
283
284       if (size < 0)
285         {
286           g_printerr ("Error receiving from socket: %s\n",
287                       error->message);
288           return 1;
289         }
290
291       if (size == 0)
292         break;
293
294       g_print ("received %" G_GSSIZE_FORMAT " bytes of data", size);
295       if (use_udp)
296         g_print (" from %s", socket_address_to_string (src_address));
297       g_print ("\n");
298
299       if (verbose)
300         g_print ("-------------------------\n"
301                  "%.*s"
302                  "-------------------------\n",
303                  (int)size, buffer);
304
305     }
306
307   g_print ("closing socket\n");
308
309   if (!g_socket_close (socket, &error))
310     {
311       g_printerr ("Error closing master socket: %s\n",
312                   error->message);
313       return 1;
314     }
315
316   g_object_unref (G_OBJECT (socket));
317   g_object_unref (G_OBJECT (address));
318
319   return 0;
320 }