-
Notifications
You must be signed in to change notification settings - Fork 38
/
files.c
740 lines (601 loc) · 15.9 KB
/
files.c
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
/*
* MOC - music on console
* Copyright (C) 2004 Damian Pietras <daper@daper.net>
*
* This program 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.
*
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdio.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <stdlib.h>
#include <dirent.h>
#ifdef HAVE_LIBMAGIC
#include <magic.h>
#include <pthread.h>
#endif
#define DEBUG
#include "common.h"
#include "playlist.h"
#include "lists.h"
#include "interface.h"
#include "decoder.h"
#include "options.h"
#include "files.h"
#include "playlist_file.h"
#include "log.h"
#include "utf8.h"
#define READ_LINE_INIT_SIZE 256
#ifdef HAVE_LIBMAGIC
static magic_t cookie = NULL;
static char *cached_file = NULL;
static char *cached_result = NULL;
#endif
void files_init ()
{
#ifdef HAVE_LIBMAGIC
assert (cookie == NULL);
cookie = magic_open (MAGIC_SYMLINK | MAGIC_MIME | MAGIC_ERROR |
MAGIC_NO_CHECK_COMPRESS | MAGIC_NO_CHECK_ELF |
MAGIC_NO_CHECK_TAR | MAGIC_NO_CHECK_TOKENS |
MAGIC_NO_CHECK_FORTRAN | MAGIC_NO_CHECK_TROFF);
if (cookie == NULL)
log_errno ("Error allocating magic cookie", errno);
else if (magic_load (cookie, NULL) != 0) {
logit ("Error loading magic database: %s", magic_error (cookie));
magic_close (cookie);
cookie = NULL;
}
#endif
}
void files_cleanup ()
{
#ifdef HAVE_LIBMAGIC
free (cached_file);
cached_file = NULL;
free (cached_result);
cached_result = NULL;
magic_close (cookie);
cookie = NULL;
#endif
}
/* Is the string a URL? */
inline int is_url (const char *str)
{
return !strncasecmp (str, "http://", sizeof ("http://") - 1)
|| !strncasecmp (str, "ftp://", sizeof ("ftp://") - 1);
}
/* Return 1 if the file is a directory, 0 if not, -1 on error. */
int is_dir (const char *file)
{
struct stat file_stat;
if (is_url (file))
return 0;
if (stat (file, &file_stat) == -1) {
char *err = xstrerror (errno);
error ("Can't stat %s: %s", file, err);
free (err);
return -1;
}
return S_ISDIR(file_stat.st_mode) ? 1 : 0;
}
/* Return 1 if the file can be read by this user, 0 if not */
int can_read_file (const char *file)
{
return access(file, R_OK) == 0;
}
enum file_type file_type (const char *file)
{
struct stat file_stat;
assert (file != NULL);
if (is_url(file))
return F_URL;
if (stat(file, &file_stat) == -1)
return F_OTHER; /* Ignore the file if stat() failed */
if (S_ISDIR(file_stat.st_mode))
return F_DIR;
if (is_sound_file(file))
return F_SOUND;
if (is_plist_file(file))
return F_PLAYLIST;
return F_OTHER;
}
/* Given a file name, return the mime type or NULL. */
char *file_mime_type (const char *file ASSERT_ONLY)
{
char *result = NULL;
assert (file != NULL);
#ifdef HAVE_LIBMAGIC
static pthread_mutex_t magic_mtx = PTHREAD_MUTEX_INITIALIZER;
if (cookie != NULL) {
LOCK(magic_mtx);
if (cached_file && !strcmp (cached_file, file))
result = xstrdup (cached_result);
else {
free (cached_file);
free (cached_result);
cached_file = cached_result = NULL;
result = xstrdup (magic_file (cookie, file));
if (result == NULL)
logit ("Error interrogating file: %s", magic_error (cookie));
else {
cached_file = xstrdup (file);
cached_result = xstrdup (result);
}
}
UNLOCK(magic_mtx);
}
#endif
return result;
}
/* Make a title from the file name for the item. If hide_extn != 0,
* strip the file name from extension. */
void make_file_title (struct plist *plist, const int num,
const bool hide_extension)
{
assert (plist != NULL);
assert (LIMIT(num, plist->num));
assert (!plist_deleted (plist, num));
if (file_type (plist->items[num].file) != F_URL) {
char *file = xstrdup (plist->items[num].file);
if (hide_extension) {
char *extn;
extn = ext_pos (file);
if (extn)
*(extn - 1) = 0;
}
if (options_get_bool ("FileNamesIconv"))
{
char *old_title = file;
file = files_iconv_str (file);
free (old_title);
}
plist_set_title_file (plist, num, file);
free (file);
}
else
plist_set_title_file (plist, num, plist->items[num].file);
}
/* Make a title from the tags for the item. */
void make_tags_title (struct plist *plist, const int num)
{
bool hide_extn;
char *title;
assert (plist != NULL);
assert (LIMIT(num, plist->num));
assert (!plist_deleted (plist, num));
if (file_type (plist->items[num].file) == F_URL) {
make_file_title (plist, num, false);
return;
}
if (plist->items[num].title_tags)
return;
assert (plist->items[num].file != NULL);
if (plist->items[num].tags->title) {
title = build_title (plist->items[num].tags);
plist_set_title_tags (plist, num, title);
free (title);
return;
}
hide_extn = options_get_bool ("HideFileExtension");
make_file_title (plist, num, hide_extn);
}
/* Switch playlist titles to title_file */
void switch_titles_file (struct plist *plist)
{
int i;
bool hide_extn;
hide_extn = options_get_bool ("HideFileExtension");
for (i = 0; i < plist->num; i++) {
if (plist_deleted (plist, i))
continue;
if (!plist->items[i].title_file)
make_file_title (plist, i, hide_extn);
assert (plist->items[i].title_file != NULL);
}
}
/* Switch playlist titles to title_tags */
void switch_titles_tags (struct plist *plist)
{
int i;
bool hide_extn;
hide_extn = options_get_bool ("HideFileExtension");
for (i = 0; i < plist->num; i++) {
if (plist_deleted (plist, i))
continue;
if (!plist->items[i].title_tags && !plist->items[i].title_file)
make_file_title (plist, i, hide_extn);
}
}
/* Add file to the directory path in buf resolving '../' and removing './'. */
/* buf must be absolute path. */
void resolve_path (char *buf, size_t size, const char *file)
{
int rc;
char *f; /* points to the char in *file we process */
char path[2*PATH_MAX]; /* temporary path */
size_t len = 0; /* number of characters in the buffer */
assert (buf[0] == '/');
rc = snprintf(path, sizeof(path), "%s/%s/", buf, file);
if (rc >= ssizeof(path))
fatal ("Path too long!");
f = path;
while (*f) {
if (!strncmp(f, "/../", 4)) {
char *slash = strrchr (buf, '/');
assert (slash != NULL);
if (slash == buf) {
/* make '/' from '/directory' */
buf[1] = 0;
len = 1;
}
else {
/* strip one element */
*(slash) = 0;
len -= len - (slash - buf);
buf[len] = 0;
}
f+= 3;
}
else if (!strncmp(f, "/./", 3))
/* skip '/.' */
f += 2;
else if (!strncmp(f, "//", 2))
/* remove double slash */
f++;
else if (len == size - 1)
fatal ("Path too long!");
else {
buf[len++] = *(f++);
buf[len] = 0;
}
}
/* remove dot from '/dir/.' */
if (len >= 2 && buf[len-1] == '.' && buf[len-2] == '/')
buf[--len] = 0;
/* strip trailing slash */
if (len > 1 && buf[len-1] == '/')
buf[--len] = 0;
}
/* Read selected tags for a file into tags structure (or create it if NULL).
* If some tags are already present, don't read them.
* If present_tags is NULL, allocate new tags. */
struct file_tags *read_file_tags (const char *file,
struct file_tags *tags, const int tags_sel)
{
struct decoder *df;
int needed_tags;
assert (file != NULL);
if (tags == NULL)
tags = tags_new ();
if (file_type (file) == F_URL)
return tags;
needed_tags = ~tags->filled & tags_sel;
if (!needed_tags) {
debug ("No need to read any tags");
return tags;
}
df = get_decoder (file);
if (!df) {
logit ("Can't find decoder functions for %s", file);
return tags;
}
/* This makes sure that we don't cause a memory leak */
assert (!((needed_tags & TAGS_COMMENTS) &&
(tags->title || tags->artist || tags->album)));
df->info (file, tags, needed_tags);
tags->filled |= tags_sel;
return tags;
}
/* Read the content of the directory, make an array of absolute paths for
* all recognized files. Put directories, playlists and sound files
* in proper structures. Return 0 on error.*/
int read_directory (const char *directory, lists_t_strs *dirs,
lists_t_strs *playlists, struct plist *plist)
{
DIR *dir;
struct dirent *entry;
bool show_hidden = options_get_bool ("ShowHiddenFiles");
int dir_is_root;
assert (directory != NULL);
assert (*directory == '/');
assert (dirs != NULL);
assert (playlists != NULL);
assert (plist != NULL);
if (!(dir = opendir(directory))) {
error_errno ("Can't read directory", errno);
return 0;
}
if (!strcmp(directory, "/"))
dir_is_root = 1;
else
dir_is_root = 0;
while ((entry = readdir(dir))) {
int rc;
char file[PATH_MAX];
enum file_type type;
if (user_wants_interrupt()) {
error ("Interrupted! Not all files read!");
break;
}
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
continue;
if (!show_hidden && entry->d_name[0] == '.')
continue;
rc = snprintf(file, sizeof(file), "%s/%s",
dir_is_root ? "" : directory, entry->d_name);
if (rc >= ssizeof(file)) {
error ("Path too long!");
closedir (dir);
return 0;
}
type = file_type (file);
if (type == F_SOUND)
plist_add (plist, file);
else if (type == F_DIR)
lists_strs_append (dirs, file);
else if (type == F_PLAYLIST)
lists_strs_append (playlists, file);
}
closedir (dir);
return 1;
}
static int dir_symlink_loop (const ino_t inode_no, const ino_t *dir_stack,
const int depth)
{
int i;
for (i = 0; i < depth; i++)
if (dir_stack[i] == inode_no)
return 1;
return 0;
}
/* Recursively add files from the directory to the playlist.
* Return 1 if OK (and even some errors), 0 if the user interrupted. */
static int read_directory_recurr_internal (const char *directory, struct plist *plist,
ino_t **dir_stack, int *depth)
{
DIR *dir;
struct dirent *entry;
struct stat st;
if (stat (directory, &st)) {
char *err = xstrerror (errno);
error ("Can't stat %s: %s", directory, err);
free (err);
return 0;
}
assert (plist != NULL);
assert (directory != NULL);
if (*dir_stack && dir_symlink_loop(st.st_ino, *dir_stack, *depth)) {
logit ("Detected symlink loop on %s", directory);
return 1;
}
if (!(dir = opendir(directory))) {
error_errno ("Can't read directory", errno);
return 1;
}
(*depth)++;
*dir_stack = (ino_t *)xrealloc (*dir_stack, sizeof(ino_t) * (*depth));
(*dir_stack)[*depth - 1] = st.st_ino;
while ((entry = readdir(dir))) {
int rc;
char file[PATH_MAX];
enum file_type type;
if (user_wants_interrupt()) {
error ("Interrupted! Not all files read!");
break;
}
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
continue;
rc = snprintf(file, sizeof(file), "%s/%s", directory, entry->d_name);
if (rc >= ssizeof(file)) {
error ("Path too long!");
continue;
}
type = file_type (file);
if (type == F_DIR)
read_directory_recurr_internal(file, plist, dir_stack, depth);
else if (type == F_SOUND && plist_find_fname(plist, file) == -1)
plist_add (plist, file);
}
(*depth)--;
*dir_stack = (ino_t *)xrealloc (*dir_stack, sizeof(ino_t) * (*depth));
closedir (dir);
return 1;
}
int read_directory_recurr (const char *directory, struct plist *plist)
{
int ret;
int depth = 0;
ino_t *dir_stack = NULL;
ret = read_directory_recurr_internal (directory, plist, &dir_stack,
&depth);
if (dir_stack)
free (dir_stack);
return ret;
}
/* Return the file extension position or NULL if the file has no extension. */
char *ext_pos (const char *file)
{
char *ext = strrchr (file, '.');
char *slash = strrchr (file, '/');
/* don't treat dot in ./file or /.file as a dot before extension */
if (ext && (!slash || slash < ext) && ext != file && *(ext-1) != '/')
ext++;
else
ext = NULL;
return ext;
}
/* Read one line from a file, strip trailing end of line chars.
* Returned memory is malloc()ed. Return NULL on error or EOF. */
char *read_line (FILE *file)
{
int line_alloc = READ_LINE_INIT_SIZE;
int len = 0;
char *line = (char *)xmalloc (sizeof(char) * line_alloc);
while (1) {
if (!fgets(line + len, line_alloc - len, file))
break;
len = strlen(line);
if (line[len-1] == '\n')
break;
/* If we are here, it means that line is longer than the buffer. */
line_alloc *= 2;
line = (char *)xrealloc (line, sizeof(char) * line_alloc);
}
if (len == 0) {
free (line);
return NULL;
}
if (line[len-1] == '\n')
line[--len] = 0;
if (len > 0 && line[len-1] == '\r')
line[--len] = 0;
return line;
}
/* Return malloc()ed string in form "base/name". */
static char *add_dir_file (const char *base, const char *name)
{
char *path;
int base_is_root;
base_is_root = !strcmp (base, "/") ? 1 : 0;
path = (char *)xmalloc (sizeof(char) *
(strlen(base) + strlen(name) + 2));
sprintf (path, "%s/%s", base_is_root ? "" : base, name);
return path;
}
/* Find directories having a prefix of 'pattern'.
* - If there are no matches, NULL is returned.
* - If there is one such directory, it is returned with a trailing '/'.
* - Otherwise the longest common prefix is returned (with no trailing '/').
* (This is used for directory auto-completion.)
* Returned memory is malloc()ed.
* 'pattern' is temporarily modified! */
char *find_match_dir (char *pattern)
{
char *slash;
DIR *dir;
struct dirent *entry;
int name_len;
char *name;
char *matching_dir = NULL;
char *search_dir;
int unambiguous = 1;
if (!pattern[0])
return NULL;
/* strip the last directory */
slash = strrchr (pattern, '/');
if (!slash)
return NULL;
if (slash == pattern) {
/* only '/dir' */
search_dir = xstrdup ("/");
}
else {
*slash = 0;
search_dir = xstrdup (pattern);
*slash = '/';
}
name = slash + 1;
name_len = strlen (name);
if (!(dir = opendir(search_dir)))
return NULL;
while ((entry = readdir(dir))) {
if (strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")
&& !strncmp(entry->d_name, name, name_len)) {
char *path = add_dir_file (search_dir, entry->d_name);
if (is_dir(path) == 1) {
if (matching_dir) {
/* More matching directories - strip
* matching_dir to the part that is
* common to both paths */
int i = 0;
while (matching_dir[i] == path[i]
&& path[i])
i++;
matching_dir[i] = 0;
free (path);
unambiguous = 0;
}
else
matching_dir = path;
}
else
free (path);
}
}
closedir (dir);
free (search_dir);
if (matching_dir && unambiguous) {
matching_dir = (char *)xrealloc (matching_dir,
sizeof(char) * (strlen(matching_dir) + 2));
strcat (matching_dir, "/");
}
return matching_dir;
}
/* Return != 0 if the file exists. */
int file_exists (const char *file)
{
struct stat file_stat;
if (!stat(file, &file_stat))
return 1;
/* Log any error other than non-existence. */
if (errno != ENOENT)
log_errno ("Error", errno);
return 0;
}
/* Get the modification time of a file. Return (time_t)-1 on error */
time_t get_mtime (const char *file)
{
struct stat stat_buf;
if (stat(file, &stat_buf) != -1)
return stat_buf.st_mtime;
return (time_t)-1;
}
/* Convert file path to absolute path;
* resulting string is allocated and must be freed afterwards. */
char *absolute_path (const char *path, const char *cwd)
{
char tmp[2*PATH_MAX];
char *result;
assert (path);
assert (cwd);
if(path[0] != '/' && !is_url(path)) {
strncpy (tmp, cwd, sizeof(tmp));
tmp[sizeof(tmp)-1] = 0;
resolve_path (tmp, sizeof(tmp), path);
result = (char *)xmalloc (sizeof(char) * (strlen(tmp)+1));
strcpy (result, tmp);
}
else {
result = (char *)xmalloc (sizeof(char) * (strlen(path)+1));
strcpy (result, path);
}
return result;
}
/* Check that a file which may cause other applications to be invoked
* is secure against tampering. */
bool is_secure (const char *file)
{
struct stat sb;
assert (file && file[0]);
if (stat (file, &sb) == -1)
return true;
if (!S_ISREG(sb.st_mode))
return false;
if (sb.st_mode & (S_IWGRP|S_IWOTH))
return false;
if (sb.st_uid != 0 && sb.st_uid != geteuid ())
return false;
return true;
}