chiark / gitweb /
Fix format string pedantry to build on 64-bit Linux
[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;
139
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);
147 }
148 if(n < 0) fatal(errno, "error reading %s", from);
149 if(close(fdout) < 0) fatal(errno, "error closing %s", to);
150 xclose(fdin);
151 return 0;
152}
153
154static int nocopy(const char *from, const char *to) {
155 xprintf("%s -> %s\n",
156 any2mb(fromencoding, from),
157 any2mb(toencoding, to));
158 return 0;
159}
160
161static int nomkdir(const char *dir, mode_t attribute((unused)) mode) {
162 xprintf("mkdir %s\n", any2mb(toencoding, dir));
163 return 0;
164}
165
166/* Name translation -------------------------------------------------------- */
167
168static int bad_windows_char(int c) {
169 switch(c) {
170 default:
171 return 0;
172 /* Documented as bad by MS */
173 case '<':
174 case '>':
175 case ':':
176 case '"':
177 case '\\':
178 case '|':
179 /* Not documented as bad by MS but Samba mangles anyway? */
180 case '*':
181 return 1;
182 }
183}
184
185/* Return the translated form of PATH */
186static char *nametrans(const char *path) {
187 char *t = any2any(fromencoding, toencoding, path);
188
189 if(windowsfriendly) {
190 /* See:
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$"
197 };
198#define NDEVICENAMES (sizeof devicenames / sizeof *devicenames)
199 char *s;
200 size_t n, l;
201
202 /* Certain characters are just not allowed. We replace them with
203 * underscores. */
204 for(s = t; *s; ++s)
205 if(bad_windows_char((unsigned char)*s))
206 *s = '_';
207 /* Trailing spaces and dots are not allowed. We just strip them. */
208 while(s > t && (s[-1] == ' ' || s[-1] == '.'))
209 --s;
210 *s = 0;
211 /* Reject device names */
212 if((s = strchr(t, '.'))) l = s - t;
213 else l = 0;
214 for(n = 0; n < NDEVICENAMES; ++n)
215 if(l == strlen(devicenames[n]) && !strncasecmp(devicenames[n], t, l))
216 break;
217 if(n < NDEVICENAMES)
218 byte_xasprintf(&t, "_%s", t);
219 }
220 return t;
221}
222
223/* The file walker --------------------------------------------------------- */
224
225/* Visit file or directory PATH relative to SOURCE. SOURCE is a null pointer
226 * at the top level.
227 *
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
230 * encoding.
231 *
232 * For most errors we carry on as best we can.
233 */
234static void visit(const char *path, const char *destpath) {
235 const struct pattern *p;
236 struct stat sb;
237 /* fullsourcepath is the full source pathname for PATH */
238 char *fullsourcepath;
239 /* fulldestpath will be the full destination pathname */
240 char *fulldestpath;
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
243 * error messages. */
244 char *errsourcepath, *errdestpath;
245
246 D(("visit %s", path ? path : "NULL"));
247
248 /* Set up all the various path names */
249 if(path) {
250 byte_xasprintf(&fullsourcepath, "%s/%s",
251 source, path);
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)
260 break;
261 if(p) {
262 /* We found a matching pattern */
263 if(p->type == 'e') {
264 D(("%s matches %s therefore excluding",
265 path, p->pattern));
266 return;
267 }
268 } else {
269 /* We did not find a matching pattern */
270 if(!default_inclusion) {
271 D(("%s matches nothing and not including by default", path));
272 return;
273 }
274 }
275 } else {
276 fullsourcepath = errsourcepath = (char *)source;
277 fulldestpath = errdestpath = (char *)destination;
278 }
279
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);
285 return;
286 }
287
288 /* Find out what kind of file we're dealing with */
289 if(stat(fullsourcepath, &sb) < 0) {
290 error(errno, "cannot stat %s", errsourcepath );
291 ++errors;
292 return;
293 }
294 if(S_ISREG(sb.st_mode)) {
295 if(copier != nocopy)
296 if(unlink(fulldestpath) < 0 && errno != ENOENT) {
297 error(errno, "cannot remove %s", errdestpath);
298 ++errors;
299 return;
300 }
301 if(copier(fullsourcepath, fulldestpath) < 0) {
302 error(errno, "cannot link %s to %s", errsourcepath, errdestpath);
303 ++errors;
304 return;
305 }
306 } else if(S_ISDIR(sb.st_mode)) {
307 DIR *dp;
308 struct dirent *de;
309 char *childpath, *childdestpath;
310
311 /* We create the directory on the destination side. If it already exists,
312 * that's fine. */
313 if(dirmaker(fulldestpath, 0777) < 0 && errno != EEXIST) {
314 error(errno, "cannot mkdir %s", errdestpath);
315 ++errors;
316 return;
317 }
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);
321 ++errors;
322 return;
323 }
324 while(((errno = 0), (de = readdir(dp)))) {
325 if(!strcmp(de->d_name, ".")
326 || !strcmp(de->d_name, "..")) continue;
327 if(path) {
328 byte_xasprintf(&childpath, "%s/%s", path, de->d_name);
329 byte_xasprintf(&childdestpath, "%s/%s",
330 destpath, nametrans(de->d_name));
331 } else {
332 childpath = de->d_name;
333 childdestpath = nametrans(de->d_name);
334 }
335 visit(childpath, childdestpath);
336 }
337 if(errno) fatal(errno, "error reading directory %s", errsourcepath);
338 closedir(dp);
339 } else {
340 /* We don't handle special files, but we'd better warn the user. */
341 info("ignoring %s", errsourcepath);
342 }
343}
344
345int main(int argc, char **argv) {
346 int n;
347 struct pattern *p;
348
320598d4 349 mem_init();
460b9539 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) {
352 switch(n) {
353 case 'h': help();
3fbdc96d 354 case 'V': version("disorderfm");
460b9539 355 case 'd': debugging = 1; break;
356 case 'f': fromencoding = optarg; break;
357 case 't': toencoding = optarg; break;
358 case 'i':
359 case 'e':
360 p = xmalloc(sizeof *p);
361 p->type = n;
362 p->pattern = optarg;
363 p->next = 0;
364 *patterns_end = p;
365 patterns_end = &p->next;
366 if(n == 'i') default_inclusion = 0;
367 break;
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");
377 }
378 }
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;
393 }
394 if(!tagencoding) tagencoding = nativeencoding;
395 visit(0, 0);
396 xfclose(stdout);
397 if(errors) fprintf(stderr, "%ld errors\n", errors);
398 return !!errors;
399}
400
401/*
402Local Variables:
403c-basic-offset:2
404comment-column:40
405fill-column:79
406indent-tabs-mode:nil
407End:
408*/