GCC Code Coverage Report


Directory: cvmfs/
File: cvmfs/loader.cc
Date: 2024-04-28 02:33:07
Exec Total Coverage
Lines: 0 531 0.0%
Branches: 0 960 0.0%

Line Branch Exec Source
1 /**
2 * This file is part of the CernVM File System.
3 *
4 * Implements stub callback functions for Fuse. Their purpose is to
5 * redirect calls to the cvmfs shared library and to block calls during the
6 * update of the library.
7 *
8 * The main executable and the cvmfs shared library _must not_ share any
9 * symbols.
10 */
11
12 #define ENOATTR ENODATA /**< instead of including attr/xattr.h */
13 #define _FILE_OFFSET_BITS 64
14
15 #include "cvmfs_config.h"
16 #include "loader.h"
17
18 #include <dlfcn.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <sched.h>
22 #include <signal.h>
23 #include <stddef.h>
24 #include <sys/resource.h>
25 #include <time.h>
26 #include <unistd.h>
27 // If valgrind headers are present on the build system, then we can detect
28 // valgrind at runtime.
29 #ifdef HAS_VALGRIND_HEADERS
30 #include <valgrind/valgrind.h>
31 #endif
32
33 #include <cassert>
34 #include <cstdlib>
35 #include <cstring>
36 #include <string>
37 #include <vector>
38
39 #include "duplex_fuse.h"
40 #include "fence.h"
41 #include "fuse_main.h"
42 #include "loader_talk.h"
43 #include "options.h"
44 #include "sanitizer.h"
45 #include "util/atomic.h"
46 #include "util/exception.h"
47 #include "util/logging.h"
48 #include "util/platform.h"
49 #include "util/posix.h"
50 #include "util/string.h"
51
52 using namespace std; // NOLINT
53
54 namespace loader {
55
56 // Follow the fuse convention for option parsing
57 struct CvmfsOptions {
58 char *config;
59 int uid;
60 int gid;
61 int system_mount;
62 int grab_mountpoint;
63 int cvmfs_suid;
64 int disable_watchdog;
65 int simple_options_parsing;
66 int foreground;
67 int fuse_debug;
68
69 // Ignored options
70 int ign_netdev;
71 int ign_user;
72 int ign_nouser;
73 int ign_users;
74 int ign_auto;
75 int ign_noauto;
76 int ign_libfuse;
77 };
78
79 enum {
80 KEY_HELP,
81 KEY_VERSION,
82 KEY_FOREGROUND,
83 KEY_SINGLETHREAD,
84 KEY_FUSE_DEBUG,
85 KEY_CVMFS_DEBUG,
86 KEY_OPTIONS_PARSE,
87 };
88 #define CVMFS_OPT(t, p, v) { t, offsetof(struct CvmfsOptions, p), v }
89 #define CVMFS_SWITCH(t, p) { t, offsetof(struct CvmfsOptions, p), 1 }
90 static struct fuse_opt cvmfs_array_opts[] = {
91 CVMFS_OPT("config=%s", config, 0),
92 CVMFS_OPT("uid=%d", uid, 0),
93 CVMFS_OPT("gid=%d", gid, 0),
94 CVMFS_SWITCH("system_mount", system_mount),
95 CVMFS_SWITCH("grab_mountpoint", grab_mountpoint),
96 CVMFS_SWITCH("cvmfs_suid", cvmfs_suid),
97 CVMFS_SWITCH("disable_watchdog", disable_watchdog),
98 CVMFS_SWITCH("simple_options_parsing", simple_options_parsing),
99 CVMFS_SWITCH("foreground", foreground),
100 CVMFS_SWITCH("fuse_debug", fuse_debug),
101
102 // Ignore these options
103 CVMFS_SWITCH("_netdev", ign_netdev),
104 CVMFS_SWITCH("user", ign_user),
105 CVMFS_SWITCH("nouser", ign_nouser),
106 CVMFS_SWITCH("users", ign_users),
107 CVMFS_SWITCH("auto", ign_auto),
108 CVMFS_SWITCH("noauto", ign_noauto),
109 CVMFS_OPT("libfuse=%d", ign_libfuse, 0),
110
111 FUSE_OPT_KEY("-V", KEY_VERSION),
112 FUSE_OPT_KEY("--version", KEY_VERSION),
113 FUSE_OPT_KEY("-h", KEY_HELP),
114 FUSE_OPT_KEY("--help", KEY_HELP),
115 FUSE_OPT_KEY("-f", KEY_FOREGROUND),
116 FUSE_OPT_KEY("-d", KEY_FUSE_DEBUG),
117 FUSE_OPT_KEY("debug", KEY_CVMFS_DEBUG),
118 FUSE_OPT_KEY("-s", KEY_SINGLETHREAD),
119 FUSE_OPT_KEY("parse", KEY_OPTIONS_PARSE),
120 FUSE_OPT_KEY("-k", KEY_OPTIONS_PARSE),
121 {0, 0, 0},
122 };
123
124
125 string *repository_name_ = NULL;
126 string *mount_point_ = NULL;
127 string *config_files_ = NULL;
128 string *socket_path_ = NULL;
129 string *usyslog_path_ = NULL;
130 int fuse3_max_threads_ = 0;
131 int fuse3_idle_threads_ = 0;
132 uid_t uid_ = 0;
133 gid_t gid_ = 0;
134 bool single_threaded_ = false;
135 bool foreground_ = false;
136 bool debug_mode_ = false;
137 bool system_mount_ = false;
138 bool grab_mountpoint_ = false;
139 bool parse_options_only_ = false;
140 bool suid_mode_ = false;
141 bool premounted_ = false;
142 bool disable_watchdog_ = false;
143 bool simple_options_parsing_ = false;
144 void *library_handle_;
145 Fence *fence_reload_;
146 CvmfsExports *cvmfs_exports_;
147 LoaderExports *loader_exports_;
148
149
150 static void Usage(const string &exename) {
151 LogCvmfs(kLogCvmfs, kLogStdout,
152 "The CernVM File System\n"
153 "Version %s\n"
154 "Copyright (c) 2009- CERN, all rights reserved\n\n"
155 "Please visit http://cernvm.cern.ch for details.\n\n"
156 "Usage: %s [-h] [-V] [-s] [-f] [-d] [-k] [-o mount options] "
157 "<repository name> <mount point>\n\n"
158 "CernVM-FS general options:\n"
159 " --help|-h Print Help output (this)\n"
160 " --version|-V Print CernVM-FS version\n"
161 " -s Run singlethreaded\n"
162 " -f Run in foreground\n"
163 " -d Enable debugging\n"
164 " -k Parse options\n"
165 "CernVM-FS mount options:\n"
166 " -o config=FILES colon-separated path list of config files\n"
167 " -o uid=UID Drop credentials to another user\n"
168 " -o gid=GID Drop credentials to another group\n"
169 " -o system_mount Indicate that mount is system-wide\n"
170 " -o grab_mountpoint give ownership of the mountpoint to the user "
171 "before mounting (required for autofs)\n"
172 " -o parse Parse and print cvmfs parameters\n"
173 " -o cvmfs_suid Enable suid mode\n\n"
174 " -o disable_watchdog Do not spawn a post mortem crash handler\n"
175 " -o foreground Run in foreground\n"
176 " -o libfuse=[2,3] Enforce a certain libfuse version\n"
177 "Fuse mount options:\n"
178 " -o allow_other allow access to other users\n"
179 " -o allow_root allow access to root\n"
180 " -o nonempty allow mounts over non-empty directory\n",
181 PACKAGE_VERSION, exename.c_str());
182 }
183
184 /**
185 * For an premounted mountpoint, the argument is the file descriptor to
186 * /dev/fuse provided in the form /dev/fd/%d
187 */
188 bool CheckPremounted(const std::string &mountpoint) {
189 int len;
190 unsigned fd;
191 bool retval = (sscanf(mountpoint.c_str(), "/dev/fd/%u%n", &fd, &len) == 1) &&
192 (len >= 0) &&
193 (static_cast<unsigned>(len) == mountpoint.length());
194 if (retval) {
195 LogCvmfs(kLogCvmfs, kLogStdout,
196 "CernVM-FS: pre-mounted on file descriptor %d", fd);
197 return true;
198 }
199 return false;
200 }
201
202
203 static void stub_init(void *userdata, struct fuse_conn_info *conn) {
204 FenceGuard fence_guard(fence_reload_);
205 cvmfs_exports_->cvmfs_operations.init(userdata, conn);
206 }
207
208
209 static void stub_destroy(void *userdata) {
210 FenceGuard fence_guard(fence_reload_);
211 cvmfs_exports_->cvmfs_operations.destroy(userdata);
212 }
213
214
215 static void stub_lookup(fuse_req_t req, fuse_ino_t parent,
216 const char *name)
217 {
218 FenceGuard fence_guard(fence_reload_);
219 cvmfs_exports_->cvmfs_operations.lookup(req, parent, name);
220 }
221
222
223 static void stub_getattr(fuse_req_t req, fuse_ino_t ino,
224 struct fuse_file_info *fi)
225 {
226 FenceGuard fence_guard(fence_reload_);
227 cvmfs_exports_->cvmfs_operations.getattr(req, ino, fi);
228 }
229
230
231 static void stub_readlink(fuse_req_t req, fuse_ino_t ino) {
232 FenceGuard fence_guard(fence_reload_);
233 cvmfs_exports_->cvmfs_operations.readlink(req, ino);
234 }
235
236
237 static void stub_opendir(fuse_req_t req, fuse_ino_t ino,
238 struct fuse_file_info *fi)
239 {
240 FenceGuard fence_guard(fence_reload_);
241 cvmfs_exports_->cvmfs_operations.opendir(req, ino, fi);
242 }
243
244
245 static void stub_releasedir(fuse_req_t req, fuse_ino_t ino,
246 struct fuse_file_info *fi)
247 {
248 FenceGuard fence_guard(fence_reload_);
249 cvmfs_exports_->cvmfs_operations.releasedir(req, ino, fi);
250 }
251
252
253 static void stub_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
254 off_t off, struct fuse_file_info *fi)
255 {
256 FenceGuard fence_guard(fence_reload_);
257 cvmfs_exports_->cvmfs_operations.readdir(req, ino, size, off, fi);
258 }
259
260
261 static void stub_open(fuse_req_t req, fuse_ino_t ino,
262 struct fuse_file_info *fi)
263 {
264 FenceGuard fence_guard(fence_reload_);
265 cvmfs_exports_->cvmfs_operations.open(req, ino, fi);
266 }
267
268
269 static void stub_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off,
270 struct fuse_file_info *fi)
271 {
272 FenceGuard fence_guard(fence_reload_);
273 cvmfs_exports_->cvmfs_operations.read(req, ino, size, off, fi);
274 }
275
276
277 static void stub_release(fuse_req_t req, fuse_ino_t ino,
278 struct fuse_file_info *fi)
279 {
280 FenceGuard fence_guard(fence_reload_);
281 cvmfs_exports_->cvmfs_operations.release(req, ino, fi);
282 }
283
284
285 static void stub_statfs(fuse_req_t req, fuse_ino_t ino) {
286 FenceGuard fence_guard(fence_reload_);
287 cvmfs_exports_->cvmfs_operations.statfs(req, ino);
288 }
289
290
291 #ifdef __APPLE__
292 static void stub_getxattr(fuse_req_t req, fuse_ino_t ino, const char *name,
293 size_t size, uint32_t position)
294 #else
295 static void stub_getxattr(fuse_req_t req, fuse_ino_t ino, const char *name,
296 size_t size)
297 #endif
298 {
299 FenceGuard fence_guard(fence_reload_);
300 #ifdef __APPLE__
301 cvmfs_exports_->cvmfs_operations.getxattr(req, ino, name, size, position);
302 #else
303 cvmfs_exports_->cvmfs_operations.getxattr(req, ino, name, size);
304 #endif
305 }
306
307
308 static void stub_listxattr(fuse_req_t req, fuse_ino_t ino, size_t size) {
309 FenceGuard fence_guard(fence_reload_);
310 cvmfs_exports_->cvmfs_operations.listxattr(req, ino, size);
311 }
312
313
314 static void stub_forget(
315 fuse_req_t req,
316 fuse_ino_t ino,
317 #if CVMFS_USE_LIBFUSE == 2
318 unsigned long nlookup // NOLINT
319 #else
320 uint64_t nlookup
321 #endif
322 ) {
323 FenceGuard fence_guard(fence_reload_);
324 cvmfs_exports_->cvmfs_operations.forget(req, ino, nlookup);
325 }
326
327
328 #if (FUSE_VERSION >= 29)
329 static void stub_forget_multi(
330 fuse_req_t req,
331 size_t count,
332 struct fuse_forget_data *forgets
333 ) {
334 FenceGuard fence_guard(fence_reload_);
335 cvmfs_exports_->cvmfs_operations.forget_multi(req, count, forgets);
336 }
337 #endif
338
339
340 /**
341 * The callback used when fuse is parsing all the options
342 * We separate CVMFS options from FUSE options here.
343 *
344 * \return On success zero, else non-zero
345 */
346 static int ParseFuseOptions(void *data __attribute__((unused)), const char *arg,
347 int key, struct fuse_args *outargs)
348 {
349 unsigned arglen = 0;
350 if (arg)
351 arglen = strlen(arg);
352 switch (key) {
353 case FUSE_OPT_KEY_OPT:
354 // Check if it a cvmfs option
355 if ((arglen > 0) && (arg[0] != '-')) {
356 const char **o;
357 for (o = (const char**)cvmfs_array_opts; *o; o++) {
358 unsigned olen = strlen(*o);
359 if ((arglen > olen && arg[olen] == '=') &&
360 (strncasecmp(arg, *o, olen) == 0))
361 return 0;
362 }
363 }
364 return 1;
365
366 case FUSE_OPT_KEY_NONOPT:
367 // first: repository name, second: mount point
368 assert(arg != NULL);
369 if (!repository_name_) {
370 repository_name_ = new string(arg);
371 } else {
372 if (mount_point_)
373 return 1;
374 mount_point_ = new string(arg);
375 premounted_ = CheckPremounted(*mount_point_);
376 }
377 return 0;
378
379 case KEY_HELP:
380 Usage(outargs->argv[0]);
381 exit(0);
382 case KEY_VERSION:
383 LogCvmfs(kLogCvmfs, kLogStdout, "CernVM-FS version %s\n",
384 PACKAGE_VERSION);
385 exit(0);
386 case KEY_FOREGROUND:
387 foreground_ = true;
388 return 0;
389 case KEY_SINGLETHREAD:
390 single_threaded_ = true;
391 return 0;
392 case KEY_FUSE_DEBUG:
393 fuse_opt_add_arg(outargs, "-d");
394 case KEY_CVMFS_DEBUG:
395 debug_mode_ = true;
396 return 0;
397 case KEY_OPTIONS_PARSE:
398 parse_options_only_ = true;
399 return 0;
400 default:
401 PANIC(kLogStderr, "internal option parsing error");
402 }
403 }
404
405 static fuse_args *ParseCmdLine(int argc, char *argv[]) {
406 struct fuse_args *mount_options = new fuse_args();
407 CvmfsOptions cvmfs_options;
408 memset(&cvmfs_options, 0, sizeof(cvmfs_options));
409
410 mount_options->argc = argc;
411 mount_options->argv = argv;
412 mount_options->allocated = 0;
413 if ((fuse_opt_parse(mount_options, &cvmfs_options, cvmfs_array_opts,
414 ParseFuseOptions) != 0) ||
415 !mount_point_ || !repository_name_)
416 {
417 delete mount_options;
418 return NULL;
419 }
420 if (cvmfs_options.config) {
421 config_files_ = new string(cvmfs_options.config);
422 free(cvmfs_options.config);
423 }
424 uid_ = cvmfs_options.uid;
425 gid_ = cvmfs_options.gid;
426 system_mount_ = cvmfs_options.system_mount;
427 grab_mountpoint_ = cvmfs_options.grab_mountpoint;
428 suid_mode_ = cvmfs_options.cvmfs_suid;
429 disable_watchdog_ = cvmfs_options.disable_watchdog;
430 simple_options_parsing_ = cvmfs_options.simple_options_parsing;
431 if (cvmfs_options.foreground) {
432 foreground_ = true;
433 }
434 if (cvmfs_options.fuse_debug) {
435 fuse_opt_add_arg(mount_options, "-d");
436 }
437
438 return mount_options;
439 }
440
441
442 static void SetFuseOperations(struct fuse_lowlevel_ops *loader_operations) {
443 memset(loader_operations, 0, sizeof(*loader_operations));
444
445 loader_operations->init = stub_init;
446 loader_operations->destroy = stub_destroy;
447
448 loader_operations->lookup = stub_lookup;
449 loader_operations->getattr = stub_getattr;
450 loader_operations->readlink = stub_readlink;
451 loader_operations->open = stub_open;
452 loader_operations->read = stub_read;
453 loader_operations->release = stub_release;
454 loader_operations->opendir = stub_opendir;
455 loader_operations->readdir = stub_readdir;
456 loader_operations->releasedir = stub_releasedir;
457 loader_operations->statfs = stub_statfs;
458 loader_operations->getxattr = stub_getxattr;
459 loader_operations->listxattr = stub_listxattr;
460 loader_operations->forget = stub_forget;
461 }
462
463
464 static void *OpenLibrary(const string &path) {
465 return dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
466 }
467
468
469 static void CloseLibrary() {
470 #ifdef HAS_VALGRIND_HEADERS
471 // If the libcvmfs_fuse library is unloaded, valgrind can't resolve the
472 // symbols anymore. We skip under valgrind.
473 if (!RUNNING_ON_VALGRIND) {
474 #endif
475 dlclose(library_handle_);
476 library_handle_ = NULL;
477 #ifdef HAS_VALGRIND_HEADERS
478 }
479 #endif
480 }
481
482
483 static CvmfsExports *LoadLibrary(const bool debug_mode,
484 LoaderExports *loader_exports)
485 {
486 std::string local_lib_path = "./";
487 if (getenv("CVMFS_LIBRARY_PATH") != NULL) {
488 local_lib_path = getenv("CVMFS_LIBRARY_PATH");
489 if (!local_lib_path.empty() && (*local_lib_path.rbegin() != '/'))
490 local_lib_path.push_back('/');
491 }
492
493 #if CVMFS_USE_LIBFUSE == 2
494 string library_name = string("cvmfs_fuse") + ((debug_mode) ? "_debug" : "");
495 #else
496 string library_name = string("cvmfs_fuse3") + ((debug_mode) ? "_debug" : "");
497 #endif
498 library_name = platform_libname(library_name);
499 string error_messages;
500
501 vector<string> library_paths; // TODO(rmeusel): C++11 initializer
502 if (library_paths.empty()) {
503 library_paths.push_back(local_lib_path + library_name);
504 library_paths.push_back("/usr/lib/" + library_name);
505 library_paths.push_back("/usr/lib64/" + library_name);
506 #ifdef __APPLE__
507 // Since OS X El Capitan (10.11) came with SIP, we needed to relocate our
508 // binaries from /usr/... to /usr/local/...
509 library_paths.push_back("/usr/local/lib/" + library_name);
510 #endif
511 }
512
513 vector<string>::const_iterator i = library_paths.begin();
514 vector<string>::const_iterator iend = library_paths.end();
515 for (; i != iend; ++i) { // TODO(rmeusel): C++11 range based for
516 library_handle_ = OpenLibrary(*i);
517 if (library_handle_ != NULL) {
518 break;
519 }
520
521 error_messages += string(dlerror()) + "\n";
522 }
523
524 if (!library_handle_) {
525 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
526 "failed to load cvmfs library, tried: '%s'\n%s",
527 JoinStrings(library_paths, "' '").c_str(), error_messages.c_str());
528 return NULL;
529 }
530
531 CvmfsExports **exports_ptr = reinterpret_cast<CvmfsExports **>(
532 dlsym(library_handle_, "g_cvmfs_exports"));
533 if (!exports_ptr)
534 return NULL;
535
536 if (loader_exports) {
537 LoadEvent *load_event = new LoadEvent();
538 load_event->timestamp = time(NULL);
539 load_event->so_version = (*exports_ptr)->so_version;
540 loader_exports->history.push_back(load_event);
541 }
542
543 return *exports_ptr;
544 }
545
546 Failures Reload(const int fd_progress, const bool stop_and_go,
547 const ReloadMode reload_mode) {
548 int retval;
549
550 // for legacy call we take the current state of debug_mode_
551 if (reload_mode == kReloadDebug) {
552 debug_mode_ = true;
553 } else if (reload_mode == kReloadNoDebug) {
554 debug_mode_ = false;
555 }
556
557 retval = cvmfs_exports_->fnMaintenanceMode(fd_progress);
558 if (!retval)
559 return kFailMaintenanceMode;
560
561 SendMsg2Socket(fd_progress, "Blocking new file system calls\n");
562 fence_reload_->Close();
563
564 SendMsg2Socket(fd_progress, "Waiting for active file system calls\n");
565 fence_reload_->Drain();
566
567 retval = cvmfs_exports_->fnSaveState(fd_progress,
568 &loader_exports_->saved_states);
569 if (!retval)
570 return kFailSaveState;
571
572 SendMsg2Socket(fd_progress, "Unloading Fuse module\n");
573 cvmfs_exports_->fnFini();
574 CloseLibrary();
575
576 if (stop_and_go) {
577 CreateFile(*socket_path_ + ".paused", 0600);
578 SendMsg2Socket(fd_progress, "Waiting for the delivery of SIGUSR1...\n");
579 WaitForSignal(SIGUSR1);
580 unlink((*socket_path_ + ".paused").c_str());
581 }
582
583 SendMsg2Socket(fd_progress, "Re-Loading Fuse module\n");
584 cvmfs_exports_ = LoadLibrary(debug_mode_, loader_exports_);
585 if (!cvmfs_exports_)
586 return kFailLoadLibrary;
587 retval = cvmfs_exports_->fnInit(loader_exports_);
588 if (retval != kFailOk) {
589 string msg_progress = cvmfs_exports_->fnGetErrorMsg() + " (" +
590 StringifyInt(retval) + ")\n";
591 LogCvmfs(kLogCvmfs, kLogSyslogErr, "%s", msg_progress.c_str());
592 SendMsg2Socket(fd_progress, msg_progress);
593 return (Failures)retval;
594 }
595
596 retval = cvmfs_exports_->fnRestoreState(fd_progress,
597 loader_exports_->saved_states);
598 if (!retval)
599 return kFailRestoreState;
600 cvmfs_exports_->fnFreeSavedState(fd_progress, loader_exports_->saved_states);
601 for (unsigned i = 0, l = loader_exports_->saved_states.size(); i < l; ++i) {
602 delete loader_exports_->saved_states[i];
603 }
604 loader_exports_->saved_states.clear();
605
606 SendMsg2Socket(fd_progress, "Activating Fuse module\n");
607 cvmfs_exports_->fnSpawn();
608
609 fence_reload_->Open();
610 return kFailOk;
611 }
612
613 } // namespace loader
614
615
616 using namespace loader; // NOLINT(build/namespaces)
617
618 int FuseMain(int argc, char *argv[]) {
619 // Set a decent umask for new files (no write access to group/everyone).
620 // We want to allow group write access for the talk-socket.
621 umask(007);
622 // SIGUSR1 is used for the stop_and_go mode during reload
623 BlockSignal(SIGUSR1);
624
625 int retval;
626
627 // Jump into alternative process flavors (e.g. shared cache manager)
628 // We are here due to a fork+execve (ManagedExec in util.cc) or due to
629 // utility calls of cvmfs2
630 if ((argc > 1) && (strstr(argv[1], "__") == argv[1])) {
631 if (string(argv[1]) == string("__RELOAD__")) {
632 if (argc < 3)
633 return 1;
634 bool stop_and_go = false;
635 if ((argc > 3) && (string(argv[3]) == "stop_and_go"))
636 stop_and_go = true;
637
638 // always last param of the cvmfs2 __RELOAD__ command
639 // check if debug mode is requested
640 // NOTE:
641 // debug mode is decided based on CVMFS_DEBUGLOG being set or not
642 // this means: reloading is now always based on CVMFS_DEBUGLOG, and
643 // reload ignores the current state
644 //
645 // if you mount with debug but do not set CVMFS_DEBUGLOG and reload,
646 // you will reload with
647 if (std::string(argv[argc - 1]) == std::string("--debug")) {
648 debug_mode_ = true;
649 } else {
650 debug_mode_ = false;
651 }
652 retval = loader_talk::MainReload(argv[2], stop_and_go, debug_mode_);
653
654 if ((retval != 0) && (stop_and_go)) {
655 CreateFile(string(argv[2]) + ".paused.crashed", 0600);
656 }
657 return retval;
658 }
659
660 if (string(argv[1]) == string("__MK_ALIEN_CACHE__")) {
661 if (argc < 5)
662 return 1;
663 string alien_cache_dir = argv[2];
664 sanitizer::PositiveIntegerSanitizer sanitizer;
665 if (!sanitizer.IsValid(argv[3]) || !sanitizer.IsValid(argv[4]))
666 return 1;
667 uid_t uid_owner = String2Uint64(argv[3]);
668 gid_t gid_owner = String2Uint64(argv[4]);
669
670 int retval = MkdirDeep(alien_cache_dir, 0770);
671 if (!retval) {
672 LogCvmfs(kLogCvmfs, kLogStderr, "Failed to create %s",
673 alien_cache_dir.c_str());
674 return 1;
675 }
676 retval = chown(alien_cache_dir.c_str(), uid_owner, gid_owner);
677 if (retval != 0) {
678 LogCvmfs(kLogCvmfs, kLogStderr, "Failed to set owner of %s to %d:%d",
679 alien_cache_dir.c_str(), uid_owner, gid_owner);
680 return 1;
681 }
682 retval = SwitchCredentials(uid_owner, gid_owner, false);
683 if (!retval) {
684 LogCvmfs(kLogCvmfs, kLogStderr, "Failed to impersonate %d:%d",
685 uid_owner, gid_owner);
686 return 1;
687 }
688 // Allow access to user and group
689 retval = MakeCacheDirectories(alien_cache_dir, 0770);
690 if (!retval) {
691 LogCvmfs(kLogCvmfs, kLogStderr, "Failed to create cache skeleton");
692 return 1;
693 }
694 return 0;
695 }
696
697 debug_mode_ = getenv("__CVMFS_DEBUG_MODE__") != NULL;
698 cvmfs_exports_ = LoadLibrary(debug_mode_, NULL);
699 if (!cvmfs_exports_)
700 return kFailLoadLibrary;
701 return cvmfs_exports_->fnAltProcessFlavor(argc, argv);
702 }
703
704 // Option parsing
705 struct fuse_args *mount_options;
706 mount_options = ParseCmdLine(argc, argv);
707 if (!mount_options) {
708 Usage(argv[0]);
709 return kFailOptions;
710 }
711
712 string parameter;
713 OptionsManager *options_manager;
714 if (simple_options_parsing_) {
715 options_manager = new SimpleOptionsParser(
716 new DefaultOptionsTemplateManager(*repository_name_));
717 } else {
718 options_manager = new BashOptionsManager(
719 new DefaultOptionsTemplateManager(*repository_name_));
720 }
721 if (config_files_) {
722 vector<string> tokens = SplitString(*config_files_, ':');
723 for (unsigned i = 0, s = tokens.size(); i < s; ++i) {
724 options_manager->ParsePath(tokens[i], false);
725 }
726 } else {
727 options_manager->ParseDefault(*repository_name_);
728 }
729
730 #ifdef __APPLE__
731 string volname = "-ovolname=" + *repository_name_;
732 fuse_opt_add_arg(mount_options, volname.c_str());
733 // Allow for up to 5 minute "hangs" before OS X may kill cvmfs
734 fuse_opt_add_arg(mount_options, "-odaemon_timeout=300");
735 fuse_opt_add_arg(mount_options, "-onoapplexattr");
736 // Should libfuse be single-threaded? See CVM-871, CVM-855
737 // single_threaded_ = true;
738 #endif
739 if (options_manager->GetValue("CVMFS_MOUNT_RW", &parameter) &&
740 options_manager->IsOn(parameter))
741 {
742 fuse_opt_add_arg(mount_options, "-orw");
743 } else {
744 fuse_opt_add_arg(mount_options, "-oro");
745 }
746 fuse_opt_add_arg(mount_options, "-onodev");
747 if (options_manager->GetValue("CVMFS_SUID", &parameter) &&
748 options_manager->IsOn(parameter))
749 {
750 suid_mode_ = true;
751 }
752 if (suid_mode_) {
753 if (getuid() != 0) {
754 PANIC(kLogStderr | kLogSyslogErr,
755 "must be root to mount with suid option");
756 }
757 fuse_opt_add_arg(mount_options, "-osuid");
758 LogCvmfs(kLogCvmfs, kLogStdout, "CernVM-FS: running with suid support");
759 }
760
761 if (options_manager->GetValue("CVMFS_CPU_AFFINITY", &parameter)) {
762 #ifndef __APPLE__
763 cpu_set_t mask;
764 vector<string> cpus = SplitString(parameter, ',');
765 CPU_ZERO(&mask);
766 for (vector<string>::iterator i = cpus.begin(); i != cpus.end(); i++) {
767 CPU_SET(String2Uint64(Trim(*i)), &mask);
768 }
769 LogCvmfs(kLogCvmfs, kLogStdout,
770 "CernVM-FS: setting CPU Affinity to %s", parameter.c_str());
771 int err = sched_setaffinity(0, sizeof(mask), &mask);
772 if (err != 0) {
773 LogCvmfs(kLogCvmfs, kLogStdout | kLogSyslogErr,
774 "Setting CPU Affinity failed with error %d", errno);
775 }
776 #else
777 LogCvmfs(kLogCvmfs, kLogStdout | kLogSyslogErr,
778 "CPU affinity setting not supported on macOS");
779 #endif
780 }
781 loader_exports_ = new LoaderExports();
782 loader_exports_->loader_version = PACKAGE_VERSION;
783 loader_exports_->boot_time = time(NULL);
784 loader_exports_->program_name = argv[0];
785 loader_exports_->foreground = foreground_;
786 loader_exports_->repository_name = *repository_name_;
787 loader_exports_->mount_point = *mount_point_;
788 loader_exports_->device_id = "0:0"; // initially unknown, set after mount
789 loader_exports_->disable_watchdog = disable_watchdog_;
790 loader_exports_->simple_options_parsing = simple_options_parsing_;
791 if (config_files_)
792 loader_exports_->config_files = *config_files_;
793 else
794 loader_exports_->config_files = "";
795
796 if (parse_options_only_) {
797 LogCvmfs(kLogCvmfs, kLogStdout, "# CernVM-FS parameters:\n%s",
798 options_manager->Dump().c_str());
799 return 0;
800 }
801
802 // Logging
803 if (options_manager->GetValue("CVMFS_SYSLOG_LEVEL", &parameter))
804 SetLogSyslogLevel(String2Uint64(parameter));
805 else
806 SetLogSyslogLevel(3);
807 if (options_manager->GetValue("CVMFS_SYSLOG_FACILITY", &parameter))
808 SetLogSyslogFacility(String2Int64(parameter));
809 SetLogSyslogPrefix(*repository_name_);
810 // Deferr setting usyslog until credentials are dropped
811
812 // Permissions check
813 if (options_manager->GetValue("CVMFS_CHECK_PERMISSIONS", &parameter)) {
814 if (options_manager->IsOn(parameter)) {
815 fuse_opt_add_arg(mount_options, "-odefault_permissions");
816 }
817 }
818
819 if (!premounted_ && !DirectoryExists(*mount_point_)) {
820 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
821 "Mount point %s does not exist", mount_point_->c_str());
822 return kFailPermission;
823 }
824
825 // Number of file descriptors
826 if (options_manager->GetValue("CVMFS_NFILES", &parameter)) {
827 int retval = SetLimitNoFile(String2Uint64(parameter));
828 if (retval == -2) {
829 LogCvmfs(kLogCvmfs, kLogStdout, "CernVM-FS: running under valgrind");
830 } else if (retval == -1) {
831 if (system_mount_) {
832 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
833 "Failed to set maximum number of open files, "
834 "insufficient permissions");
835 return kFailPermission;
836 }
837 unsigned soft_limit, hard_limit;
838 GetLimitNoFile(&soft_limit, &hard_limit);
839 LogCvmfs(kLogCvmfs, kLogStdout | kLogSyslogWarn,
840 "Failed to set requested number of open files, "
841 "using maximum number %u", hard_limit);
842 if (hard_limit > soft_limit) {
843 (void) SetLimitNoFile(hard_limit);
844 }
845 }
846 }
847
848 // Apply OOM score adjustment
849 if (options_manager->GetValue("CVMFS_OOM_SCORE_ADJ", &parameter)) {
850 string proc_path = "/proc/" + StringifyInt(getpid()) + "/oom_score_adj";
851 int fd_oom = open(proc_path.c_str(), O_WRONLY);
852 if (fd_oom < 0) {
853 LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogWarn,
854 "failed to open %s", proc_path.c_str());
855 } else {
856 bool retval = SafeWrite(fd_oom, parameter.data(), parameter.length());
857 if (!retval) {
858 LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogWarn,
859 "failed to set OOM score adjustment to %s", parameter.c_str());
860 }
861 close(fd_oom);
862 }
863 }
864
865 // Protect the process from being killed by systemd
866 if (options_manager->GetValue("CVMFS_SYSTEMD_NOKILL", &parameter) &&
867 options_manager->IsOn(parameter))
868 {
869 argv[0][0] = '@';
870 }
871
872 // Grab mountpoint
873 if (grab_mountpoint_) {
874 if ((chown(mount_point_->c_str(), uid_, gid_) != 0) ||
875 (chmod(mount_point_->c_str(), 0755) != 0))
876 {
877 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
878 "Failed to grab mountpoint %s (%d)",
879 mount_point_->c_str(), errno);
880 return kFailPermission;
881 }
882 }
883
884 // Drop credentials
885 if ((uid_ != 0) || (gid_ != 0)) {
886 LogCvmfs(kLogCvmfs, kLogStdout, "CernVM-FS: running with credentials %d:%d",
887 uid_, gid_);
888 const bool retrievable = (suid_mode_ || !disable_watchdog_);
889 if (!SwitchCredentials(uid_, gid_, retrievable)) {
890 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
891 "Failed to drop credentials");
892 return kFailPermission;
893 }
894 }
895 if (disable_watchdog_) {
896 LogCvmfs(kLogCvmfs, kLogDebug, "No watchdog, enabling core files");
897 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
898 }
899
900 // Only set usyslog now, otherwise file permissions are wrong
901 usyslog_path_ = new string();
902 if (options_manager->GetValue("CVMFS_USYSLOG", &parameter))
903 *usyslog_path_ = parameter;
904 SetLogMicroSyslog(*usyslog_path_);
905
906 if (single_threaded_) {
907 LogCvmfs(kLogCvmfs, kLogStdout,
908 "CernVM-FS: running in single threaded mode");
909 }
910 if (debug_mode_) {
911 LogCvmfs(kLogCvmfs, kLogStdout | kLogSyslogWarn,
912 "CernVM-FS: running in debug mode");
913 }
914
915 #ifndef FUSE_CAP_POSIX_ACL
916 if (options_manager->GetValue("CVMFS_ENFORCE_ACLS", &parameter) &&
917 options_manager->IsOn(parameter))
918 {
919 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
920 "CernVM-FS: ACL support requested but not available in this "
921 "version of libfuse");
922 return kFailPermission;
923 }
924 #endif
925
926 // Initialize the loader socket, connections are not accepted until Spawn()
927 socket_path_ = new string("/var/run/cvmfs");
928 if (options_manager->GetValue("CVMFS_RELOAD_SOCKETS", &parameter))
929 *socket_path_ = MakeCanonicalPath(parameter);
930 *socket_path_ += "/cvmfs." + *repository_name_;
931 retval = loader_talk::Init(*socket_path_);
932 if (!retval) {
933 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
934 "Failed to initialize loader socket");
935 return kFailLoaderTalk;
936 }
937
938 // TODO(jblomer): we probably want to apply a default setting related to the
939 // number of cores.
940 if (options_manager->GetValue("CVMFS_FUSE3_MAX_THREADS", &parameter)) {
941 fuse3_max_threads_ = String2Int64(parameter);
942 }
943 if (options_manager->GetValue("CVMFS_FUSE3_IDLE_THREADS", &parameter)) {
944 fuse3_idle_threads_ = String2Int64(parameter);
945 }
946 #ifdef CVMFS_ENABLE_FUSE3_LOOP_CONFIG
947 if (fuse3_max_threads_) {
948 LogCvmfs(kLogCvmfs, kLogStdout,
949 "CernVM-FS: Fuse3 max_threads=%d", fuse3_max_threads_);
950 }
951 if (fuse3_idle_threads_) {
952 LogCvmfs(kLogCvmfs, kLogStdout,
953 "CernVM-FS: Fuse3 min_idle_threads=%d", fuse3_idle_threads_);
954 }
955 #else
956 if (fuse3_max_threads_ || fuse3_idle_threads_) {
957 LogCvmfs(kLogCvmfs, kLogStdout,
958 "CernVM-FS: ignoring fuse3 thread settings (libfuse too old)");
959 }
960 #endif
961
962 // Options are not needed anymore
963 delete options_manager;
964 options_manager = NULL;
965
966 struct fuse_session *session;
967 #if CVMFS_USE_LIBFUSE == 2
968 struct fuse_chan *channel;
969 loader_exports_->fuse_channel_or_session = reinterpret_cast<void **>(
970 &channel);
971 #else
972 loader_exports_->fuse_channel_or_session = reinterpret_cast<void **>(
973 &session);
974 #endif
975
976 // Load and initialize cvmfs library
977 LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak,
978 "CernVM-FS: loading Fuse module... ");
979 cvmfs_exports_ = LoadLibrary(debug_mode_, loader_exports_);
980 if (!cvmfs_exports_) {
981 return kFailLoadLibrary;
982 }
983 retval = cvmfs_exports_->fnInit(loader_exports_);
984 if (retval != kFailOk) {
985 if (retval == kFailDoubleMount) {
986 LogCvmfs(kLogCvmfs, kLogStderr,
987 "\nCernVM-FS: repository %s already mounted on %s",
988 loader_exports_->repository_name.c_str(),
989 loader_exports_->mount_point.c_str());
990 return 0;
991 }
992 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr, "%s (%d - %s)",
993 cvmfs_exports_->fnGetErrorMsg().c_str(),
994 retval, Code2Ascii((Failures)retval));
995 cvmfs_exports_->fnFini();
996 return retval;
997 }
998 LogCvmfs(kLogCvmfs, kLogStdout, "done");
999
1000 // Mount
1001 fence_reload_ = new Fence();
1002
1003 if (suid_mode_) {
1004 const bool retrievable = true;
1005 if (!SwitchCredentials(0, getgid(), retrievable)) {
1006 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
1007 "failed to re-gain root permissions for mounting");
1008 cvmfs_exports_->fnFini();
1009 return kFailPermission;
1010 }
1011 }
1012
1013
1014 struct fuse_lowlevel_ops loader_operations;
1015 SetFuseOperations(&loader_operations);
1016 #if (FUSE_VERSION >= 29)
1017 if (cvmfs_exports_->cvmfs_operations.forget_multi)
1018 loader_operations.forget_multi = stub_forget_multi;
1019 #endif
1020
1021 #if CVMFS_USE_LIBFUSE == 2
1022 channel = fuse_mount(mount_point_->c_str(), mount_options);
1023 if (!channel) {
1024 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
1025 "failed to create Fuse channel");
1026 cvmfs_exports_->fnFini();
1027 return kFailMount;
1028 }
1029
1030 session = fuse_lowlevel_new(mount_options, &loader_operations,
1031 sizeof(loader_operations), NULL);
1032 if (!session) {
1033 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
1034 "failed to create Fuse session");
1035 fuse_unmount(mount_point_->c_str(), channel);
1036 cvmfs_exports_->fnFini();
1037 return kFailMount;
1038 }
1039 #else
1040 // libfuse3
1041 session = fuse_session_new(mount_options, &loader_operations,
1042 sizeof(loader_operations), NULL);
1043 if (!session) {
1044 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
1045 "failed to create Fuse session");
1046 cvmfs_exports_->fnFini();
1047 return kFailMount;
1048 }
1049 retval = fuse_session_mount(session, mount_point_->c_str());
1050 if (retval != 0) {
1051 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
1052 "failed to mount file system");
1053 cvmfs_exports_->fnFini();
1054 return kFailMount;
1055 }
1056 #endif
1057
1058 // drop credentials
1059 if (suid_mode_) {
1060 const bool retrievable = !disable_watchdog_;
1061 if (!SwitchCredentials(uid_, gid_, retrievable)) {
1062 LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
1063 "failed to drop permissions after mounting");
1064 cvmfs_exports_->fnFini();
1065 return kFailPermission;
1066 }
1067 }
1068
1069 // Determine device id
1070 int fd_mountinfo = open("/proc/self/mountinfo", O_RDONLY);
1071 if (fd_mountinfo > 0) {
1072 std::string line;
1073 while (GetLineFd(fd_mountinfo, &line)) {
1074 std::vector<std::string> tokens = SplitString(line, ' ');
1075 if (tokens.size() < 5) continue;
1076 if (tokens[4] != loader_exports_->mount_point) continue;
1077 unsigned i = 5;
1078 for (; i < tokens.size(); ++i) {
1079 if (tokens[i] == "-") break;
1080 }
1081 if (tokens.size() < i + 3) continue;
1082 if (tokens[i + 2] != "cvmfs2") continue;
1083 loader_exports_->device_id = tokens[2];
1084 break;
1085 }
1086 close(fd_mountinfo);
1087 }
1088
1089 if (!premounted_) {
1090 LogCvmfs(kLogCvmfs, kLogStdout, "CernVM-FS: mounted cvmfs on %s",
1091 mount_point_->c_str());
1092 }
1093 LogCvmfs(kLogCvmfs, kLogSyslog,
1094 "CernVM-FS: linking %s to repository %s",
1095 mount_point_->c_str(), repository_name_->c_str());
1096 if (!foreground_)
1097 Daemonize();
1098
1099 cvmfs_exports_->fnSpawn();
1100 loader_talk::Spawn();
1101
1102 SetLogMicroSyslog("");
1103 retval = fuse_set_signal_handlers(session);
1104 assert(retval == 0);
1105 #if CVMFS_USE_LIBFUSE == 2
1106 fuse_session_add_chan(session, channel);
1107 #endif
1108 if (single_threaded_) {
1109 retval = fuse_session_loop(session);
1110 } else {
1111 #if CVMFS_USE_LIBFUSE == 2
1112 retval = fuse_session_loop_mt(session);
1113 #else
1114 #ifdef CVMFS_ENABLE_FUSE3_LOOP_CONFIG
1115 struct fuse_loop_config *fuse_loop_cfg = fuse_loop_cfg_create();
1116
1117 fuse_loop_cfg_set_clone_fd(fuse_loop_cfg, 1);
1118
1119 if (fuse3_max_threads_ > 0) {
1120 fuse_loop_cfg_set_max_threads(fuse_loop_cfg, fuse3_max_threads_);
1121 }
1122 if (fuse3_idle_threads_ > 0) {
1123 fuse_loop_cfg_set_idle_threads(fuse_loop_cfg, fuse3_idle_threads_);
1124 }
1125
1126 retval = fuse_session_loop_mt(session, fuse_loop_cfg);
1127 fuse_loop_cfg_destroy(fuse_loop_cfg);
1128 #else
1129 retval = fuse_session_loop_mt(session, 1 /* use fd per thread */);
1130 #endif // CVMFS_ENABLE_FUSE3_LOOP_CONFIG
1131 #endif // fuse2/3
1132 }
1133 SetLogMicroSyslog(*usyslog_path_);
1134
1135 loader_talk::Fini();
1136 cvmfs_exports_->fnFini();
1137
1138 // Unmount
1139 #if CVMFS_USE_LIBFUSE == 2
1140 fuse_remove_signal_handlers(session);
1141 fuse_session_remove_chan(channel);
1142 fuse_session_destroy(session);
1143 fuse_unmount(mount_point_->c_str(), channel);
1144 channel = NULL;
1145 #else
1146 // libfuse3
1147 fuse_remove_signal_handlers(session);
1148 fuse_session_unmount(session);
1149 fuse_session_destroy(session);
1150 #endif
1151 fuse_opt_free_args(mount_options);
1152 delete mount_options;
1153 session = NULL;
1154 mount_options = NULL;
1155
1156 CloseLibrary();
1157
1158 LogCvmfs(kLogCvmfs, kLogSyslog, "CernVM-FS: unmounted %s (%s)",
1159 mount_point_->c_str(), repository_name_->c_str());
1160
1161 delete fence_reload_;
1162 delete loader_exports_;
1163 delete config_files_;
1164 delete repository_name_;
1165 delete mount_point_;
1166 delete socket_path_;
1167 fence_reload_ = NULL;
1168 loader_exports_ = NULL;
1169 config_files_ = NULL;
1170 repository_name_ = NULL;
1171 mount_point_ = NULL;
1172 socket_path_ = NULL;
1173
1174 if (retval != 0)
1175 return kFailFuseLoop;
1176 return kFailOk;
1177 }
1178
1179
1180 __attribute__((visibility("default")))
1181 CvmfsStubExports *g_cvmfs_stub_exports = NULL;
1182
1183 static void __attribute__((constructor)) LibraryMain() {
1184 g_cvmfs_stub_exports = new CvmfsStubExports();
1185 g_cvmfs_stub_exports->fn_main = FuseMain;
1186 }
1187
1188 static void __attribute__((destructor)) LibraryExit() {
1189 delete g_cvmfs_stub_exports;
1190 g_cvmfs_stub_exports = NULL;
1191 }
1192