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