File: wget.c

package info (click to toggle)
libdex 1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,136 kB
  • sloc: ansic: 13,114; asm: 226; makefile: 22; sh: 6; javascript: 5
file content (215 lines) | stat: -rw-r--r-- 6,932 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/* wget.c
 *
 * Copyright 2022 Christian Hergert <chergert@redhat.com>
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

#include "config.h"

#include <unistd.h>

#include <libsoup/soup.h>
#include <libdex.h>

#define PRIO G_PRIORITY_DEFAULT

static DexFuture *session_send (SoupSession *session,
                                SoupMessage *message,
                                int          priority);

static char *output_document;
static char *url;
static GMainLoop *main_loop;
static int exit_code;
static const GOptionEntry entries[] = {
  { "output-document", 'o', 0,
    G_OPTION_ARG_FILENAME, &output_document,
    "write documents to FILE", "FILE" },
  { NULL }
};

static DexFuture *
wget (gpointer user_data)
{
  g_autoptr(GOutputStream) output = NULL;
  g_autoptr(GInputStream) input = NULL;
  g_autoptr(SoupMessage) message = NULL;
  g_autoptr(SoupSession) session = NULL;
  g_autoptr(GError) error = NULL;
  g_autoptr(GFile) file = NULL;
  gssize len;

  /* Create SoupSession used to manage connections */
  session = soup_session_new_with_options ("user-agent", "libdex-wget",
                                           "accept-language-auto", TRUE,
                                           "timeout", 15,
                                           NULL);

  /* Create SoupMessage to submit request and get response */
  if (!(message = soup_message_new ("GET", url)))
    return dex_future_new_reject (G_URI_ERROR,
                                  G_URI_ERROR_FAILED,
                                  "Failed to parse url \"%s\"", url);

  /* Suspend until we get a response or error */
  if (!(input = dex_await_object (session_send (session, message, PRIO), &error)))
    return dex_future_new_for_error (g_steal_pointer (&error));

  /* If output_document is not specified, use the URI to guess a name */
  if (output_document == NULL)
    {
      GUri *uri = soup_message_get_uri (message);
      const char *path = g_uri_get_path (uri);

      /* Try to get a reasonable name for the file */
      output_document = path ? g_path_get_basename (path) : g_strdup ("output");

      /* Avoid https://example.com/ having a filename of "/" */
      if (output_document == NULL || output_document[0] == '/')
        {
          g_free (output_document);
          output_document = g_strdup ("index.html");
        }
    }

  /* Suspend while the file at @output_document is created or replaced */
  file = g_file_new_for_path (output_document);
  if (!(output = dex_await_object (dex_file_replace (file, NULL, TRUE, G_FILE_CREATE_REPLACE_DESTINATION, PRIO), &error)))
    return dex_future_new_for_error (g_steal_pointer (&error));

  /* Suspend while the input stream is spliced to our output stream */
  len = dex_await_int64 (dex_output_stream_splice (output, input, 0, PRIO), &error);
  if (error != NULL)
    return dex_future_new_for_error (g_steal_pointer (&error));

  /* Suspend while we wait for @output to close/sync */
  if (!dex_await_boolean (dex_output_stream_close (output, PRIO), &error))
    return dex_future_new_for_error (g_steal_pointer (&error));

  /* Return the length copied back */
  return dex_future_new_for_int64 (len);
}

static DexFuture *
fiber_completed (DexFuture *completed,
                 gpointer   value)
{
  GError *error = NULL;
  gssize len;

  /* We can "await" here because we know @completed is a resolved
   * or rejected future. Otherwise, dex_await() only works on a fiber
   * to be able to suspend execution until the result is ready.
   */
  len = dex_await_int64 (dex_ref (completed), &error);

  /* Give the user some information on success/failure */
  if (error != NULL)
    g_printerr ("error: %s\n", error->message);
  else
    g_printerr ("wrote %"G_GSSIZE_FORMAT" bytes to \"%s\".\n", len, output_document);

  /* Set exit code for program and exit main loop */
  exit_code = error != NULL ? EXIT_FAILURE : EXIT_SUCCESS;
  g_main_loop_quit (main_loop);
  return NULL;
}

int
main (int argc,
      char *argv[])
{
  GOptionContext *context;
  DexFuture *future;
  GError *error = NULL;

  dex_init ();

  context = g_option_context_new ("- a non-interactive network retriever");
  g_option_context_add_main_entries (context, entries, NULL);
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("%s: %s\n", argv[0], error->message);
      return EXIT_FAILURE;
    }

  if (argc != 2)
    {
      g_printerr ("usage: %s [OPTIONS...] URL\n", argv[0]);
      return EXIT_FAILURE;
    }

  url = g_strdup (argv[1]);
  main_loop = g_main_loop_new (NULL, FALSE);

  /* Spawn a fiber */
  future = dex_scheduler_spawn (NULL, 0, wget, NULL, NULL);

  /* Handle resolve/reject of future and exit */
  future = dex_future_finally (future, fiber_completed, NULL, NULL);

  g_main_loop_run (main_loop);

  dex_unref (future);
  g_option_context_free (context);
  g_main_loop_unref (main_loop);
  g_free (output_document);
  g_free (url);

  return exit_code;
}

/* This is a GAsyncResult wrapper which converts it into a DexFuture.
 * DexAsyncPair can be used for simple pairs currently, but lacks support
 * for additional parameters. I hope to add that in the future though.
 */
static void
session_send_cb (GObject      *object,
                 GAsyncResult *result,
                 gpointer      user_data)
{
  DexAsyncPair *async_pair = user_data;
  GInputStream *stream;
  GError *error = NULL;

  stream = soup_session_send_finish (SOUP_SESSION (object), result, &error);

  if (error == NULL)
    dex_async_pair_return_object (async_pair, stream);
  else
    dex_async_pair_return_error (async_pair, error);

  dex_unref (async_pair);
}

static DexFuture *
session_send (SoupSession *session,
              SoupMessage *message,
              int          priority)
{
  DexAsyncPair *async_pair;

  g_return_val_if_fail (SOUP_IS_SESSION (session), NULL);
  g_return_val_if_fail (SOUP_IS_MESSAGE (message), NULL);

  async_pair = (DexAsyncPair *)g_type_create_instance (DEX_TYPE_ASYNC_PAIR);
  soup_session_send_async (session, message, priority,
                           dex_async_pair_get_cancellable (async_pair),
                           session_send_cb,
                           dex_ref (async_pair));
  return DEX_FUTURE (async_pair);
}