chiark / gitweb /
Merge from uaudio branch.
[disorder] / clients / disorderfm.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2006, 2007, 2008 Richard Kettlewell
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 /** @file clients/disorderfm.c
19  * @brief DisOrder file manager
20  *
21  * Intended to support encoding conversion, tag extraction, etc.  Not yet
22  * complete (and hasn't been worked on for ages).
23  */
24 #include "common.h"
25
26 #include <getopt.h>
27 #include <unistd.h>
28 #include <locale.h>
29 #include <fcntl.h>
30 #include <errno.h>
31 #include <dirent.h>
32 #include <sys/stat.h>
33 #include <langinfo.h>
34 #include <fnmatch.h>
35
36 #include "syscalls.h"
37 #include "log.h"
38 #include "printf.h"
39 #include "charset.h"
40 #include "defs.h"
41 #include "mem.h"
42 #include "version.h"
43
44 /* Arguments etc ----------------------------------------------------------- */
45
46 typedef int copyfn(const char *from, const char *to);
47 typedef int mkdirfn(const char *dir, mode_t mode);
48
49 /* Input and output directories */
50 static const char *source, *destination;
51
52 /* Function used to copy or link a file */
53 static copyfn *copier = link;
54
55 /* Function used to make a directory */
56 static mkdirfn *dirmaker = mkdir;
57
58 /* Various encodings */
59 static const char *fromencoding, *toencoding, *tagencoding;
60
61 /* Directory for untagged files */
62 static const char *untagged;
63
64 /* Extract tag information? */
65 static int extracttags;
66
67 /* Windows-friendly filenames? */
68 static int windowsfriendly;
69
70 /* Native character encoding (i.e. from LC_CTYPE) */
71 static const char *nativeencoding;
72
73 /* Count of errors */
74 static long errors;
75
76 /* Included/excluded filename patterns */
77 static struct pattern {
78   struct pattern *next;
79   const char *pattern;
80   int type;
81 } *patterns, **patterns_end = &patterns;
82
83 static int default_inclusion = 1;
84
85 static const struct option options[] = {
86   { "help", no_argument, 0, 'h' },
87   { "version", no_argument, 0, 'V' },
88   { "debug", no_argument, 0, 'd' },
89   { "from", required_argument, 0, 'f' },
90   { "to", required_argument, 0, 't' },
91   { "include", required_argument, 0, 'i' },
92   { "exclude", required_argument, 0, 'e' },
93   { "extract-tags", no_argument, 0, 'E' },
94   { "tag-encoding", required_argument, 0, 'T' },
95   { "untagged", required_argument, 0, 'u' },
96   { "windows-friendly", no_argument, 0, 'w' },
97   { "link", no_argument, 0, 'l' },
98   { "symlink", no_argument, 0, 's' },
99   { "copy", no_argument, 0, 'c' },
100   { "no-action", no_argument, 0, 'n' },
101   { 0, 0, 0, 0 }
102 };
103
104 /* display usage message and terminate */
105 static void help(void) {
106   xprintf("Usage:\n"
107 "  disorderfm [OPTIONS] SOURCE DESTINATION\n"
108 "Options:\n"
109 "  --from, -f ENCODING     Source encoding\n"
110 "  --to, -t ENCODING       Destination encoding\n"
111 "If neither --from nor --to are specified then no encoding translation is\n"
112 "performed.  If only one is specified then the other defaults to the current\n"
113 "locale's encoding.\n"
114 "  --windows-friendly, -w  Replace illegal characters with '_'\n"
115 "  --include, -i PATTERN   Include files matching a glob pattern\n"
116 "  --exclude, -e PATTERN   Include files matching a glob pattern\n"
117 "--include and --exclude may be used multiple times.  They are checked in\n"
118 "order and the first match wins.  If --include is ever used then nonmatching\n"
119 "files are excluded, otherwise they are included.\n"
120 "  --link, -l              Link files from source to destination (default)\n"
121 "  --symlink, -s           Symlink files from source to destination\n"
122 "  --copy, -c              Copy files from source to destination\n"
123 "  --no-action, -n         Just report what would be done\n"
124 "  --debug, -d             Debug mode\n"
125 "  --help, -h              Display usage message\n"
126 "  --version, -V           Display version number\n");
127   /* TODO: tag extraction stuff when implemented */
128   xfclose(stdout);
129   exit(0);
130 }
131
132 /* Utilities --------------------------------------------------------------- */
133
134 /* Copy FROM to TO.  Has the same signature as link/symlink. */
135 static int copy(const char *from, const char *to) {
136   int fdin, fdout;
137   char buffer[4096];
138   int n;
139   struct stat sb;
140
141   if((fdin = open(from, O_RDONLY)) < 0)
142     fatal(errno, "error opening %s", from);
143   if((fdout = open(to, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
144     fatal(errno, "error opening %s", to);
145   while((n = read(fdin, buffer, sizeof buffer)) > 0) {
146     if(write(fdout, buffer, n) < 0)
147       fatal(errno, "error writing to %s", to);
148   }
149   if(n < 0) fatal(errno, "error reading %s", from);
150   if(fstat(fdin, &sb) < 0)
151     fatal(errno, "error stating %s", from);
152   if(fchown(fdout, sb.st_uid, sb.st_gid) < 0)
153     fatal(errno, "error chowning %s", from);
154   if(fchmod(fdout, sb.st_mode & 07777) < 0)
155     fatal(errno, "error chmoding %s", from);
156   if(close(fdout) < 0) fatal(errno, "error closing %s", to);
157   xclose(fdin);
158   return 0;
159 }
160
161 static int nocopy(const char *from, const char *to) {
162   xprintf("%s -> %s\n",
163           any2mb(fromencoding, from),
164           any2mb(toencoding, to));
165   return 0;
166 }
167
168 static int nomkdir(const char *dir, mode_t attribute((unused)) mode) {
169   xprintf("mkdir %s\n", any2mb(toencoding, dir));
170   return 0;
171 }
172
173 /* Name translation -------------------------------------------------------- */
174
175 static int bad_windows_char(int c) {
176   switch(c) {
177   default:
178     return 0;
179     /* Documented as bad by MS */
180   case '<':
181   case '>':
182   case ':':
183   case '"':
184   case '\\':
185   case '|':
186     /* Not documented as bad by MS but Samba mangles anyway? */
187   case '*':
188     return 1;
189   }
190 }
191
192 /* Return the translated form of PATH */
193 static char *nametrans(const char *path) {
194   char *t = any2any(fromencoding, toencoding, path);
195
196   if(windowsfriendly) {
197     /* See:
198      * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/naming_a_file.asp?frame=true&hidetoc=true */
199     /* List of forbidden names */
200     static const char *const devicenames[] = {
201       "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5",
202       "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5",
203       "LPT6", "LPT7", "LPT8", "LPT9", "CLOCK$"
204     };
205 #define NDEVICENAMES (sizeof devicenames / sizeof *devicenames)
206     char *s;
207     size_t n, l;
208
209     /* Certain characters are just not allowed.  We replace them with
210      * underscores. */
211     for(s = t; *s; ++s)
212       if(bad_windows_char((unsigned char)*s))
213         *s = '_';
214     /* Trailing spaces and dots are not allowed.  We just strip them. */
215     while(s > t && (s[-1] == ' ' || s[-1] == '.'))
216       --s;
217     *s = 0;
218     /* Reject device names */
219     if((s = strchr(t, '.'))) l = s - t;
220     else l = 0;
221     for(n = 0; n < NDEVICENAMES; ++n)
222       if(l == strlen(devicenames[n]) && !strncasecmp(devicenames[n], t, l))
223         break;
224     if(n < NDEVICENAMES)
225       byte_xasprintf(&t, "_%s", t);
226   }
227   return t;
228 }
229
230 /* The file walker --------------------------------------------------------- */
231
232 /* Visit file or directory PATH relative to SOURCE.  SOURCE is a null pointer
233  * at the top level.
234  *
235  * PATH is something we extracted from the filesystem so by assumption is in
236  * the FROM encoding, which might _not_ be the same as the current locale's
237  * encoding.
238  *
239  * For most errors we carry on as best we can.
240  */
241 static void visit(const char *path, const char *destpath) {
242   const struct pattern *p;
243   struct stat sb;
244   /* fullsourcepath is the full source pathname for PATH */
245   char *fullsourcepath;
246   /* fulldestpath will be the full destination pathname */
247   char *fulldestpath;
248   /* String to use in error messags.  We convert to the current locale; this
249    * may be somewhat misleading but is necessary to avoid getting EILSEQ in
250    * error messages. */
251   char *errsourcepath, *errdestpath;
252
253   D(("visit %s", path ? path : "NULL"));
254   
255   /* Set up all the various path names */
256   if(path) {
257     byte_xasprintf(&fullsourcepath, "%s/%s",
258                    source, path);
259     byte_xasprintf(&fulldestpath, "%s/%s",
260                    destination, destpath);
261     byte_xasprintf(&errsourcepath, "%s/%s",
262                    source, any2mb(fromencoding, path));
263     byte_xasprintf(&errdestpath, "%s/%s",
264                    destination, any2mb(toencoding, destpath));
265     for(p = patterns; p; p = p->next)
266       if(fnmatch(p->pattern, path, FNM_PATHNAME) == 0)
267         break;
268     if(p) {
269       /* We found a matching pattern */
270       if(p->type == 'e') {
271         D(("%s matches %s therefore excluding",
272            path, p->pattern));
273         return;
274       }
275     } else {
276       /* We did not find a matching pattern */
277       if(!default_inclusion) {
278         D(("%s matches nothing and not including by default", path));
279         return;
280       }
281     }
282   } else {
283     fullsourcepath = errsourcepath = (char *)source;
284     fulldestpath = errdestpath = (char *)destination;
285   }
286
287   /* The destination directory might be a subdirectory of the source
288    * directory. In that case we'd better not descend into it when we encounter
289    * it in the source. */
290   if(!strcmp(fullsourcepath, destination)) {
291     info("%s matches destination directory, not recursing", errsourcepath);
292     return;
293   }
294   
295   /* Find out what kind of file we're dealing with */
296   if(stat(fullsourcepath, &sb) < 0) {
297     error(errno, "cannot stat %s", errsourcepath );
298     ++errors;
299     return;
300   }
301   if(S_ISREG(sb.st_mode)) {
302     if(copier != nocopy)
303       if(unlink(fulldestpath) < 0 && errno != ENOENT) {
304         error(errno, "cannot remove %s", errdestpath);
305         ++errors;
306         return;
307       }
308     if(copier(fullsourcepath, fulldestpath) < 0) {
309       error(errno, "cannot link %s to %s", errsourcepath, errdestpath);
310       ++errors;
311       return;
312     }
313   } else if(S_ISDIR(sb.st_mode)) {
314     DIR *dp;
315     struct dirent *de;
316     char *childpath, *childdestpath;
317   
318     /* We create the directory on the destination side.  If it already exists,
319      * that's fine. */
320     if(dirmaker(fulldestpath, 0700) == 0) {
321       if(dirmaker != nomkdir) {
322         /* Created new directory.  Adjust permissions and ownership to match the
323          * old one. */
324         if(chown(fulldestpath, sb.st_uid, sb.st_gid) < 0) {
325           error(errno, "cannot chown %s", errdestpath);
326           ++errors;
327         }
328         if(chmod(fulldestpath, sb.st_mode & 07777) < 0) {
329           error(errno, "cannot chmod %s", errdestpath);
330           ++errors;
331         }
332       }
333     } else if(errno != EEXIST) {
334       error(errno, "cannot mkdir %s", errdestpath);
335       ++errors;
336       return;
337     }
338     /* We read the directory and visit all the files in it in any old order. */
339     if(!(dp = opendir(fullsourcepath))) {
340       error(errno, "cannot open directory %s", errsourcepath);
341       ++errors;
342       return;
343     }
344     while(((errno = 0), (de = readdir(dp)))) {
345       if(!strcmp(de->d_name, ".")
346          || !strcmp(de->d_name, "..")) continue;
347       if(path) {
348         byte_xasprintf(&childpath, "%s/%s", path, de->d_name);
349         byte_xasprintf(&childdestpath, "%s/%s",
350                        destpath, nametrans(de->d_name));
351       } else {
352         childpath = de->d_name;
353         childdestpath = nametrans(de->d_name);
354       }
355       visit(childpath, childdestpath);
356     }
357     if(errno) fatal(errno, "error reading directory %s", errsourcepath);
358     closedir(dp);
359   } else {
360     /* We don't handle special files, but we'd better warn the user. */
361     info("ignoring %s", errsourcepath);
362   }
363 }
364
365 int main(int argc, char **argv) {
366   int n;
367   struct pattern *p;
368
369   mem_init();
370   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
371   while((n = getopt_long(argc, argv, "hVdf:t:i:e:ET:u:wlscn", options, 0)) >= 0) {
372     switch(n) {
373     case 'h': help();
374     case 'V': version("disorderfm");
375     case 'd': debugging = 1; break;
376     case 'f': fromencoding = optarg; break;
377     case 't': toencoding = optarg; break;
378     case 'i': 
379     case 'e':
380       p = xmalloc(sizeof *p);
381       p->type = n;
382       p->pattern = optarg;
383       p->next = 0;
384       *patterns_end = p;
385       patterns_end = &p->next;
386       if(n == 'i') default_inclusion = 0;
387       break;
388     case 'E': extracttags = 1; break;
389     case 'T': tagencoding = optarg; break;
390     case 'u': untagged = optarg; break;
391     case 'w': windowsfriendly = 1; break;
392     case 'l': copier = link; break;
393     case 's': copier = symlink; break;
394     case 'c': copier = copy; break;
395     case 'n': copier = nocopy; dirmaker = nomkdir; break;
396     default: fatal(0, "invalid option");
397     }
398   }
399   if(optind == argc) fatal(0, "missing SOURCE and DESTINATION arguments");
400   else if(optind + 1 == argc) fatal(0, "missing DESTINATION argument");
401   else if(optind + 2 != argc) fatal(0, "redundant extra arguments");
402   if(extracttags) fatal(0, "--extract-tags is not implemented yet"); /* TODO */
403   if(tagencoding && !extracttags)
404     fatal(0, "--tag-encoding without --extra-tags does not make sense");
405   if(untagged && !extracttags)
406     fatal(0, "--untagged without --extra-tags does not make sense");
407   source = argv[optind];
408   destination = argv[optind + 1];
409   nativeencoding = nl_langinfo(CODESET);
410   if(fromencoding || toencoding) {
411     if(!fromencoding) fromencoding = nativeencoding;
412     if(!toencoding) toencoding = nativeencoding;
413   }
414   if(!tagencoding) tagencoding = nativeencoding;
415   visit(0, 0);
416   xfclose(stdout);
417   if(errors) fprintf(stderr, "%ld errors\n", errors);
418   return !!errors;
419 }
420
421 /*
422 Local Variables:
423 c-basic-offset:2
424 comment-column:40
425 fill-column:79
426 indent-tabs-mode:nil
427 End:
428 */