summaryrefslogtreecommitdiff
path: root/src/install.c
blob: bca4b09eee0e40fc5ee8df448b160af4bbc25708 (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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
/* vim: set ts=2 sw=2 et: */

/*
 * Copyright (C) 2002, 2004  Red Hat, Inc.
 * Copyright (C) 2006-2008  Vincent Untz
 *
 * Program written by Havoc Pennington <hp@pobox.com>
 *                    Ray Strode <rstrode@redhat.com>
 *                    Vincent Untz <vuntz@gnome.org>
 *
 * update-desktop-database 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 2 of the
 * License, or (at your option) any later version.
 *
 * update-desktop-database 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 update-desktop-database; see the file COPYING.  If not,
 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite
 * 330, Boston, MA 02111-1307, USA.
 */

#include <config.h>

#include <glib.h>
#include <glib/gstdio.h>
#include <glib/gi18n.h>

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <locale.h>

#include "keyfileutils.h"
#include "validate.h"

static const char** args = NULL;
static gboolean delete_original = FALSE;
static gboolean rebuild_mime_info_cache = FALSE;
static char *vendor_name = NULL;
static char *target_dir = NULL;
static GSList *edit_actions = NULL;
static mode_t permissions = 0644;

typedef enum
{
  DFU_REMOVE_KEY,
  DFU_ADD_TO_LIST,
  DFU_REMOVE_FROM_LIST,
  DFU_COPY_KEY
} DfuEditActionType;

typedef struct
{
  DfuEditActionType  type;
  char              *key;
  char              *action_value;
} DfuEditAction;

static DfuEditAction *
dfu_edit_action_new (DfuEditActionType  type,
                     const char        *key,
                     const char        *action_value)
{
  DfuEditAction *action;

  action = g_slice_new0 (DfuEditAction);
  action->type = type;
  action->key = g_strdup (key);
  action->action_value = g_strdup (action_value);

  return action;
}

static void
dfu_edit_action_free (DfuEditAction *action)
{
  g_assert (action != NULL);

  g_free (action->key);
  g_free (action->action_value);

  g_slice_free (DfuEditAction, action);
}

static gboolean
files_are_the_same (const char *first,
                    const char *second)
{
  /* This check gets confused by hard links.
   * but it's too annoying to check if two
   * paths are the same (though I'm sure there's a
   * "path canonicalizer" I should be using...)
   */

  struct stat first_sb;
  struct stat second_sb;

  if (stat (first, &first_sb) < 0)
    {
      g_printerr (_("Could not stat \"%s\": %s\n"), first, g_strerror (errno));
      return TRUE;
    }

  if (stat (second, &second_sb) < 0)
    {
      g_printerr (_("Could not stat \"%s\": %s\n"), first, g_strerror (errno));
      return TRUE;
    }

  return ((first_sb.st_dev == second_sb.st_dev) &&
          (first_sb.st_ino == second_sb.st_ino) &&
          /* Broken paranoia in case an OS doesn't use inodes or something */
          (first_sb.st_size == second_sb.st_size) &&
          (first_sb.st_mtime == second_sb.st_mtime));
}

static gboolean
rebuild_cache (const char  *dir,
               GError     **err)
{
  GError *spawn_error;
  char *argv[4] = { "update-desktop-database", "-q", (char *) dir, NULL };
  int exit_status;
  gboolean retval;

  spawn_error = NULL;

  retval = g_spawn_sync (NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
                         NULL, NULL, &exit_status, &spawn_error);

  if (spawn_error != NULL)
    {
      g_propagate_error (err, spawn_error);
      return FALSE;
    }

  return exit_status == 0 && retval;
}

static void
process_one_file (const char *filename,
                  GError    **err)
{
  char *new_filename;
  char *dirname;
  char *basename;
  GKeyFile *kf = NULL;
  GError *rebuild_error;
  GSList *tmp;

  kf = g_key_file_new ();
  if (!g_key_file_load_from_file (kf, filename,
                                  G_KEY_FILE_KEEP_COMMENTS|
                                  G_KEY_FILE_KEEP_TRANSLATIONS,
                                  err)) {
    g_key_file_free (kf);
    return;
  }

  if (!desktop_file_fixup (kf, filename)) {
    g_key_file_free (kf);
    g_set_error (err, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_PARSE,
                 _("Failed to fix the content of the desktop file"));
    return;
  }

  /* Mark file as having been processed by us, so automated
   * tools can check that desktop files went through our
   * munging
   */
  g_key_file_set_string (kf, GROUP_DESKTOP_ENTRY,
                         "X-Desktop-File-Install-Version", VERSION);

  tmp = edit_actions;
  while (tmp != NULL)
    {
      DfuEditAction *action = tmp->data;

      switch (action->type)
        {
          case DFU_REMOVE_KEY:
            g_key_file_remove_key (kf, GROUP_DESKTOP_ENTRY,
                                   action->key, NULL);
            break;
          case DFU_ADD_TO_LIST:
            dfu_key_file_merge_list (kf, GROUP_DESKTOP_ENTRY,
                                     action->key, action->action_value);
            break;
          case DFU_REMOVE_FROM_LIST:
            dfu_key_file_remove_list (kf, GROUP_DESKTOP_ENTRY,
                                      action->key, action->action_value);
            break;
          case DFU_COPY_KEY:
            dfu_key_file_copy_key (kf, GROUP_DESKTOP_ENTRY, action->key,
                                   GROUP_DESKTOP_ENTRY, action->action_value);
            break;
          default:
            g_assert_not_reached ();
        }

      tmp = tmp->next;
    }

  dirname = g_path_get_dirname (filename);
  basename = g_path_get_basename (filename);

  if (vendor_name && !g_str_has_prefix (basename, vendor_name))
    {
      char *new_base;
      new_base = g_strconcat (vendor_name, "-", basename, NULL);
      new_filename = g_build_filename (target_dir, new_base, NULL);
      g_free (new_base);
    }
  else
    {
      new_filename = g_build_filename (target_dir, basename, NULL);
    }

  g_free (dirname);
  g_free (basename);

  if (!dfu_key_file_to_file (kf, new_filename, err)) {
    g_key_file_free (kf);
    g_free (new_filename);
    return;
  }

  g_key_file_free (kf);

  /* Load and validate the file we just wrote */
  if (!desktop_file_validate (new_filename, FALSE, TRUE))
    {
      g_set_error (err, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_PARSE,
                   _("Failed to validate the created desktop file"));

      if (!files_are_the_same (filename, new_filename))
        g_unlink (new_filename);

      g_free (new_filename);
      return;
    }

  if (g_chmod (new_filename, permissions) < 0)
    {
      g_set_error (err, G_FILE_ERROR,
                   g_file_error_from_errno (errno),
                   _("Failed to set permissions %o on \"%s\": %s"),
                   permissions, new_filename, g_strerror (errno));

      if (!files_are_the_same (filename, new_filename))
        g_unlink (new_filename);

      g_free (new_filename);
      return;
    }

  if (delete_original &&
      !files_are_the_same (filename, new_filename))
    {
      if (g_unlink (filename) < 0)
        g_printerr (_("Error removing original file \"%s\": %s\n"),
                    filename, g_strerror (errno));
    }

  if (rebuild_mime_info_cache)
    {
      rebuild_error = NULL;
      rebuild_cache (target_dir, &rebuild_error);

      if (rebuild_error != NULL)
        g_propagate_error (err, rebuild_error);
    }

  g_free (new_filename);
}

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

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


static const GOptionEntry options[] = {
  {
    "delete-original",
    '\0',
    '\0',
    G_OPTION_ARG_NONE,
    &delete_original,
    N_("Delete the source desktop files, leaving only the target files (effectively \"renames\" the desktop files)"),
    NULL
  },
  {
#define OPTION_DIR "dir"
    OPTION_DIR,
    '\0',
    '\0',
    G_OPTION_ARG_CALLBACK,
    parse_install_options_callback,
    N_("Install desktop files to the DIR directory"),
    N_("DIR")
  },
  {
#define OPTION_MODE "mode"
    OPTION_MODE,
    'm',
    '\0',
    G_OPTION_ARG_CALLBACK,
    parse_install_options_callback,
    N_("Set the permissions of the destination files to MODE"),
    N_("MODE")
  },
  {
#define OPTION_VENDOR "vendor"
    OPTION_VENDOR,
    '\0',
    '\0',
    G_OPTION_ARG_CALLBACK,
    parse_install_options_callback,
    N_("Add a vendor prefix to the desktop files, if not already present"),
    N_("VENDOR")
  },
  {
    "rebuild-mime-info-cache",
    '\0',
    '\0',
    G_OPTION_ARG_NONE,
    &rebuild_mime_info_cache,
    N_("Rebuild the MIME types application database after installing desktop files"),
    NULL
  },
  { G_OPTION_REMAINING,
    0,
    0,
    G_OPTION_ARG_FILENAME_ARRAY,
    &args,
    NULL,
    N_("[FILE...]") },
  {
    NULL
  }
};

static const GOptionEntry edit_options[] = {
  {
#define OPTION_COPY_NAME "copy-name-to-generic-name"
    OPTION_COPY_NAME,
    '\0',
    G_OPTION_FLAG_NO_ARG,
    G_OPTION_ARG_CALLBACK,
    parse_edit_options_callback,
    N_("Copy the value of the \"Name\" key to the \"GenericName\" key"),
    NULL
  },
  {
#define OPTION_COPY_GENERIC_NAME "copy-generic-name-to-name"
    OPTION_COPY_GENERIC_NAME,
    '\0',
    G_OPTION_FLAG_NO_ARG,
    G_OPTION_ARG_CALLBACK,
    parse_edit_options_callback,
    N_("Copy the value of the \"GenericName\" key to the \"Name\" key"),
    NULL
  },
  {
#define OPTION_REMOVE_KEY "remove-key"
    OPTION_REMOVE_KEY,
    '\0',
    '\0',
    G_OPTION_ARG_CALLBACK,
    parse_edit_options_callback,
    N_("Remove the KEY key from the desktop files, if present"),
    N_("KEY")
  },
  {
#define OPTION_ADD_CATEGORY "add-category"
    OPTION_ADD_CATEGORY,
    '\0',
    '\0',
    G_OPTION_ARG_CALLBACK,
    parse_edit_options_callback,
    N_("Add CATEGORY to the list of categories"),
    N_("CATEGORY")
  },
  {
#define OPTION_REMOVE_CATEGORY "remove-category"
    OPTION_REMOVE_CATEGORY,
    '\0',
    '\0',
    G_OPTION_ARG_CALLBACK,
    parse_edit_options_callback,
    N_("Remove CATEGORY from the list of categories"),
    N_("CATEGORY")
  },
  {
#define OPTION_ADD_MIME_TYPE "add-mime-type"
    OPTION_ADD_MIME_TYPE,
    '\0',
    '\0',
    G_OPTION_ARG_CALLBACK,
    parse_edit_options_callback,
    N_("Add MIME-TYPE to the list of MIME types"),
    N_("MIME-TYPE")
  },
  {
#define OPTION_REMOVE_MIME_TYPE "remove-mime-type"
    OPTION_REMOVE_MIME_TYPE,
    '\0',
    '\0',
    G_OPTION_ARG_CALLBACK,
    parse_edit_options_callback,
    N_("Remove MIME-TYPE from the list of MIME types"),
    N_("MIME-TYPE")
  },
  {
#define OPTION_ADD_ONLY_SHOW_IN "add-only-show-in"
    OPTION_ADD_ONLY_SHOW_IN,
    '\0',
    '\0',
    G_OPTION_ARG_CALLBACK,
    parse_edit_options_callback,
    N_("Add ENVIRONMENT to the list of desktop environment where the desktop files should be displayed"),
    N_("ENVIRONMENT")
  },
  {
#define OPTION_REMOVE_ONLY_SHOW_IN "remove-only-show-in"
    OPTION_REMOVE_ONLY_SHOW_IN,
    '\0',
    '\0',
    G_OPTION_ARG_CALLBACK,
    parse_edit_options_callback,
    N_("Remove ENVIRONMENT from the list of desktop environment where the desktop files should be displayed"),
    N_("ENVIRONMENT")
  },
  {
    NULL
  }
};

static gboolean
parse_install_options_callback (const gchar  *option_name,
                                const gchar  *value,
                                gpointer      data,
                                GError      **error)
{
  /* skip "-" or "--" */
  option_name++;
  if (*option_name == '-')
    option_name++;

  if (strcmp (OPTION_DIR, option_name) == 0)
    {
      if (target_dir)
        {
          g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
                       _("Can only specify --dir once"));
          return FALSE;
        }

      target_dir = g_strdup (value);
    }

  else if (strcmp (OPTION_MODE, option_name) == 0 ||
           strcmp ("m", option_name) == 0)
    {
      unsigned long ul;
      char *end;

      end = NULL;
      ul = strtoul (value, &end, 8);
      if (*value && end && *end == '\0')
        permissions = ul;
      else
        {
          g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
                       _("Could not parse mode string \"%s\""), value);

          return FALSE;
        }
    }

  else if (strcmp (OPTION_VENDOR, option_name) == 0)
    {
      if (vendor_name)
        {
          g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
              _("Can only specify --vendor once"));
          return FALSE;
        }

      vendor_name = g_strdup (value);
    }

  else
    {
      g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
                   _("Unknown option \"%s\""), option_name);

      return FALSE;
    }

  return TRUE;
}

static gboolean
parse_edit_options_callback (const gchar  *option_name,
                             const gchar  *value,
                             gpointer      data,
                             GError      **error)
{
  /* Note: we prepend actions to the list, so we'll need to reverse it later */

  DfuEditAction  *action;
  char          **list;
  int             i;

  /* skip "-" or "--" */
  option_name++;
  if (*option_name == '-')
    option_name++;

#define PARSE_OPTION_LIST(type, key)                                    \
  do {                                                                  \
    list = g_strsplit (value, ";", 0);                                  \
    for (i = 0; list[i]; i++)                                           \
      {                                                                 \
        if (*list[i] == '\0')                                           \
          continue;                                                     \
                                                                        \
        action = dfu_edit_action_new (type, key, list[i]);              \
        edit_actions = g_slist_prepend (edit_actions, action);          \
      }                                                                 \
  } while (0)

  if (strcmp (OPTION_COPY_NAME, option_name) == 0)
    {
      action = dfu_edit_action_new (DFU_COPY_KEY, "Name", "GenericName");
      edit_actions = g_slist_prepend (edit_actions, action);
    }

  else if (strcmp (OPTION_COPY_GENERIC_NAME, option_name) == 0)
    {
      action = dfu_edit_action_new (DFU_COPY_KEY, "GenericName", "Name");
      edit_actions = g_slist_prepend (edit_actions, action);
    }

  else if (strcmp (OPTION_REMOVE_KEY, option_name) == 0)
    {
      action = dfu_edit_action_new (DFU_REMOVE_KEY, value, NULL);
      edit_actions = g_slist_prepend (edit_actions, action);
    }

  else if (strcmp (OPTION_ADD_CATEGORY, option_name) == 0)
    {
      PARSE_OPTION_LIST (DFU_ADD_TO_LIST, "Categories");
    }

  else if (strcmp (OPTION_REMOVE_CATEGORY, option_name) == 0)
    {
      PARSE_OPTION_LIST (DFU_REMOVE_FROM_LIST, "Categories");
    }

  else if (strcmp (OPTION_ADD_MIME_TYPE, option_name) == 0)
    {
      PARSE_OPTION_LIST (DFU_ADD_TO_LIST, "MimeType");
    }

  else if (strcmp (OPTION_REMOVE_MIME_TYPE, option_name) == 0)
    {
      PARSE_OPTION_LIST (DFU_REMOVE_FROM_LIST, "MimeType");
    }

  else if (strcmp (OPTION_ADD_ONLY_SHOW_IN, option_name) == 0)
    {
      PARSE_OPTION_LIST (DFU_ADD_TO_LIST, "OnlyShowIn");
    }

  else if (strcmp (OPTION_REMOVE_ONLY_SHOW_IN, option_name) == 0)
    {
      PARSE_OPTION_LIST (DFU_REMOVE_FROM_LIST, "OnlyShowIn");
    }

  else
    {
      g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
                   _("Unknown option \"%s\""), option_name);

      return FALSE;
    }

  return TRUE;
}

int
main (int argc, char **argv)
{
  GOptionContext *context;
  GOptionGroup *group;
  GError* err = NULL;
  int i;
  mode_t dir_permissions;

  setlocale (LC_ALL, "");

  context = g_option_context_new ("");
  g_option_context_set_summary (context, _("Install desktop files."));
  g_option_context_add_main_entries (context, options, NULL);

  group = g_option_group_new ("edit", _("Edition options for desktop file"), _("Show desktop file edition options"), NULL, NULL);
  g_option_group_add_entries (group, edit_options);
  g_option_context_add_group (context, group);

  err = NULL;
  g_option_context_parse (context, &argc, &argv, &err);

  if (err != NULL) {
    g_printerr ("%s\n", err->message);
    g_printerr (_("Run '%s --help' to see a full list of available command line options.\n"), argv[0]);
    g_error_free (err);
    return 1;
  }

  if (vendor_name == NULL && g_getenv ("DESKTOP_FILE_VENDOR"))
    vendor_name = g_strdup (g_getenv ("DESKTOP_FILE_VENDOR"));

  if (target_dir == NULL && g_getenv ("DESKTOP_FILE_INSTALL_DIR"))
    target_dir = g_strdup (g_getenv ("DESKTOP_FILE_INSTALL_DIR"));

  if (target_dir == NULL)
    target_dir = g_build_filename (DATADIR, "applications", NULL);

  /* Create the target directory */
  dir_permissions = permissions;

  /* Add search bit when the target file is readable */
  if (permissions & 0400)
    dir_permissions |= 0100;
  if (permissions & 0040)
    dir_permissions |= 0010;
  if (permissions & 0004)
    dir_permissions |= 0001;

  g_mkdir_with_parents (target_dir, dir_permissions);

  edit_actions = g_slist_reverse (edit_actions);

  i = 0;
  while (args && args[i])
    {
      err = NULL;
      process_one_file (args[i], &err);
      if (err != NULL)
        {
          g_printerr (_("Error on file \"%s\": %s\n"),
                      args[i], err->message);

          g_error_free (err);

          return 1;
        }

      ++i;
    }

  g_slist_free_full (edit_actions, (GDestroyNotify) dfu_edit_action_free);

  if (i == 0)
    {
      g_printerr (_("Must specify one or more desktop files to install\n"));

      return 1;
    }

  g_option_context_free (context);

  return 0;
}