Debian Codegraph @

examples/wget.c

raw symbols SCIP
1 /* wget.c
2 *
3 * Copyright 2022 Christian Hergert <[email protected]>
4 *
5 * This library is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License as
7 * published by the Free Software Foundation; either version 2.1 of the
8 * License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 * SPDX-License-Identifier: LGPL-2.1-or-later
19 */
20
21 #include "config.h"
22
23 #ifdef HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26
27 #include <libsoup/soup.h>
28 #include <libdex.h>
29
30 #define PRIO G_PRIORITY_DEFAULT
31
32 static DexFuture *session_send (SoupSession *session,
33 SoupMessage *message,
34 int priority);
35
36 static char *output_document;
37 static char *url;
38 static GMainLoop *main_loop;
39 static int exit_code;
40 static const GOptionEntry entries[] = {
41 { "output-document", 'o', 0,
42 G_OPTION_ARG_FILENAME, &output_document,
43 "write documents to FILE", "FILE" },
44 { NULL }
45 };
46
47 static DexFuture *
48 wget (gpointer user_data)
49 {
50 g_autoptr(GOutputStream) output = NULL;
51 g_autoptr(GInputStream) input = NULL;
52 g_autoptr(SoupMessage) message = NULL;
53 g_autoptr(SoupSession) session = NULL;
54 g_autoptr(GError) error = NULL;
55 g_autoptr(GFile) file = NULL;
56 gssize len;
57
58 /* Create SoupSession used to manage connections */
59 session = soup_session_new_with_options ("user-agent", "libdex-wget",
60 "accept-language-auto", TRUE,
61 "timeout", 15,
62 NULL);
63
64 /* Create SoupMessage to submit request and get response */
65 if (!(message = soup_message_new ("GET", url)))
66 return dex_future_new_reject (G_URI_ERROR,
67 G_URI_ERROR_FAILED,
68 "Failed to parse url \"%s\"", url);
69
70 /* Suspend until we get a response or error */
71 if (!(input = dex_await_object (session_send (session, message, PRIO), &error)))
72 return dex_future_new_for_error (g_steal_pointer (&error));
73
74 /* If output_document is not specified, use the URI to guess a name */
75 if (output_document == NULL)
76 {
77 GUri *uri = soup_message_get_uri (message);
78 const char *path = g_uri_get_path (uri);
79
80 /* Try to get a reasonable name for the file */
81 output_document = path ? g_path_get_basename (path) : g_strdup ("output");
82
83 /* Avoid https://example.com/ having a filename of "/" */
84 if (output_document == NULL || output_document[0] == '/')
85 {
86 g_free (output_document);
87 output_document = g_strdup ("index.html");
88 }
89 }
90
91 /* Suspend while the file at @output_document is created or replaced */
92 file = g_file_new_for_path (output_document);
93 if (!(output = dex_await_object (dex_file_replace (file, NULL, TRUE, G_FILE_CREATE_REPLACE_DESTINATION, PRIO), &error)))
94 return dex_future_new_for_error (g_steal_pointer (&error));
95
96 /* Suspend while the input stream is spliced to our output stream */
97 len = dex_await_int64 (dex_output_stream_splice (output, input, 0, PRIO), &error);
98 if (error != NULL)
99 return dex_future_new_for_error (g_steal_pointer (&error));
100
101 /* Suspend while we wait for @output to close/sync */
102 if (!dex_await_boolean (dex_output_stream_close (output, PRIO), &error))
103 return dex_future_new_for_error (g_steal_pointer (&error));
104
105 /* Return the length copied back */
106 return dex_future_new_for_int64 (len);
107 }
108
109 static DexFuture *
110 fiber_completed (DexFuture *completed,
111 gpointer value)
112 {
113 GError *error = NULL;
114 gssize len;
115
116 /* We can "await" here because we know @completed is a resolved
117 * or rejected future. Otherwise, dex_await() only works on a fiber
118 * to be able to suspend execution until the result is ready.
119 */
120 len = dex_await_int64 (dex_ref (completed), &error);
121
122 /* Give the user some information on success/failure */
123 if (error != NULL)
124 g_printerr ("error: %s\n", error->message);
125 else
126 g_printerr ("wrote %"G_GSSIZE_FORMAT" bytes to \"%s\".\n", len, output_document);
127
128 /* Set exit code for program and exit main loop */
129 exit_code = error != NULL ? EXIT_FAILURE : EXIT_SUCCESS;
130 g_main_loop_quit (main_loop);
131 return NULL;
132 }
133
134 int
135 main (int argc,
136 char *argv[])
137 {
138 GOptionContext *context;
139 DexFuture *future;
140 GError *error = NULL;
141
142 dex_init ();
143
144 context = g_option_context_new ("- a non-interactive network retriever");
145 g_option_context_add_main_entries (context, entries, NULL);
146 if (!g_option_context_parse (context, &argc, &argv, &error))
147 {
148 g_printerr ("%s: %s\n", argv[0], error->message);
149 return EXIT_FAILURE;
150 }
151
152 if (argc != 2)
153 {
154 g_printerr ("usage: %s [OPTIONS...] URL\n", argv[0]);
155 return EXIT_FAILURE;
156 }
157
158 url = g_strdup (argv[1]);
159 main_loop = g_main_loop_new (NULL, FALSE);
160
161 /* Spawn a fiber */
162 future = dex_scheduler_spawn (NULL, 0, wget, NULL, NULL);
163
164 /* Handle resolve/reject of future and exit */
165 future = dex_future_finally (future, fiber_completed, NULL, NULL);
166
167 g_main_loop_run (main_loop);
168
169 dex_unref (future);
170 g_option_context_free (context);
171 g_main_loop_unref (main_loop);
172 g_free (output_document);
173 g_free (url);
174
175 return exit_code;
176 }
177
178 /* This is a GAsyncResult wrapper which converts it into a DexFuture.
179 * DexAsyncPair can be used for simple pairs currently, but lacks support
180 * for additional parameters. I hope to add that in the future though.
181 */
182 static void
183 session_send_cb (GObject *object,
184 GAsyncResult *result,
185 gpointer user_data)
186 {
187 DexAsyncPair *async_pair = user_data;
188 GInputStream *stream;
189 GError *error = NULL;
190
191 stream = soup_session_send_finish (SOUP_SESSION (object), result, &error);
192
193 if (error == NULL)
194 dex_async_pair_return_object (async_pair, stream);
195 else
196 dex_async_pair_return_error (async_pair, error);
197
198 dex_unref (async_pair);
199 }
200
201 static DexFuture *
202 session_send (SoupSession *session,
203 SoupMessage *message,
204 int priority)
205 {
206 DexAsyncPair *async_pair;
207
208 g_return_val_if_fail (SOUP_IS_SESSION (session), NULL);
209 g_return_val_if_fail (SOUP_IS_MESSAGE (message), NULL);
210
211 async_pair = (DexAsyncPair *)g_type_create_instance (DEX_TYPE_ASYNC_PAIR);
212 soup_session_send_async (session, message, priority,
213 dex_async_pair_get_cancellable (async_pair),
214 session_send_cb,
215 dex_ref (async_pair));
216 return DEX_FUTURE (async_pair);
217 }