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) {
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);
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);
161 static int nocopy(const char *from, const char *to) {
162 xprintf("%s -> %s\n",
163 any2mb(fromencoding, from),
164 any2mb(toencoding, to));
168 static int nomkdir(const char *dir, mode_t attribute((unused)) mode) {
169 xprintf("mkdir %s\n", any2mb(toencoding, dir));
173 /* Name translation -------------------------------------------------------- */
175 static int bad_windows_char(int c) {
179 /* Documented as bad by MS */
186 /* Not documented as bad by MS but Samba mangles anyway? */
192 /* Return the translated form of PATH */
193 static char *nametrans(const char *path) {
194 char *t = any2any(fromencoding, toencoding, path);
196 if(windowsfriendly) {
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$"
205 #define NDEVICENAMES (sizeof devicenames / sizeof *devicenames)
209 /* Certain characters are just not allowed. We replace them with
212 if(bad_windows_char((unsigned char)*s))
214 /* Trailing spaces and dots are not allowed. We just strip them. */
215 while(s > t && (s[-1] == ' ' || s[-1] == '.'))
218 /* Reject device names */
219 if((s = strchr(t, '.'))) l = s - t;
221 for(n = 0; n < NDEVICENAMES; ++n)
222 if(l == strlen(devicenames[n]) && !strncasecmp(devicenames[n], t, l))
225 byte_xasprintf(&t, "_%s", t);
230 /* The file walker --------------------------------------------------------- */
232 /* Visit file or directory PATH relative to SOURCE. SOURCE is a null pointer
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
239 * For most errors we carry on as best we can.
241 static void visit(const char *path, const char *destpath) {
242 const struct pattern *p;
244 /* fullsourcepath is the full source pathname for PATH */
245 char *fullsourcepath;
246 /* fulldestpath will be the full destination pathname */
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
251 char *errsourcepath, *errdestpath;
253 D(("visit %s", path ? path : "NULL"));
255 /* Set up all the various path names */
257 byte_xasprintf(&fullsourcepath, "%s/%s",
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)
269 /* We found a matching pattern */
271 D(("%s matches %s therefore excluding",
276 /* We did not find a matching pattern */
277 if(!default_inclusion) {
278 D(("%s matches nothing and not including by default", path));
283 fullsourcepath = errsourcepath = (char *)source;
284 fulldestpath = errdestpath = (char *)destination;
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);
295 /* Find out what kind of file we're dealing with */
296 if(stat(fullsourcepath, &sb) < 0) {
297 error(errno, "cannot stat %s", errsourcepath );
301 if(S_ISREG(sb.st_mode)) {
303 if(unlink(fulldestpath) < 0 && errno != ENOENT) {
304 error(errno, "cannot remove %s", errdestpath);
308 if(copier(fullsourcepath, fulldestpath) < 0) {
309 error(errno, "cannot link %s to %s", errsourcepath, errdestpath);
313 } else if(S_ISDIR(sb.st_mode)) {
316 char *childpath, *childdestpath;
318 /* We create the directory on the destination side. If it already exists,
320 if(dirmaker(fulldestpath, 0700) == 0) {
321 if(dirmaker != nomkdir) {
322 /* Created new directory. Adjust permissions and ownership to match the
324 if(chown(fulldestpath, sb.st_uid, sb.st_gid) < 0) {
325 error(errno, "cannot chown %s", errdestpath);
328 if(chmod(fulldestpath, sb.st_mode & 07777) < 0) {
329 error(errno, "cannot chmod %s", errdestpath);
333 } else if(errno != EEXIST) {
334 error(errno, "cannot mkdir %s", errdestpath);
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);
344 while(((errno = 0), (de = readdir(dp)))) {
345 if(!strcmp(de->d_name, ".")
346 || !strcmp(de->d_name, "..")) continue;
348 byte_xasprintf(&childpath, "%s/%s", path, de->d_name);
349 byte_xasprintf(&childdestpath, "%s/%s",
350 destpath, nametrans(de->d_name));
352 childpath = de->d_name;
353 childdestpath = nametrans(de->d_name);
355 visit(childpath, childdestpath);
357 if(errno) fatal(errno, "error reading directory %s", errsourcepath);
360 /* We don't handle special files, but we'd better warn the user. */
361 info("ignoring %s", errsourcepath);
365 int main(int argc, char **argv) {
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) {
374 case 'V': version("disorderfm");
375 case 'd': debugging = 1; break;
376 case 'f': fromencoding = optarg; break;
377 case 't': toencoding = optarg; break;
380 p = xmalloc(sizeof *p);
385 patterns_end = &p->next;
386 if(n == 'i') default_inclusion = 0;
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");
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;
414 if(!tagencoding) tagencoding = nativeencoding;
417 if(errors) fprintf(stderr, "%ld errors\n", errors);