mount_setattr.2: Minor wording, grammar, and formatting fixes
[man-pages.git] / man2 / open_by_handle_at.2
blobfa7add5cf0e940d816e3bd8d67a2ea9bc094d357
1 .\" Copyright (c) 2014 by Michael Kerrisk <mtk.manpages@gmail.com>
2 .\"
3 .\" %%%LICENSE_START(VERBATIM)
4 .\" Permission is granted to make and distribute verbatim copies of this
5 .\" manual provided the copyright notice and this permission notice are
6 .\" preserved on all copies.
7 .\"
8 .\" Permission is granted to copy and distribute modified versions of this
9 .\" manual under the conditions for verbatim copying, provided that the
10 .\" entire resulting derived work is distributed under the terms of a
11 .\" permission notice identical to this one.
12 .\"
13 .\" Since the Linux kernel and libraries are constantly changing, this
14 .\" manual page may be incorrect or out-of-date.  The author(s) assume no
15 .\" responsibility for errors or omissions, or for damages resulting from
16 .\" the use of the information contained herein.  The author(s) may not
17 .\" have taken the same level of care in the production of this manual,
18 .\" which is licensed free of charge, as they might when working
19 .\" professionally.
20 .\"
21 .\" Formatted or processed versions of this manual, if unaccompanied by
22 .\" the source, must acknowledge the copyright and authors of this work.
23 .\" %%%LICENSE_END
24 .\"
25 .TH OPEN_BY_HANDLE_AT 2 2021-03-22 "Linux" "Linux Programmer's Manual"
26 .SH NAME
27 name_to_handle_at, open_by_handle_at \- obtain handle
28 for a pathname and open file via a handle
29 .SH SYNOPSIS
30 .nf
31 .BR "#define _GNU_SOURCE" "         /* See feature_test_macros(7) */"
32 .B #include <fcntl.h>
33 .PP
34 .BI "int name_to_handle_at(int " dirfd ", const char *" pathname ,
35 .BI "                      struct file_handle *" handle ,
36 .BI "                      int *" mount_id ", int " flags );
37 .BI "int open_by_handle_at(int " mount_fd ", struct file_handle *" handle ,
38 .BI "                      int " flags );
39 .fi
40 .SH DESCRIPTION
41 The
42 .BR name_to_handle_at ()
43 and
44 .BR open_by_handle_at ()
45 system calls split the functionality of
46 .BR openat (2)
47 into two parts:
48 .BR name_to_handle_at ()
49 returns an opaque handle that corresponds to a specified file;
50 .BR open_by_handle_at ()
51 opens the file corresponding to a handle returned by a previous call to
52 .BR name_to_handle_at ()
53 and returns an open file descriptor.
54 .\"
55 .\"
56 .SS name_to_handle_at()
57 The
58 .BR name_to_handle_at ()
59 system call returns a file handle and a mount ID corresponding to
60 the file specified by the
61 .IR dirfd
62 and
63 .IR pathname
64 arguments.
65 The file handle is returned via the argument
66 .IR handle ,
67 which is a pointer to a structure of the following form:
68 .PP
69 .in +4n
70 .EX
71 struct file_handle {
72     unsigned int  handle_bytes;   /* Size of f_handle [in, out] */
73     int           handle_type;    /* Handle type [out] */
74     unsigned char f_handle[0];    /* File identifier (sized by
75                                      caller) [out] */
77 .EE
78 .in
79 .PP
80 It is the caller's responsibility to allocate the structure
81 with a size large enough to hold the handle returned in
82 .IR f_handle .
83 Before the call, the
84 .IR handle_bytes
85 field should be initialized to contain the allocated size for
86 .IR f_handle .
87 (The constant
88 .BR MAX_HANDLE_SZ ,
89 defined in
90 .IR <fcntl.h> ,
91 specifies the maximum expected size for a file handle.
92 It is not a
93 guaranteed upper limit as future filesystems may require more space.)
94 Upon successful return, the
95 .IR handle_bytes
96 field is updated to contain the number of bytes actually written to
97 .IR f_handle .
98 .PP
99 The caller can discover the required size for the
100 .I file_handle
101 structure by making a call in which
102 .IR handle\->handle_bytes
103 is zero;
104 in this case, the call fails with the error
105 .BR EOVERFLOW
107 .IR handle\->handle_bytes
108 is set to indicate the required size;
109 the caller can then use this information to allocate a structure
110 of the correct size (see EXAMPLES below).
111 Some care is needed here as
112 .BR EOVERFLOW
113 can also indicate that no file handle is available for this particular
114 name in a filesystem which does normally support file-handle lookup.
115 This case can be detected when the
116 .B EOVERFLOW
117 error is returned without
118 .I handle_bytes
119 being increased.
121 Other than the use of the
122 .IR handle_bytes
123 field, the caller should treat the
124 .IR file_handle
125 structure as an opaque data type: the
126 .IR handle_type
128 .IR f_handle
129 fields are needed only by a subsequent call to
130 .BR open_by_handle_at ().
133 .I flags
134 argument is a bit mask constructed by ORing together zero or more of
135 .BR AT_EMPTY_PATH
137 .BR AT_SYMLINK_FOLLOW ,
138 described below.
140 Together, the
141 .I pathname
143 .I dirfd
144 arguments identify the file for which a handle is to be obtained.
145 There are four distinct cases:
146 .IP * 3
148 .I pathname
149 is a nonempty string containing an absolute pathname,
150 then a handle is returned for the file referred to by that pathname.
151 In this case,
152 .IR dirfd
153 is ignored.
154 .IP *
156 .I pathname
157 is a nonempty string containing a relative pathname and
158 .IR dirfd
159 has the special value
160 .BR AT_FDCWD ,
161 then
162 .I pathname
163 is interpreted relative to the current working directory of the caller,
164 and a handle is returned for the file to which it refers.
165 .IP *
167 .I pathname
168 is a nonempty string containing a relative pathname and
169 .IR dirfd
170 is a file descriptor referring to a directory, then
171 .I pathname
172 is interpreted relative to the directory referred to by
173 .IR dirfd ,
174 and a handle is returned for the file to which it refers.
175 (See
176 .BR openat (2)
177 for an explanation of why "directory file descriptors" are useful.)
178 .IP *
180 .I pathname
181 is an empty string and
182 .I flags
183 specifies the value
184 .BR AT_EMPTY_PATH ,
185 then
186 .IR dirfd
187 can be an open file descriptor referring to any type of file,
189 .BR AT_FDCWD ,
190 meaning the current working directory,
191 and a handle is returned for the file to which it refers.
194 .I mount_id
195 argument returns an identifier for the filesystem
196 mount that corresponds to
197 .IR pathname .
198 This corresponds to the first field in one of the records in
199 .IR /proc/self/mountinfo .
200 Opening the pathname in the fifth field of that record yields a file
201 descriptor for the mount point;
202 that file descriptor can be used in a subsequent call to
203 .BR open_by_handle_at ().
204 .I mount_id
205 is returned both for a successful call and for a call that results
206 in the error
207 .BR EOVERFLOW .
209 By default,
210 .BR name_to_handle_at ()
211 does not dereference
212 .I pathname
213 if it is a symbolic link, and thus returns a handle for the link itself.
215 .B AT_SYMLINK_FOLLOW
216 is specified in
217 .IR flags ,
218 .I pathname
219 is dereferenced if it is a symbolic link
220 (so that the call returns a handle for the file referred to by the link).
222 .BR name_to_handle_at ()
223 does not trigger a mount when the final component of the pathname is an
224 automount point.
225 When a filesystem supports both file handles and
226 automount points, a
227 .BR name_to_handle_at ()
228 call on an automount point will return with error
229 .BR EOVERFLOW
230 without having increased
231 .IR handle_bytes .
232 This can happen since Linux 4.13
233 .\" commit 20fa19027286983ab2734b5910c4a687436e0c31
234 with NFS when accessing a directory
235 which is on a separate filesystem on the server.
236 In this case, the automount can be triggered by adding a "/" to the end
237 of the pathname.
238 .SS open_by_handle_at()
240 .BR open_by_handle_at ()
241 system call opens the file referred to by
242 .IR handle ,
243 a file handle returned by a previous call to
244 .BR name_to_handle_at ().
247 .IR mount_fd
248 argument is a file descriptor for any object (file, directory, etc.)
249 in the mounted filesystem with respect to which
250 .IR handle
251 should be interpreted.
252 The special value
253 .B AT_FDCWD
254 can be specified, meaning the current working directory of the caller.
257 .I flags
258 argument
259 is as for
260 .BR open (2).
262 .I handle
263 refers to a symbolic link, the caller must specify the
264 .B O_PATH
265 flag, and the symbolic link is not dereferenced; the
266 .B O_NOFOLLOW
267 flag, if specified, is ignored.
269 The caller must have the
270 .B CAP_DAC_READ_SEARCH
271 capability to invoke
272 .BR open_by_handle_at ().
273 .SH RETURN VALUE
274 On success,
275 .BR name_to_handle_at ()
276 returns 0,
278 .BR open_by_handle_at ()
279 returns a file descriptor (a nonnegative integer).
281 In the event of an error, both system calls return \-1 and set
282 .I errno
283 to indicate the error.
284 .SH ERRORS
285 .BR name_to_handle_at ()
287 .BR open_by_handle_at ()
288 can fail for the same errors as
289 .BR openat (2).
290 In addition, they can fail with the errors noted below.
292 .BR name_to_handle_at ()
293 can fail with the following errors:
295 .B EFAULT
296 .IR pathname ,
297 .IR mount_id ,
299 .IR handle
300 points outside your accessible address space.
302 .B EINVAL
303 .I flags
304 includes an invalid bit value.
306 .B EINVAL
307 .IR handle\->handle_bytes
308 is greater than
309 .BR MAX_HANDLE_SZ .
311 .B ENOENT
312 .I pathname
313 is an empty string, but
314 .BR AT_EMPTY_PATH
315 was not specified in
316 .IR flags .
318 .B ENOTDIR
319 The file descriptor supplied in
320 .I dirfd
321 does not refer to a directory,
322 and it is not the case that both
323 .I flags
324 includes
325 .BR AT_EMPTY_PATH
327 .I pathname
328 is an empty string.
330 .B EOPNOTSUPP
331 The filesystem does not support decoding of a pathname to a file handle.
333 .B EOVERFLOW
335 .I handle\->handle_bytes
336 value passed into the call was too small.
337 When this error occurs,
338 .I handle\->handle_bytes
339 is updated to indicate the required size for the handle.
343 .BR open_by_handle_at ()
344 can fail with the following errors:
346 .B EBADF
347 .IR mount_fd
348 is not an open file descriptor.
350 .B EFAULT
351 .IR handle
352 points outside your accessible address space.
354 .B EINVAL
355 .I handle\->handle_bytes
356 is greater than
357 .BR MAX_HANDLE_SZ
358 or is equal to zero.
360 .B ELOOP
361 .I handle
362 refers to a symbolic link, but
363 .B O_PATH
364 was not specified in
365 .IR flags .
367 .B EPERM
368 The caller does not have the
369 .BR CAP_DAC_READ_SEARCH
370 capability.
372 .B ESTALE
373 The specified
374 .I handle
375 is not valid.
376 This error will occur if, for example, the file has been deleted.
377 .SH VERSIONS
378 These system calls first appeared in Linux 2.6.39.
379 Library support is provided in glibc since version 2.14.
380 .SH CONFORMING TO
381 These system calls are nonstandard Linux extensions.
383 FreeBSD has a broadly similar pair of system calls in the form of
384 .BR getfh ()
386 .BR openfh ().
387 .SH NOTES
388 A file handle can be generated in one process using
389 .BR name_to_handle_at ()
390 and later used in a different process that calls
391 .BR open_by_handle_at ().
393 Some filesystem don't support the translation of pathnames to
394 file handles, for example,
395 .IR /proc ,
396 .IR /sys ,
397 and various network filesystems.
399 A file handle may become invalid ("stale") if a file is deleted,
400 or for other filesystem-specific reasons.
401 Invalid handles are notified by an
402 .B ESTALE
403 error from
404 .BR open_by_handle_at ().
406 These system calls are designed for use by user-space file servers.
407 For example, a user-space NFS server might generate a file handle
408 and pass it to an NFS client.
409 Later, when the client wants to open the file,
410 it could pass the handle back to the server.
411 .\" https://lwn.net/Articles/375888/
412 .\"     "Open by handle" - Jonathan Corbet, 2010-02-23
413 This sort of functionality allows a user-space file server to operate in
414 a stateless fashion with respect to the files it serves.
417 .I pathname
418 refers to a symbolic link and
419 .IR flags
420 does not specify
421 .BR AT_SYMLINK_FOLLOW ,
422 then
423 .BR name_to_handle_at ()
424 returns a handle for the link (rather than the file to which it refers).
425 .\" commit bcda76524cd1fa32af748536f27f674a13e56700
426 The process receiving the handle can later perform operations
427 on the symbolic link by converting the handle to a file descriptor using
428 .BR open_by_handle_at ()
429 with the
430 .BR O_PATH
431 flag, and then passing the file descriptor as the
432 .IR dirfd
433 argument in system calls such as
434 .BR readlinkat (2)
436 .BR fchownat (2).
437 .SS Obtaining a persistent filesystem ID
438 The mount IDs in
439 .IR /proc/self/mountinfo
440 can be reused as filesystems are unmounted and mounted.
441 Therefore, the mount ID returned by
442 .BR name_to_handle_at ()
444 .IR *mount_id )
445 should not be treated as a persistent identifier
446 for the corresponding mounted filesystem.
447 However, an application can use the information in the
448 .I mountinfo
449 record that corresponds to the mount ID
450 to derive a persistent identifier.
452 For example, one can use the device name in the fifth field of the
453 .I mountinfo
454 record to search for the corresponding device UUID via the symbolic links in
455 .IR /dev/disks/by\-uuid .
456 (A more comfortable way of obtaining the UUID is to use the
457 .\" e.g., http://stackoverflow.com/questions/6748429/using-libblkid-to-find-uuid-of-a-partition
458 .BR libblkid (3)
459 library.)
460 That process can then be reversed,
461 using the UUID to look up the device name,
462 and then obtaining the corresponding mount point,
463 in order to produce the
464 .IR mount_fd
465 argument used by
466 .BR open_by_handle_at ().
467 .SH EXAMPLES
468 The two programs below demonstrate the use of
469 .BR name_to_handle_at ()
471 .BR open_by_handle_at ().
472 The first program
473 .RI ( t_name_to_handle_at.c )
474 uses
475 .BR name_to_handle_at ()
476 to obtain the file handle and mount ID
477 for the file specified in its command-line argument;
478 the handle and mount ID are written to standard output.
480 The second program
481 .RI ( t_open_by_handle_at.c )
482 reads a mount ID and file handle from standard input.
483 The program then employs
484 .BR open_by_handle_at ()
485 to open the file using that handle.
486 If an optional command-line argument is supplied, then the
487 .IR mount_fd
488 argument for
489 .BR open_by_handle_at ()
490 is obtained by opening the directory named in that argument.
491 Otherwise,
492 .IR mount_fd
493 is obtained by scanning
494 .IR /proc/self/mountinfo
495 to find a record whose mount ID matches the mount ID
496 read from standard input,
497 and the mount directory specified in that record is opened.
498 (These programs do not deal with the fact that mount IDs are not persistent.)
500 The following shell session demonstrates the use of these two programs:
502 .in +4n
504 $ \fBecho \(aqCan you please think about it?\(aq > cecilia.txt\fP
505 $ \fB./t_name_to_handle_at cecilia.txt > fh\fP
506 $ \fB./t_open_by_handle_at < fh\fP
507 open_by_handle_at: Operation not permitted
508 $ \fBsudo ./t_open_by_handle_at < fh\fP      # Need CAP_SYS_ADMIN
509 Read 31 bytes
510 $ \fBrm cecilia.txt\fP
514 Now we delete and (quickly) re-create the file so that
515 it has the same content and (by chance) the same inode.
516 Nevertheless,
517 .BR open_by_handle_at ()
518 .\" Christoph Hellwig: That's why the file handles contain a generation
519 .\" counter that gets incremented in this case.
520 recognizes that the original file referred to by the file handle
521 no longer exists.
523 .in +4n
525 $ \fBstat \-\-printf="%i\en" cecilia.txt\fP     # Display inode number
526 4072121
527 $ \fBrm cecilia.txt\fP
528 $ \fBecho \(aqCan you please think about it?\(aq > cecilia.txt\fP
529 $ \fBstat \-\-printf="%i\en" cecilia.txt\fP     # Check inode number
530 4072121
531 $ \fBsudo ./t_open_by_handle_at < fh\fP
532 open_by_handle_at: Stale NFS file handle
535 .SS Program source: t_name_to_handle_at.c
538 #define _GNU_SOURCE
539 #include <sys/types.h>
540 #include <sys/stat.h>
541 #include <fcntl.h>
542 #include <stdio.h>
543 #include <stdlib.h>
544 #include <unistd.h>
545 #include <errno.h>
546 #include <string.h>
548 #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \e
549                         } while (0)
552 main(int argc, char *argv[])
554     struct file_handle *fhp;
555     int mount_id, fhsize, flags, dirfd;
556     char *pathname;
558     if (argc != 2) {
559         fprintf(stderr, "Usage: %s pathname\en", argv[0]);
560         exit(EXIT_FAILURE);
561     }
563     pathname = argv[1];
565     /* Allocate file_handle structure. */
567     fhsize = sizeof(*fhp);
568     fhp = malloc(fhsize);
569     if (fhp == NULL)
570         errExit("malloc");
572     /* Make an initial call to name_to_handle_at() to discover
573        the size required for file handle. */
575     dirfd = AT_FDCWD;           /* For name_to_handle_at() calls */
576     flags = 0;                  /* For name_to_handle_at() calls */
577     fhp\->handle_bytes = 0;
578     if (name_to_handle_at(dirfd, pathname, fhp,
579                 &mount_id, flags) != \-1 || errno != EOVERFLOW) {
580         fprintf(stderr, "Unexpected result from name_to_handle_at()\en");
581         exit(EXIT_FAILURE);
582     }
584     /* Reallocate file_handle structure with correct size. */
586     fhsize = sizeof(*fhp) + fhp\->handle_bytes;
587     fhp = realloc(fhp, fhsize);         /* Copies fhp\->handle_bytes */
588     if (fhp == NULL)
589         errExit("realloc");
591     /* Get file handle from pathname supplied on command line. */
593     if (name_to_handle_at(dirfd, pathname, fhp, &mount_id, flags) == \-1)
594         errExit("name_to_handle_at");
596     /* Write mount ID, file handle size, and file handle to stdout,
597        for later reuse by t_open_by_handle_at.c. */
599     printf("%d\en", mount_id);
600     printf("%u %d   ", fhp\->handle_bytes, fhp\->handle_type);
601     for (int j = 0; j < fhp\->handle_bytes; j++)
602         printf(" %02x", fhp\->f_handle[j]);
603     printf("\en");
605     exit(EXIT_SUCCESS);
608 .SS Program source: t_open_by_handle_at.c
611 #define _GNU_SOURCE
612 #include <sys/types.h>
613 #include <sys/stat.h>
614 #include <fcntl.h>
615 #include <limits.h>
616 #include <stdio.h>
617 #include <stdlib.h>
618 #include <unistd.h>
619 #include <string.h>
621 #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \e
622                         } while (0)
624 /* Scan /proc/self/mountinfo to find the line whose mount ID matches
625    \(aqmount_id\(aq. (An easier way to do this is to install and use the
626    \(aqlibmount\(aq library provided by the \(aqutil\-linux\(aq project.)
627    Open the corresponding mount path and return the resulting file
628    descriptor. */
630 static int
631 open_mount_path_by_id(int mount_id)
633     char *linep;
634     size_t lsize;
635     char mount_path[PATH_MAX];
636     int mi_mount_id, found;
637     ssize_t nread;
638     FILE *fp;
640     fp = fopen("/proc/self/mountinfo", "r");
641     if (fp == NULL)
642         errExit("fopen");
644     found = 0;
645     linep = NULL;
646     while (!found) {
647         nread = getline(&linep, &lsize, fp);
648         if (nread == \-1)
649             break;
651         nread = sscanf(linep, "%d %*d %*s %*s %s",
652                        &mi_mount_id, mount_path);
653         if (nread != 2) {
654             fprintf(stderr, "Bad sscanf()\en");
655             exit(EXIT_FAILURE);
656         }
658         if (mi_mount_id == mount_id)
659             found = 1;
660     }
661     free(linep);
663     fclose(fp);
665     if (!found) {
666         fprintf(stderr, "Could not find mount point\en");
667         exit(EXIT_FAILURE);
668     }
670     return open(mount_path, O_RDONLY);
674 main(int argc, char *argv[])
676     struct file_handle *fhp;
677     int mount_id, fd, mount_fd, handle_bytes;
678     ssize_t nread;
679     char buf[1000];
680 #define LINE_SIZE 100
681     char line1[LINE_SIZE], line2[LINE_SIZE];
682     char *nextp;
684     if ((argc > 1 && strcmp(argv[1], "\-\-help") == 0) || argc > 2) {
685         fprintf(stderr, "Usage: %s [mount\-path]\en", argv[0]);
686         exit(EXIT_FAILURE);
687     }
689     /* Standard input contains mount ID and file handle information:
691          Line 1: <mount_id>
692          Line 2: <handle_bytes> <handle_type>   <bytes of handle in hex>
693     */
695     if ((fgets(line1, sizeof(line1), stdin) == NULL) ||
696            (fgets(line2, sizeof(line2), stdin) == NULL)) {
697         fprintf(stderr, "Missing mount_id / file handle\en");
698         exit(EXIT_FAILURE);
699     }
701     mount_id = atoi(line1);
703     handle_bytes = strtoul(line2, &nextp, 0);
705     /* Given handle_bytes, we can now allocate file_handle structure. */
707     fhp = malloc(sizeof(*fhp) + handle_bytes);
708     if (fhp == NULL)
709         errExit("malloc");
711     fhp\->handle_bytes = handle_bytes;
713     fhp\->handle_type = strtoul(nextp, &nextp, 0);
715     for (int j = 0; j < fhp\->handle_bytes; j++)
716         fhp\->f_handle[j] = strtoul(nextp, &nextp, 16);
718     /* Obtain file descriptor for mount point, either by opening
719        the pathname specified on the command line, or by scanning
720        /proc/self/mounts to find a mount that matches the \(aqmount_id\(aq
721        that we received from stdin. */
723     if (argc > 1)
724         mount_fd = open(argv[1], O_RDONLY);
725     else
726         mount_fd = open_mount_path_by_id(mount_id);
728     if (mount_fd == \-1)
729         errExit("opening mount fd");
731     /* Open file using handle and mount point. */
733     fd = open_by_handle_at(mount_fd, fhp, O_RDONLY);
734     if (fd == \-1)
735         errExit("open_by_handle_at");
737     /* Try reading a few bytes from the file. */
739     nread = read(fd, buf, sizeof(buf));
740     if (nread == \-1)
741         errExit("read");
743     printf("Read %zd bytes\en", nread);
745     exit(EXIT_SUCCESS);
748 .SH SEE ALSO
749 .BR open (2),
750 .BR libblkid (3),
751 .BR blkid (8),
752 .BR findfs (8),
753 .BR mount (8)
756 .I libblkid
758 .I libmount
759 documentation in the latest
760 .I util\-linux
761 release at
762 .UR https://www.kernel.org/pub/linux/utils/util\-linux/