summaryrefslogtreecommitdiffstats
path: root/tests/src/vfs/extfs/helpers-list/mc_parse_ls_l.c
blob: 8c1889e3a79ec8a3ff34731f5a13ba4c43479b14 (plain)
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*
   A parser for file-listings formatted like 'ls -l'.

   Copyright (C) 2016-2024
   Free Software Foundation, Inc.

   This file is part of the Midnight Commander.

   The Midnight Commander is free software: you can redistribute it
   and/or modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation, either version 3 of the License,
   or (at your option) any later version.

   The Midnight Commander 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 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/>.
 */

/** \file
 *  \brief A parser for file-listings formatted like 'ls -l'.
 *
 * This program parses file-listings the same way MC does.
 * It's basically a wrapper around vfs_parse_ls_lga().
 * You can feed it the output of any of extfs's helpers.
 *
 * After parsing, the data is written out to stdout. The output
 * format can be either YAML or a format similar to 'ls -l'.
 *
 * This program is the main tool our tester script is going to use.
 */

#include <config.h>

#include <stdio.h>
#include <stdlib.h>

#include "lib/global.h"

#include "lib/vfs/utilvfs.h"    /* vfs_parse_ls_lga() */
#include "lib/util.h"           /* string_perm() */
#include "lib/timefmt.h"        /* FMT_LOCALTIME */
#include "lib/widget.h"         /* for the prototype of message() only */

/*** global variables ****************************************************************************/

/*** file scope macro definitions ****************************************************************/

/*** file scope type declarations ****************************************************************/

typedef enum
{
    FORMAT_YAML,
    FORMAT_LS
} output_format_t;

/*** forward declarations (file scope functions) *************************************************/

static gboolean
parse_format_name_argument (const gchar * option_name, const gchar * value, gpointer data,
                            GError ** error);

/*** file scope variables ************************************************************************/

/* Command-line options. */
static gboolean opt_drop_mtime = FALSE;
static gboolean opt_drop_ids = FALSE;
static gboolean opt_symbolic_ids = FALSE;
static output_format_t opt_output_format = FORMAT_LS;

/* Misc. */
static int error_count = 0;

static GOptionEntry entries[] = {
    {"drop-mtime", 0, 0, G_OPTION_ARG_NONE, &opt_drop_mtime, "Don't include mtime in the output.",
     NULL},
    {"drop-ids", 0, 0, G_OPTION_ARG_NONE, &opt_drop_ids, "Don't include uid/gid in the output.",
     NULL},
    {"symbolic-ids", 0, 0, G_OPTION_ARG_NONE, &opt_symbolic_ids,
     "Print the strings '<<uid>>'/'<<gid>>' instead of the numeric IDs when they match the process' uid/gid.",
     NULL},
    {"format", 'f', 0, G_OPTION_ARG_CALLBACK, parse_format_name_argument,
     "Output format. Default: ls.", "<ls|yaml>"},
    G_OPTION_ENTRY_NULL
};

/* --------------------------------------------------------------------------------------------- */
/*** file scope functions ************************************************************************/
/* --------------------------------------------------------------------------------------------- */
/**
 * Command-line handling.
 */
/* --------------------------------------------------------------------------------------------- */

static gboolean
parse_format_name_argument (const gchar * option_name, const gchar * value, gpointer data,
                            GError ** error)
{
    (void) option_name;
    (void) data;

    if (strcmp (value, "yaml") == 0)
        opt_output_format = FORMAT_YAML;
    else if (strcmp (value, "ls") == 0)
        opt_output_format = FORMAT_LS;
    else
    {
        g_set_error (error, MC_ERROR, G_OPTION_ERROR_FAILED, "unknown output format '%s'", value);
        return FALSE;
    }

    return TRUE;
}

/* --------------------------------------------------------------------------------------------- */

static gboolean
parse_command_line (int *argc, char **argv[])
{
    GError *error = NULL;
    GOptionContext *context;

    context =
        g_option_context_new
        ("- Parses its input, which is expected to be in a format similar to 'ls -l', and writes the result to stdout.");
    g_option_context_add_main_entries (context, entries, NULL);
    if (!g_option_context_parse (context, argc, argv, &error))
    {
        g_print ("option parsing failed: %s\n", error->message);
        g_error_free (error);

        return FALSE;
    }

    return TRUE;
}

/* --------------------------------------------------------------------------------------------- */
/**
 * Utility functions.
 */
/* --------------------------------------------------------------------------------------------- */

static const char *
my_itoa (int i)
{
    static char buf[BUF_SMALL];

    sprintf (buf, "%d", i);
    return buf;
}

/* --------------------------------------------------------------------------------------------- */

/**
 * Returns the uid as-is, or as "<<uid>>" if the same as current user.
 */
static const char *
symbolic_uid (uid_t uid)
{
    return (opt_symbolic_ids && uid == getuid ())? "<<uid>>" : my_itoa ((int) uid);
}

/* --------------------------------------------------------------------------------------------- */

static const char *
symbolic_gid (gid_t gid)
{
    return (opt_symbolic_ids && gid == getgid ())? "<<gid>>" : my_itoa ((int) gid);
}

/* --------------------------------------------------------------------------------------------- */

/**
 * Cuts off a string's line-end (as in Perl).
 */
static void
chomp (char *s)
{
    int i;

    i = strlen (s);

    /* Code taken from vfs_parse_ls_lga(), with modifications. */
    if ((--i >= 0) && (s[i] == '\r' || s[i] == '\n'))
        s[i] = '\0';
    if ((--i >= 0) && (s[i] == '\r' || s[i] == '\n'))
        s[i] = '\0';
}

/* --------------------------------------------------------------------------------------------- */

static const char *
string_date (time_t t)
{
    static char buf[BUF_SMALL];

    /*
     * If we ever want to be able to re-parse the output of this program,
     * we'll need to use the American brain-damaged MM-DD-YYYY instead of
     * YYYY-MM-DD because vfs_parse_ls_lga() doesn't currently recognize
     * the latter.
     */
    FMT_LOCALTIME (buf, sizeof buf, "%Y-%m-%d %H:%M:%S", t);
    return buf;
}

/* --------------------------------------------------------------------------------------------- */

/**
 * Override MC's message().
 *
 * vfs_parse_ls_lga() calls this on error. Since MC's uses tty/widgets, it
 * will crash us. We replace it with a plain version.
 */
void
message (int flags, const char *title, const char *text, ...)
{
    char *p;
    va_list ap;

    (void) flags;
    (void) title;

    va_start (ap, text);
    p = g_strdup_vprintf (text, ap);
    va_end (ap);
    printf ("message(): vfs_parse_ls_lga(): parsing error at: %s\n", p);
    g_free (p);
}

/* --------------------------------------------------------------------------------------------- */
/**
 * YAML output format.
 */
/* --------------------------------------------------------------------------------------------- */

static void
yaml_dump_stbuf (const struct stat *st)
{
    /* Various casts and flags here were taken/inspired by info_show_info(). */
    printf ("  perm: %s\n", string_perm (st->st_mode));
    if (!opt_drop_ids)
    {
        printf ("  uid: %s\n", symbolic_uid (st->st_uid));
        printf ("  gid: %s\n", symbolic_gid (st->st_gid));
    }
    printf ("  size: %" PRIuMAX "\n", (uintmax_t) st->st_size);
    printf ("  nlink: %d\n", (int) st->st_nlink);
    if (!opt_drop_mtime)
        printf ("  mtime: %s\n", string_date (st->st_mtime));
}

/* --------------------------------------------------------------------------------------------- */

static void
yaml_dump_string (const char *name, const char *val)
{
    char *q;

    q = g_shell_quote (val);
    printf ("  %s: %s\n", name, q);
    g_free (q);
}

/* --------------------------------------------------------------------------------------------- */

static void
yaml_dump_record (gboolean success, const char *input_line, const struct stat *st,
                  const char *filename, const char *linkname)
{
    printf ("-\n");             /* Start new item in the list. */

    if (success)
    {
        if (filename != NULL)
            yaml_dump_string ("name", filename);
        if (linkname != NULL)
            yaml_dump_string ("linkname", linkname);
        yaml_dump_stbuf (st);
    }
    else
    {
        yaml_dump_string ("cannot parse input line", input_line);
    }
}

/* --------------------------------------------------------------------------------------------- */
/**
 * 'ls' output format.
 */
/* --------------------------------------------------------------------------------------------- */

static void
ls_dump_stbuf (const struct stat *st)
{
    /* Various casts and flags here were taken/inspired by info_show_info(). */
    printf ("%s %3d ", string_perm (st->st_mode), (int) st->st_nlink);
    if (!opt_drop_ids)
    {
        printf ("%8s ", symbolic_uid (st->st_uid));
        printf ("%8s ", symbolic_gid (st->st_gid));
    }
    printf ("%10" PRIuMAX " ", (uintmax_t) st->st_size);
    if (!opt_drop_mtime)
        printf ("%s ", string_date (st->st_mtime));
}

/* --------------------------------------------------------------------------------------------- */

static void
ls_dump_record (gboolean success, const char *input_line, const struct stat *st,
                const char *filename, const char *linkname)
{
    if (success)
    {
        ls_dump_stbuf (st);
        if (filename != NULL)
            printf ("%s", filename);
        if (linkname != NULL)
            printf (" -> %s", linkname);
        printf ("\n");
    }
    else
    {
        printf ("cannot parse input line: '%s'\n", input_line);
    }
}

/* ------------------------------------------------------------------------------ */
/**
 * Main code.
 */
/* ------------------------------------------------------------------------------ */

static void
process_ls_line (const char *line)
{
    struct stat st;
    char *filename, *linkname;
    gboolean success;

    memset (&st, 0, sizeof st);
    filename = NULL;
    linkname = NULL;

    success = vfs_parse_ls_lga (line, &st, &filename, &linkname, NULL);

    if (!success)
        error_count++;

    if (opt_output_format == FORMAT_YAML)
        yaml_dump_record (success, line, &st, filename, linkname);
    else
        ls_dump_record (success, line, &st, filename, linkname);

    g_free (filename);
    g_free (linkname);
}

/* ------------------------------------------------------------------------------ */

static void
process_input (FILE * input)
{
    char line[BUF_4K];

    while (fgets (line, sizeof line, input) != NULL)
    {
        chomp (line);           /* Not mandatory. Makes error messages nicer. */
        if (strncmp (line, "total ", 6) == 0)   /* Convenience only: makes 'ls -l' parse cleanly. */
            continue;
        process_ls_line (line);
    }
}

/* ------------------------------------------------------------------------------ */

int
main (int argc, char *argv[])
{
    FILE *input;

    if (!parse_command_line (&argc, &argv))
        return EXIT_FAILURE;

    if (argc >= 2)
    {
        input = fopen (argv[1], "r");
        if (input == NULL)
        {
            perror (argv[1]);
            return EXIT_FAILURE;
        }
    }
    else
    {
        input = stdin;
    }

    process_input (input);

    return (error_count > 0) ? EXIT_FAILURE : EXIT_SUCCESS;
}

/* ------------------------------------------------------------------------------ */