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