2 * This file is part of DisOrder.
3 * Copyright (C) 2006, 2007, 2008 Richard Kettlewell
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.
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.
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/>.
18 /** @file clients/disorderfm.c
19 * @brief DisOrder file manager
21 * Intended to support encoding conversion, tag extraction, etc. Not yet
22 * complete (and hasn't been worked on for ages).
44 /* Arguments etc ----------------------------------------------------------- */
46 typedef int copyfn(const char *from, const char *to);
47 typedef int mkdirfn(const char *dir, mode_t mode);
49 /* Input and output directories */
50 static const char *source, *destination;
52 /* Function used to copy or link a file */
53 static copyfn *copier = link;
55 /* Function used to make a directory */
56 static mkdirfn *dirmaker = mkdir;
58 /* Various encodings */
59 static const char *fromencoding, *toencoding, *tagencoding;
61 /* Directory for untagged files */
62 static const char *untagged;
64 /* Extract tag information? */
65 static int extracttags;
67 /* Windows-friendly filenames? */
68 static int windowsfriendly;
70 /* Native character encoding (i.e. from LC_CTYPE) */
71 static const char *nativeencoding;
76 /* Included/excluded filename patterns */
77 static struct pattern {
81 } *patterns, **patterns_end = &patterns;
83 static int default_inclusion = 1;
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' },
104 /* display usage message and terminate */
105 static void help(void) {
107 " disorderfm [OPTIONS] SOURCE DESTINATION\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 */
132 /* Utilities --------------------------------------------------------------- */
134 /* Copy FROM to TO. Has the same signature as link/symlink. */
135 static int copy(const char *from, const char *to) {
140 if((fdin = open(from, O_RDONLY)) < 0)
141 fatal(errno, "error opening %s", from);
142 if((fdout = open(to, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
143 fatal(errno, "error opening %s", to);
144 while((n = read(fdin, buffer, sizeof buffer)) > 0) {
145 if(write(fdout, buffer, n) < 0)
146 fatal(errno, "error writing to %s", to);
148 if(n < 0) fatal(errno, "error reading %s", from);
149 if(close(fdout) < 0) fatal(errno, "error closing %s", to);
154 static int nocopy(const char *from, const char *to) {
155 xprintf("%s -> %s\n",
156 any2mb(fromencoding, from),
157 any2mb(toencoding, to));
161 static int nomkdir(const char *dir, mode_t attribute((unused)) mode) {
162 xprintf("mkdir %s\n", any2mb(toencoding, dir));
166 /* Name translation -------------------------------------------------------- */
168 static int bad_windows_char(int c) {
172 /* Documented as bad by MS */
179 /* Not documented as bad by MS but Samba mangles anyway? */
185 /* Return the translated form of PATH */
186 static char *nametrans(const char *path) {
187 char *t = any2any(fromencoding, toencoding, path);
189 if(windowsfriendly) {
191 * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/naming_a_file.asp?frame=true&hidetoc=true */
192 /* List of forbidden names */
193 static const char *const devicenames[] = {
194 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5",
195 "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5",
196 "LPT6", "LPT7", "LPT8", "LPT9", "CLOCK$"
198 #define NDEVICENAMES (sizeof devicenames / sizeof *devicenames)
202 /* Certain characters are just not allowed. We replace them with
205 if(bad_windows_char((unsigned char)*s))
207 /* Trailing spaces and dots are not allowed. We just strip them. */
208 while(s > t && (s[-1] == ' ' || s[-1] == '.'))
211 /* Reject device names */
212 if((s = strchr(t, '.'))) l = s - t;
214 for(n = 0; n < NDEVICENAMES; ++n)
215 if(l == strlen(devicenames[n]) && !strncasecmp(devicenames[n], t, l))
218 byte_xasprintf(&t, "_%s", t);
223 /* The file walker --------------------------------------------------------- */
225 /* Visit file or directory PATH relative to SOURCE. SOURCE is a null pointer
228 * PATH is something we extracted from the filesystem so by assumption is in
229 * the FROM encoding, which might _not_ be the same as the current locale's
232 * For most errors we carry on as best we can.
234 static void visit(const char *path, const char *destpath) {
235 const struct pattern *p;
237 /* fullsourcepath is the full source pathname for PATH */
238 char *fullsourcepath;
239 /* fulldestpath will be the full destination pathname */
241 /* String to use in error messags. We convert to the current locale; this
242 * may be somewhat misleading but is necessary to avoid getting EILSEQ in
244 char *errsourcepath, *errdestpath;
246 D(("visit %s", path ? path : "NULL"));
248 /* Set up all the various path names */
250 byte_xasprintf(&fullsourcepath, "%s/%s",
252 byte_xasprintf(&fulldestpath, "%s/%s",
253 destination, destpath);
254 byte_xasprintf(&errsourcepath, "%s/%s",
255 source, any2mb(fromencoding, path));
256 byte_xasprintf(&errdestpath, "%s/%s",
257 destination, any2mb(toencoding, destpath));
258 for(p = patterns; p; p = p->next)
259 if(fnmatch(p->pattern, path, FNM_PATHNAME) == 0)
262 /* We found a matching pattern */
264 D(("%s matches %s therefore excluding",
269 /* We did not find a matching pattern */
270 if(!default_inclusion) {
271 D(("%s matches nothing and not including by default", path));
276 fullsourcepath = errsourcepath = (char *)source;
277 fulldestpath = errdestpath = (char *)destination;
280 /* The destination directory might be a subdirectory of the source
281 * directory. In that case we'd better not descend into it when we encounter
282 * it in the source. */
283 if(!strcmp(fullsourcepath, destination)) {
284 info("%s matches destination directory, not recursing", errsourcepath);
288 /* Find out what kind of file we're dealing with */
289 if(stat(fullsourcepath, &sb) < 0) {
290 error(errno, "cannot stat %s", errsourcepath );
294 if(S_ISREG(sb.st_mode)) {
296 if(unlink(fulldestpath) < 0 && errno != ENOENT) {
297 error(errno, "cannot remove %s", errdestpath);
301 if(copier(fullsourcepath, fulldestpath) < 0) {
302 error(errno, "cannot link %s to %s", errsourcepath, errdestpath);
306 } else if(S_ISDIR(sb.st_mode)) {
309 char *childpath, *childdestpath;
311 /* We create the directory on the destination side. If it already exists,
313 if(dirmaker(fulldestpath, 0777) < 0 && errno != EEXIST) {
314 error(errno, "cannot mkdir %s", errdestpath);
318 /* We read the directory and visit all the files in it in any old order. */
319 if(!(dp = opendir(fullsourcepath))) {
320 error(errno, "cannot open directory %s", errsourcepath);
324 while(((errno = 0), (de = readdir(dp)))) {
325 if(!strcmp(de->d_name, ".")
326 || !strcmp(de->d_name, "..")) continue;
328 byte_xasprintf(&childpath, "%s/%s", path, de->d_name);
329 byte_xasprintf(&childdestpath, "%s/%s",
330 destpath, nametrans(de->d_name));
332 childpath = de->d_name;
333 childdestpath = nametrans(de->d_name);
335 visit(childpath, childdestpath);
337 if(errno) fatal(errno, "error reading directory %s", errsourcepath);
340 /* We don't handle special files, but we'd better warn the user. */
341 info("ignoring %s", errsourcepath);
345 int main(int argc, char **argv) {
350 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
351 while((n = getopt_long(argc, argv, "hVdf:t:i:e:ET:u:wlscn", options, 0)) >= 0) {
354 case 'V': version("disorderfm");
355 case 'd': debugging = 1; break;
356 case 'f': fromencoding = optarg; break;
357 case 't': toencoding = optarg; break;
360 p = xmalloc(sizeof *p);
365 patterns_end = &p->next;
366 if(n == 'i') default_inclusion = 0;
368 case 'E': extracttags = 1; break;
369 case 'T': tagencoding = optarg; break;
370 case 'u': untagged = optarg; break;
371 case 'w': windowsfriendly = 1; break;
372 case 'l': copier = link; break;
373 case 's': copier = symlink; break;
374 case 'c': copier = copy; break;
375 case 'n': copier = nocopy; dirmaker = nomkdir; break;
376 default: fatal(0, "invalid option");
379 if(optind == argc) fatal(0, "missing SOURCE and DESTINATION arguments");
380 else if(optind + 1 == argc) fatal(0, "missing DESTINATION argument");
381 else if(optind + 2 != argc) fatal(0, "redundant extra arguments");
382 if(extracttags) fatal(0, "--extract-tags is not implemented yet"); /* TODO */
383 if(tagencoding && !extracttags)
384 fatal(0, "--tag-encoding without --extra-tags does not make sense");
385 if(untagged && !extracttags)
386 fatal(0, "--untagged without --extra-tags does not make sense");
387 source = argv[optind];
388 destination = argv[optind + 1];
389 nativeencoding = nl_langinfo(CODESET);
390 if(fromencoding || toencoding) {
391 if(!fromencoding) fromencoding = nativeencoding;
392 if(!toencoding) toencoding = nativeencoding;
394 if(!tagencoding) tagencoding = nativeencoding;
397 if(errors) fprintf(stderr, "%ld errors\n", errors);