tls: Make g_tls_{client|server}_connection_new() return a GIOStream
[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 GMainLoop *loop;
9
10 gboolean verbose = FALSE;
11 gboolean non_blocking = FALSE;
12 gboolean use_udp = FALSE;
13 int cancel_timeout = 0;
14 int read_timeout = 0;
15 gboolean unix_socket = FALSE;
16 gboolean tls = FALSE;
17
18 static GOptionEntry cmd_entries[] = {
19   {"cancel", 'c', 0, G_OPTION_ARG_INT, &cancel_timeout,
20    "Cancel any op after the specified amount of seconds", NULL},
21   {"udp", 'u', 0, G_OPTION_ARG_NONE, &use_udp,
22    "Use udp instead of tcp", NULL},
23   {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
24    "Be verbose", NULL},
25   {"non-blocking", 'n', 0, G_OPTION_ARG_NONE, &non_blocking,
26    "Enable non-blocking i/o", NULL},
27 #ifdef G_OS_UNIX
28   {"unix", 'U', 0, G_OPTION_ARG_NONE, &unix_socket,
29    "Use a unix socket instead of IP", NULL},
30 #endif
31   {"timeout", 't', 0, G_OPTION_ARG_INT, &read_timeout,
32    "Time out reads after the specified number of seconds", NULL},
33   {"tls", 'T', 0, G_OPTION_ARG_NONE, &tls,
34    "Use TLS (SSL)", NULL},
35   {NULL}
36 };
37
38 #include "socket-common.c"
39
40 static gboolean
41 accept_certificate (GTlsClientConnection *conn, GTlsCertificate *cert,
42                     GTlsCertificateFlags errors, gpointer user_data)
43 {
44   g_print ("Certificate would have been rejected ( ");
45   if (errors & G_TLS_CERTIFICATE_UNKNOWN_CA)
46     g_print ("unknown-ca ");
47   if (errors & G_TLS_CERTIFICATE_BAD_IDENTITY)
48     g_print ("bad-identity ");
49   if (errors & G_TLS_CERTIFICATE_NOT_ACTIVATED)
50     g_print ("not-activated ");
51   if (errors & G_TLS_CERTIFICATE_EXPIRED)
52     g_print ("expired ");
53   if (errors & G_TLS_CERTIFICATE_REVOKED)
54     g_print ("revoked ");
55   if (errors & G_TLS_CERTIFICATE_INSECURE)
56     g_print ("insecure ");
57   g_print (") but accepting anyway.\n");
58
59   return TRUE;
60 }
61
62 int
63 main (int argc,
64       char *argv[])
65 {
66   GSocket *socket;
67   GSocketAddress *src_address;
68   GSocketAddress *address;
69   GSocketType socket_type;
70   GSocketFamily socket_family;
71   GError *error = NULL;
72   GOptionContext *context;
73   GCancellable *cancellable;
74   GSocketAddressEnumerator *enumerator;
75   GSocketConnectable *connectable;
76   GIOStream *connection;
77   GInputStream *istream;
78   GOutputStream *ostream;
79
80   g_thread_init (NULL);
81
82   g_type_init ();
83
84   context = g_option_context_new (" <hostname>[:port] - Test GSocket client stuff");
85   g_option_context_add_main_entries (context, cmd_entries, NULL);
86   if (!g_option_context_parse (context, &argc, &argv, &error))
87     {
88       g_printerr ("%s: %s\n", argv[0], error->message);
89       return 1;
90     }
91
92   if (argc != 2)
93     {
94       g_printerr ("%s: %s\n", argv[0], "Need to specify hostname / unix socket name");
95       return 1;
96     }
97
98   if (use_udp && tls)
99     {
100       g_printerr ("DTLS (TLS over UDP) is not supported");
101       return 1;
102     }
103
104   if (cancel_timeout)
105     {
106       cancellable = g_cancellable_new ();
107       g_thread_create (cancel_thread, cancellable, FALSE, NULL);
108     }
109   else
110     {
111       cancellable = NULL;
112     }
113
114   loop = g_main_loop_new (NULL, FALSE);
115
116   if (use_udp)
117     socket_type = G_SOCKET_TYPE_DATAGRAM;
118   else
119     socket_type = G_SOCKET_TYPE_STREAM;
120
121   if (unix_socket)
122     socket_family = G_SOCKET_FAMILY_UNIX;
123   else
124     socket_family = G_SOCKET_FAMILY_IPV4;
125
126   socket = g_socket_new (socket_family, socket_type, 0, &error);
127   if (socket == NULL)
128     {
129       g_printerr ("%s: %s\n", argv[0], error->message);
130       return 1;
131     }
132
133   if (read_timeout)
134     g_socket_set_timeout (socket, read_timeout);
135
136   if (unix_socket)
137     {
138       GSocketAddress *addr;
139
140       addr = socket_address_from_string (argv[1]);
141       if (addr == NULL)
142         {
143           g_printerr ("%s: Could not parse '%s' as unix socket name\n", argv[0], argv[1]);
144           return 1;
145         }
146       connectable = G_SOCKET_CONNECTABLE (addr);
147     }
148   else
149     {
150       connectable = g_network_address_parse (argv[1], 7777, &error);
151       if (connectable == NULL)
152         {
153           g_printerr ("%s: %s\n", argv[0], error->message);
154           return 1;
155         }
156     }
157
158   enumerator = g_socket_connectable_enumerate (connectable);
159   while (TRUE)
160     {
161       address = g_socket_address_enumerator_next (enumerator, cancellable, &error);
162       if (address == NULL)
163         {
164           if (error == NULL)
165             g_printerr ("%s: No more addresses to try\n", argv[0]);
166           else
167             g_printerr ("%s: %s\n", argv[0], error->message);
168           return 1;
169         }
170
171       if (g_socket_connect (socket, address, cancellable, &error))
172         break;
173       g_printerr ("%s: Connection to %s failed: %s, trying next\n", argv[0], socket_address_to_string (address), error->message);
174       g_error_free (error);
175       error = NULL;
176
177       g_object_unref (address);
178     }
179   g_object_unref (enumerator);
180
181   g_print ("Connected to %s\n",
182            socket_address_to_string (address));
183
184   src_address = g_socket_get_local_address (socket, &error);
185   if (!src_address)
186     {
187       g_printerr ("Error getting local address: %s\n",
188                   error->message);
189       return 1;
190     }
191   g_print ("local address: %s\n",
192            socket_address_to_string (src_address));
193   g_object_unref (src_address);
194
195   if (use_udp)
196     {
197       connection = NULL;
198       istream = NULL;
199       ostream = NULL;
200     }
201   else
202     connection = G_IO_STREAM (g_socket_connection_factory_create_connection (socket));
203
204   if (tls)
205     {
206       GIOStream *tls_conn;
207
208       tls_conn = g_tls_client_connection_new (connection, connectable, &error);
209       if (!tls_conn)
210         {
211           g_printerr ("Could not create TLS connection: %s\n",
212                       error->message);
213           return 1;
214         }
215
216       g_signal_connect (tls_conn, "accept-certificate",
217                         G_CALLBACK (accept_certificate), NULL);
218
219       if (!g_tls_connection_handshake (G_TLS_CONNECTION (tls_conn),
220                                        cancellable, &error))
221         {
222           g_printerr ("Error during TLS handshake: %s\n",
223                       error->message);
224           return 1;
225         }
226
227       g_object_unref (connection);
228       connection = G_IO_STREAM (tls_conn);
229     }
230   g_object_unref (connectable);
231
232   if (connection)
233     {
234       istream = g_io_stream_get_input_stream (connection);
235       ostream = g_io_stream_get_output_stream (connection);
236     }
237
238   /* TODO: Test non-blocking connect/handshake */
239   if (non_blocking)
240     g_socket_set_blocking (socket, FALSE);
241
242   while (TRUE)
243     {
244       gchar buffer[4096];
245       gssize size;
246       gsize to_send;
247
248       if (fgets (buffer, sizeof buffer, stdin) == NULL)
249         break;
250
251       to_send = strlen (buffer);
252       while (to_send > 0)
253         {
254           if (use_udp)
255             {
256               ensure_socket_condition (socket, G_IO_OUT, cancellable);
257               size = g_socket_send_to (socket, address,
258                                        buffer, to_send,
259                                        cancellable, &error);
260             }
261           else
262             {
263               ensure_connection_condition (connection, G_IO_OUT, cancellable);
264               size = g_output_stream_write (ostream,
265                                             buffer, to_send,
266                                             cancellable, &error);
267             }
268
269           if (size < 0)
270             {
271               if (g_error_matches (error,
272                                    G_IO_ERROR,
273                                    G_IO_ERROR_WOULD_BLOCK))
274                 {
275                   g_print ("socket send would block, handling\n");
276                   g_error_free (error);
277                   error = NULL;
278                   continue;
279                 }
280               else
281                 {
282                   g_printerr ("Error sending to socket: %s\n",
283                               error->message);
284                   return 1;
285                 }
286             }
287
288           g_print ("sent %" G_GSSIZE_FORMAT " bytes of data\n", size);
289
290           if (size == 0)
291             {
292               g_printerr ("Unexpected short write\n");
293               return 1;
294             }
295
296           to_send -= size;
297         }
298
299       if (use_udp)
300         {
301           ensure_socket_condition (socket, G_IO_IN, cancellable);
302           size = g_socket_receive_from (socket, &src_address,
303                                         buffer, sizeof buffer,
304                                         cancellable, &error);
305         }
306       else
307         {
308           ensure_connection_condition (connection, G_IO_IN, cancellable);
309           size = g_input_stream_read (istream,
310                                       buffer, sizeof buffer,
311                                       cancellable, &error);
312         }
313
314       if (size < 0)
315         {
316           g_printerr ("Error receiving from socket: %s\n",
317                       error->message);
318           return 1;
319         }
320
321       if (size == 0)
322         break;
323
324       g_print ("received %" G_GSSIZE_FORMAT " bytes of data", size);
325       if (use_udp)
326         g_print (" from %s", socket_address_to_string (src_address));
327       g_print ("\n");
328
329       if (verbose)
330         g_print ("-------------------------\n"
331                  "%.*s"
332                  "-------------------------\n",
333                  (int)size, buffer);
334
335     }
336
337   g_print ("closing socket\n");
338
339   if (connection)
340     {
341       if (!g_io_stream_close (connection, cancellable, &error))
342         {
343           g_printerr ("Error closing connection: %s\n",
344                       error->message);
345           return 1;
346         }
347       g_object_unref (connection);
348     }
349   else
350     {
351       if (!g_socket_close (socket, &error))
352         {
353           g_printerr ("Error closing master socket: %s\n",
354                       error->message);
355           return 1;
356         }
357     }
358
359   g_object_unref (socket);
360   g_object_unref (address);
361
362   return 0;
363 }