summaryrefslogtreecommitdiff
path: root/src/share/scan.c
blob: 4407510f78dacfbc19994104472a2cf79cfedcc5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/* Copyright (c) 2012-2013 Yoran Heling

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be included
  in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <global.h>
#include <share/local.h>

/* Scanning a shared directory is done in two stages. First each of the
 * affected filesystem directories is read in sequence, with the results merged
 * into a single virtual directory. Then, this resulting directory is merged
 * into the actual share structure, comparing the differences and updating the
 * database and hash indices while merging.
 *
 * The first stage is done in a background thread (share_scan_thread*), and is
 * run for each affected filesystem dir in the order of their precedence. The
 * order matters due to the merging into a single accumulated result - the
 * merge determines which files should remain and which are "hidden".
 *
 *   Given (share_scan_work_t):
 *   - fspath: A filesystem path,
 *   - dest: An ordered destination share_flv_t (accumulated result)
 *   - pathid
 *
 *   Will:
 *   - Read all names in `fspath' and create an ordered share_flv_t lst
 *	 - Set share_fl_t.(name|size|lastmod|pathid) for each entry in lst
 *	 - Remove items from lst that have a duplicate casefolded name
 *   - Go through `dest' and `lst' in order and:
 *     - If in `lst' and not in `dest': add it to `dest'
 *     - Otherwise, free()
 *
 *
 * The second stage is performed in the main thread (share_scan_merge*):
 *
 *   Given:
 *   - dir: Previous share_fl_t * directory (may be empty)
 *   - lst: Accumulated directory results from the first stage
 *
 *   Will:
 *   - Go through `lst' and `dir' in order and:
 *     - If in `dir' and not in `lst':
 *       - Remove from `dir'
 *       - Remove its pathid from the associated row in the sharefiles table,
 *         recursively for directories.
 *     - If in `lst' and not in `dir':
 *       - Add to `dir'
 *       - If it's a file, add to hash queue
 *     - If in `dir' and `lst':
 *       - If it used to be a directory and is now a file or vice versa
 *         || If it's a file, and its pathid has changed
 *         || If the names have different original case
 *         || If it's a file, and its size or lastmod has changed:
 *         - Re-insert in `dir' as in the remove and add actions above
 */


/* Maximum supported file size (16 TiB). This limit exists for a number of
 * reasons:
 * - This way we don't have to be very strict about checking for overflows when
 *   calculating a total share or directory size. It's easy to create one
 *   sparse file that overflows all other calculations, it's less easy to
 *   create 2^20 (more than a million) files of 16 TiB.
 *   (Still, even with this check you can get an overflow if you tried hard
 *   enough...)
 * - This gives us 20 bits in share_fl.flags, usable for various flags
 * - Regardless of how fast your machine is, hashing a single 16 TiB file take
 *   a while. Globster doesn't remember hashing progress of a single file
 *   across restarts.
 * XXX: This value also indirectly affects some parameters in share/hash.c,
 * make sure to revise those on changes to this value.
 */
#define SHARE_MAXFILESIZE (((uint64_t)1)<<44)


typedef struct {
	evtp_work_t w;
	share_flv_t dest;
	uint16_t pathid;
	bool pathexists : 1;
	bool followsymlinks : 1;
	bool excludehidden : 1;
	char fspath[];
} share_scan_work_t;


struct share_scan_t {
	ev_tstamp start;
	share_t *s;
	share_fl_t *root, *dir;
	share_scan_work_t **work, **next;
	bool pathexists; /* Whether the path exists in at least one of the scanned dirs */
};

typedef vec_t(share_scan_work_t *) share_scan_workv_t;

static void share_scan_next(share_scan_t *sc);


static share_fl_t *share_scan_thread_item(share_scan_work_t *w, const char *fname, kstring_t *buf) {
	struct stat st;
	share_fl_t *fl;

	if(fname[0] == '.' && (!fname[1] || (fname[1] == '.' && !fname[2])))
		return NULL;

	if(w->excludehidden && fname[0] == '.') {
		ytrace("Ignoring hidden file '%s/%s'", w->fspath, fname);
		return NULL;
	}

	/* TODO: Filename charset conversion + testing whether stat() survives that round-trip */

	buf->l = 0;
	ksprintf(buf, "%s/%s", w->fspath, fname);
	ytrace("Stat()ing '%s'", buf->s);

	if((w->followsymlinks ? stat : lstat)(buf->s, &st) == -1) {
		/* TODO: Report this error to D-Bus? */
		ywarn("Error reading file information for '%s': %s", buf->s, strerror(errno));
		return NULL;
	}

	if(!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode)) {
		yinfo("Not sharing '%s': Neither file nor directory", buf->s);
		return NULL;
	}

	if(S_ISREG(st.st_mode) && (uint64_t)st.st_size >= SHARE_MAXFILESIZE) {
		yinfo("Not sharing '%s': File too large (%"PRIu64" > %"PRIu64")", buf->s, st.st_size, SHARE_MAXFILESIZE);
		return NULL;
	}

	fl = share_fl_create(S_ISDIR(st.st_mode), fname, buf);
	if(!share_fl_isdir(fl)) {
		share_fl_setsize(fl, st.st_size);
		fl->lastmod = st.st_mtime;
		fl->pathid = w->pathid;
	}
	return fl;
}


static share_flv_t share_scan_thread_readdir(share_scan_work_t *w) {
	DIR *dir;
	struct dirent *item;
	share_fl_t *fl;
	share_flv_t lst = {};
	kstring_t buf = {};
	int olderrno;

	if(!(dir = opendir(w->fspath))) {
		w->pathexists = false;
		ytrace("Error opening directory '%s': %s", w->fspath, strerror(errno));
		return lst;
	}
	w->pathexists = true;

	errno = 0;
	while((item = readdir(dir)) != NULL)
		if((fl = share_scan_thread_item(w, item->d_name, &buf)) != NULL)
			vec_insert_order(lst, lst.n, fl);

	olderrno = errno;
	if(closedir(dir) == -1 || olderrno) {
		/* TODO: Report this error to D-Bus? */
		ywarn("Error reading file list from '%s': %s", w->fspath, strerror(olderrno ? olderrno : errno));
	}

	free(buf.s);
	return lst;
}


/* Remove items with the same (casefolded) name. In order to avoid that a
 * different item is chosen at each scan, the item to be removed is decided by
 * a casestr_cmp() on the casestr data (Which is almost always different for
 * different files, but reality sucks when, due to charset conversion, two
 * files map to exactly the same name. Properly handling that case may
 * complicate the code more than I'd like, so let's just accept some "random"
 * selection behaviour if that happens). */
static void share_scan_thread_rmdupes(share_scan_work_t *w, share_flv_t *lst) {
	size_t i = 1;

	while(i<lst->n) {
		char *as = share_fl_name(lst->a[i-1]);
		char *bs = share_fl_name(lst->a[i]);
		if(strcmp(as, bs) == 0) {
			size_t rem = casestr_cmp(as, bs) < 0 ? i : i-1;
			yinfo("Multiple files in '%s' casefold to '%s', only one will be shared", w->fspath, as);
			free(lst->a[rem]);
			vec_remove_order(*lst, rem);
		} else
			i++;
	}
}


static void share_scan_thread_merge(share_scan_work_t *w, share_flv_t *lst) {
	size_t li = 0, di = 0;

	while(li<lst->n) {
		int cmp = 1;

		if(di < w->dest.n) {
			char *ls = share_fl_name(lst->a[li]);
			do
				cmp = strcmp(ls, share_fl_name(w->dest.a[di]));
			while(cmp >= 0 && ++di < w->dest.n);
		}

		if(cmp == 0)
			free(lst->a[li]);
		else {
			vec_insert_order(w->dest, di, lst->a[li]);
			di++;
		}
		li++;
	}
}


static void share_scan_work(evtp_work_t *_w) {
	share_scan_work_t *w = (share_scan_work_t *)_w;
	ytrace("Scanning '%s'", w->fspath);
	share_flv_t lst = share_scan_thread_readdir(w);
	if(lst.n)
		qsort(lst.a, lst.n, sizeof(*lst.a), share_fl_sort_cmp);
	share_scan_thread_rmdupes(w, &lst);
	share_scan_thread_merge(w, &lst);
	free(lst.a);
}



static void share_scan_merge_new(share_t *s, share_fl_t *dir, share_fl_t *fl) {
	fl->parent = dir;
	if(!share_fl_isdir(fl))
		share_hash_add(s, fl);
	/* TODO: Add to sharefiles table */
}


static void share_scan_merge_del(share_t *s, share_fl_t *fl) {
	if(share_fl_isdir(fl)) {
		size_t i;
		for(i=0; i<fl->sub.n; i++)
			share_scan_merge_del(s, fl->sub.a[i]);
		free(fl->sub.a);
	} else {
		share_hash_remove(s, fl);
		/* TODO: Remove from sharefiles table */
	}
	free(fl);
}


static void share_scan_merge(share_t *s, share_fl_t *dst, share_flv_t *lst) {
	size_t li = 0, di = 0;

	while(li < lst->n || di < dst->sub.n) {
		share_fl_t *lf = li == lst->n ? NULL : lst->a[li];
		share_fl_t *df = di == dst->sub.n ? NULL : dst->sub.a[di];
		int cmp = !df ? -1 : !lf ? 1 : strcmp(share_fl_name(lf), share_fl_name(df));

		/* lf < df, meaning an item in lst is not in dst */
		if(cmp < 0) {
			vec_insert_order(dst->sub, di, lf);
			share_scan_merge_new(s, dst, lf);
			di++;
			li++;
			continue;
		}

		/* lf > df, meaning an item in dst is not in lst */
		if(cmp > 0) {
			share_scan_merge_del(s, df);
			vec_remove_order(dst->sub, di);
			continue;
		}

		/* lf == df, the item is in both dst and lst. Check for differences. */
		if(share_fl_isdir(lf) != share_fl_isdir(df)
				|| (!share_fl_isdir(lf) && (share_fl_size(lf) != share_fl_size(df) || lf->lastmod != df->lastmod || lf->pathid != lf->pathid))
				|| casestr_cmp(share_fl_name(lf), share_fl_name(df)) != 0) {
			share_scan_merge_del(s, df);
			share_scan_merge_new(s, dst, lf);
			dst->sub.a[di] = lf;
		}
		di++;
		li++;
	}
}


static void share_scan_work_done(evtp_work_t *_w) {
	share_scan_work_t *w = (share_scan_work_t *)_w;
	share_scan_t *sc = _w->data;
	share_flv_t dest = w->dest;
	bool pathexists = w->pathexists;
	free(w);

	/* Scan aborted, throw away results */
	if(!sc) {
		free(dest.a);
		return;
	}

	sc->pathexists = sc->pathexists || pathexists;
	*(sc->next++) = NULL;
	if(*sc->next) { /* More directories to scan, queue the next one */
		(*sc->next)->dest = dest;
		evtp_submit(&(*sc->next)->w, threadpool, share_scan_work, share_scan_work_done);
		return;
	}
	/* All directories scanned */

	if(!sc->pathexists && !dest.n) {
		kstring_t buf = {};
		share_fl_path(sc->dir, &buf);
		/* TODO: Report this error to D-Bus? */
		ywarn("No filesystem paths found for share %"PRIu16" vpath '%s'", sc->s->c.id, buf.s);
		free(buf.s);
	}

	free(sc->work);
	share_scan_merge(sc->s, sc->dir, &dest);
	free(dest.a);
	share_scan_next(sc);
}


/* Determines whether the given fspath should be scanned for the given vpath,
 * and creates/adds a work object to *work */
static void share_scan_dir_queue(share_scan_t *sc, share_scan_workv_t *work, const char *vpath, share_path_t *p, kstring_t *buf) {
	char *ps = p->props.VirtualPath;
	if(!path_isancestor(ps, vpath) && strcmp(ps, vpath) != 0)
		return;

	buf->l = 0;
	kputs(p->props.FilesystemPath, buf);
	kputs(ps[1] || !vpath[1] ? vpath+strlen(ps) : vpath, buf);

	share_scan_work_t *w = malloc(offsetof(share_scan_work_t, fspath) + 1 + buf->l);
	w->w.data = sc;
	w->followsymlinks = p->props.FollowSymlinks;
	w->excludehidden = p->props.ExcludeHidden;
	w->pathid = p->id;
	strcpy(w->fspath, buf->s);
	vec_insert_order(*work, work->n, w);
}


/* Determines whether the given path has its "mount point" under vpath and adds
 * a directory entry for it - to ensure that it exists and that it will be
 * scanned. */
static void share_scan_dir_addvpath(share_flv_t *dest, const char *vpath, share_path_t *p, kstring_t *buf) {
	char *ps = p->props.VirtualPath; /* temporarily modified in-place, but we can do that. */
	if(!path_isancestor(vpath, ps))
		return;

	ps += vpath[1] ? strlen(vpath)+1 : 1;
	char *end = ps;
	while(*end && *end != '/')
		end++;
	char endc = *end;
	*end = 0;
	share_fl_t *fl = share_fl_create(true, ps, buf);
	*end = endc;

	vec_insert_sorted(*dest, strcmp(share_fl_name(dest->a[i]), share_fl_name(fl)), fl);
}


static void share_scan_dir(share_scan_t *sc) {
	kstring_t vpath = {};
	share_fl_path(sc->dir, &vpath);
	ytrace("Queueing scan for share %"PRIu16" vpath '%s'", sc->s->c.id, vpath.s);

	/* Figure out which filesystem directories to scan and create appropriate work objects */
	share_scan_workv_t work = {};
	share_flv_t dest = {};
	kstring_t buf = {};
	size_t i;
	for(i=0; i<sc->s->c.paths.n; i++) {
		share_path_t *p = sc->s->c.paths.a[i];
		share_scan_dir_queue(sc, &work, vpath.s, p, &buf);
		share_scan_dir_addvpath(&dest, vpath.s, p, &buf);
	}
	free(buf.s);
	free(vpath.s);

	if(!work.n) {
		share_scan_merge(sc->s, sc->dir, &dest);
		share_scan_next(sc);
	} else {
		vec_insert_order(work, work.n, NULL);
		sc->pathexists = false;
		sc->work = sc->next = work.a;
		(*sc->next)->dest = dest;
		evtp_submit(&(*sc->next)->w, threadpool, share_scan_work, share_scan_work_done);
	}
}


/* Called when sc->dir has been scanned, looks for new directories to be
 * scanned. Uses a depth-first search. */
static void share_scan_next(share_scan_t *sc) {
	size_t j;
	share_fl_t *par, *fl = sc->dir;

	/* Look for the first child dir */
	for(j=0; j<fl->sub.n; j++)
		if(share_fl_isdir(fl->sub.a[j])) {
			sc->dir = fl->sub.a[j];
			share_scan_dir(sc);
			return;
		}

	/* Look for next sibling, or the sibling of a parent dir */
	while(fl->parent && fl != sc->root) {
		j = SIZE_MAX-1;
		par = fl->parent;
		vec_search(par->sub, strcmp(share_fl_name(par->sub.a[i]), share_fl_name(fl)), j=i);
		for(j++; j<par->sub.n; j++)
			if(share_fl_isdir(par->sub.a[j])) {
				sc->dir = par->sub.a[j];
				share_scan_dir(sc);
				return;
			}
		fl = fl->parent;
	}

	/* Nothing found, we're done. */
	if(ylog_enabled(YLOG_DEBUG)) {
		kstring_t buf = {};
		share_fl_path(sc->root, &buf);
		yinfo("Filesystem scan completed in %.3fs for share %"PRIu16" vpath '%s'", ev_now()-sc->start, sc->s->c.id, buf.s);
		free(buf.s);
	}
	share_share_refresh_done(sc->s);
	free(sc);
}


share_scan_t *share_scan(share_t *s, share_fl_t *root) {
	if(ylog_enabled(YLOG_DEBUG)) {
		kstring_t buf = {};
		share_fl_path(root, &buf);
		ydebug("Starting filesystem scan for share %"PRIu16" vpath '%s'", s->c.id, buf.s);
		free(buf.s);
	}

	share_scan_t *sc = malloc(sizeof(share_scan_t));
	sc->s = s;
	sc->start = ev_now();
	sc->root = sc->dir = root;
	share_scan_dir(sc);
	return sc;
}


void share_scan_cancel(share_scan_t *sc) {
	if(*sc->next)
		(*sc->next)->w.data = NULL;
	while(*(++sc->next))
		free(*sc->next);
	free(sc->work);
	free(sc);
}


/* vim: set noet sw=4 ts=4: */