fanotify_mark.2: ERRORS: add missing EBADF error for invalid 'dirfd'
[man-pages.git] / man2 / open_by_handle_at.2
blobf3fa2a4f44294a21fc43a8a7f4da234ae9ffc748
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 EBADF
351 .I pathname
352 is relative and
353 .I dirfd
354 is not a valid file descriptor.
356 .B EFAULT
357 .IR handle
358 points outside your accessible address space.
360 .B EINVAL
361 .I handle\->handle_bytes
362 is greater than
363 .BR MAX_HANDLE_SZ
364 or is equal to zero.
366 .B ELOOP
367 .I handle
368 refers to a symbolic link, but
369 .B O_PATH
370 was not specified in
371 .IR flags .
373 .B EPERM
374 The caller does not have the
375 .BR CAP_DAC_READ_SEARCH
376 capability.
378 .B ESTALE
379 The specified
380 .I handle
381 is not valid.
382 This error will occur if, for example, the file has been deleted.
383 .SH VERSIONS
384 These system calls first appeared in Linux 2.6.39.
385 Library support is provided in glibc since version 2.14.
386 .SH CONFORMING TO
387 These system calls are nonstandard Linux extensions.
389 FreeBSD has a broadly similar pair of system calls in the form of
390 .BR getfh ()
392 .BR openfh ().
393 .SH NOTES
394 A file handle can be generated in one process using
395 .BR name_to_handle_at ()
396 and later used in a different process that calls
397 .BR open_by_handle_at ().
399 Some filesystem don't support the translation of pathnames to
400 file handles, for example,
401 .IR /proc ,
402 .IR /sys ,
403 and various network filesystems.
405 A file handle may become invalid ("stale") if a file is deleted,
406 or for other filesystem-specific reasons.
407 Invalid handles are notified by an
408 .B ESTALE
409 error from
410 .BR open_by_handle_at ().
412 These system calls are designed for use by user-space file servers.
413 For example, a user-space NFS server might generate a file handle
414 and pass it to an NFS client.
415 Later, when the client wants to open the file,
416 it could pass the handle back to the server.
417 .\" https://lwn.net/Articles/375888/
418 .\"     "Open by handle" - Jonathan Corbet, 2010-02-23
419 This sort of functionality allows a user-space file server to operate in
420 a stateless fashion with respect to the files it serves.
423 .I pathname
424 refers to a symbolic link and
425 .IR flags
426 does not specify
427 .BR AT_SYMLINK_FOLLOW ,
428 then
429 .BR name_to_handle_at ()
430 returns a handle for the link (rather than the file to which it refers).
431 .\" commit bcda76524cd1fa32af748536f27f674a13e56700
432 The process receiving the handle can later perform operations
433 on the symbolic link by converting the handle to a file descriptor using
434 .BR open_by_handle_at ()
435 with the
436 .BR O_PATH
437 flag, and then passing the file descriptor as the
438 .IR dirfd
439 argument in system calls such as
440 .BR readlinkat (2)
442 .BR fchownat (2).
443 .SS Obtaining a persistent filesystem ID
444 The mount IDs in
445 .IR /proc/self/mountinfo
446 can be reused as filesystems are unmounted and mounted.
447 Therefore, the mount ID returned by
448 .BR name_to_handle_at ()
450 .IR *mount_id )
451 should not be treated as a persistent identifier
452 for the corresponding mounted filesystem.
453 However, an application can use the information in the
454 .I mountinfo
455 record that corresponds to the mount ID
456 to derive a persistent identifier.
458 For example, one can use the device name in the fifth field of the
459 .I mountinfo
460 record to search for the corresponding device UUID via the symbolic links in
461 .IR /dev/disks/by\-uuid .
462 (A more comfortable way of obtaining the UUID is to use the
463 .\" e.g., http://stackoverflow.com/questions/6748429/using-libblkid-to-find-uuid-of-a-partition
464 .BR libblkid (3)
465 library.)
466 That process can then be reversed,
467 using the UUID to look up the device name,
468 and then obtaining the corresponding mount point,
469 in order to produce the
470 .IR mount_fd
471 argument used by
472 .BR open_by_handle_at ().
473 .SH EXAMPLES
474 The two programs below demonstrate the use of
475 .BR name_to_handle_at ()
477 .BR open_by_handle_at ().
478 The first program
479 .RI ( t_name_to_handle_at.c )
480 uses
481 .BR name_to_handle_at ()
482 to obtain the file handle and mount ID
483 for the file specified in its command-line argument;
484 the handle and mount ID are written to standard output.
486 The second program
487 .RI ( t_open_by_handle_at.c )
488 reads a mount ID and file handle from standard input.
489 The program then employs
490 .BR open_by_handle_at ()
491 to open the file using that handle.
492 If an optional command-line argument is supplied, then the
493 .IR mount_fd
494 argument for
495 .BR open_by_handle_at ()
496 is obtained by opening the directory named in that argument.
497 Otherwise,
498 .IR mount_fd
499 is obtained by scanning
500 .IR /proc/self/mountinfo
501 to find a record whose mount ID matches the mount ID
502 read from standard input,
503 and the mount directory specified in that record is opened.
504 (These programs do not deal with the fact that mount IDs are not persistent.)
506 The following shell session demonstrates the use of these two programs:
508 .in +4n
510 $ \fBecho \(aqCan you please think about it?\(aq > cecilia.txt\fP
511 $ \fB./t_name_to_handle_at cecilia.txt > fh\fP
512 $ \fB./t_open_by_handle_at < fh\fP
513 open_by_handle_at: Operation not permitted
514 $ \fBsudo ./t_open_by_handle_at < fh\fP      # Need CAP_SYS_ADMIN
515 Read 31 bytes
516 $ \fBrm cecilia.txt\fP
520 Now we delete and (quickly) re-create the file so that
521 it has the same content and (by chance) the same inode.
522 Nevertheless,
523 .BR open_by_handle_at ()
524 .\" Christoph Hellwig: That's why the file handles contain a generation
525 .\" counter that gets incremented in this case.
526 recognizes that the original file referred to by the file handle
527 no longer exists.
529 .in +4n
531 $ \fBstat \-\-printf="%i\en" cecilia.txt\fP     # Display inode number
532 4072121
533 $ \fBrm cecilia.txt\fP
534 $ \fBecho \(aqCan you please think about it?\(aq > cecilia.txt\fP
535 $ \fBstat \-\-printf="%i\en" cecilia.txt\fP     # Check inode number
536 4072121
537 $ \fBsudo ./t_open_by_handle_at < fh\fP
538 open_by_handle_at: Stale NFS file handle
541 .SS Program source: t_name_to_handle_at.c
544 #define _GNU_SOURCE
545 #include <sys/types.h>
546 #include <sys/stat.h>
547 #include <fcntl.h>
548 #include <stdio.h>
549 #include <stdlib.h>
550 #include <unistd.h>
551 #include <errno.h>
552 #include <string.h>
554 #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \e
555                         } while (0)
558 main(int argc, char *argv[])
560     struct file_handle *fhp;
561     int mount_id, fhsize, flags, dirfd;
562     char *pathname;
564     if (argc != 2) {
565         fprintf(stderr, "Usage: %s pathname\en", argv[0]);
566         exit(EXIT_FAILURE);
567     }
569     pathname = argv[1];
571     /* Allocate file_handle structure. */
573     fhsize = sizeof(*fhp);
574     fhp = malloc(fhsize);
575     if (fhp == NULL)
576         errExit("malloc");
578     /* Make an initial call to name_to_handle_at() to discover
579        the size required for file handle. */
581     dirfd = AT_FDCWD;           /* For name_to_handle_at() calls */
582     flags = 0;                  /* For name_to_handle_at() calls */
583     fhp\->handle_bytes = 0;
584     if (name_to_handle_at(dirfd, pathname, fhp,
585                 &mount_id, flags) != \-1 || errno != EOVERFLOW) {
586         fprintf(stderr, "Unexpected result from name_to_handle_at()\en");
587         exit(EXIT_FAILURE);
588     }
590     /* Reallocate file_handle structure with correct size. */
592     fhsize = sizeof(*fhp) + fhp\->handle_bytes;
593     fhp = realloc(fhp, fhsize);         /* Copies fhp\->handle_bytes */
594     if (fhp == NULL)
595         errExit("realloc");
597     /* Get file handle from pathname supplied on command line. */
599     if (name_to_handle_at(dirfd, pathname, fhp, &mount_id, flags) == \-1)
600         errExit("name_to_handle_at");
602     /* Write mount ID, file handle size, and file handle to stdout,
603        for later reuse by t_open_by_handle_at.c. */
605     printf("%d\en", mount_id);
606     printf("%u %d   ", fhp\->handle_bytes, fhp\->handle_type);
607     for (int j = 0; j < fhp\->handle_bytes; j++)
608         printf(" %02x", fhp\->f_handle[j]);
609     printf("\en");
611     exit(EXIT_SUCCESS);
614 .SS Program source: t_open_by_handle_at.c
617 #define _GNU_SOURCE
618 #include <sys/types.h>
619 #include <sys/stat.h>
620 #include <fcntl.h>
621 #include <limits.h>
622 #include <stdio.h>
623 #include <stdlib.h>
624 #include <unistd.h>
625 #include <string.h>
627 #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \e
628                         } while (0)
630 /* Scan /proc/self/mountinfo to find the line whose mount ID matches
631    \(aqmount_id\(aq. (An easier way to do this is to install and use the
632    \(aqlibmount\(aq library provided by the \(aqutil\-linux\(aq project.)
633    Open the corresponding mount path and return the resulting file
634    descriptor. */
636 static int
637 open_mount_path_by_id(int mount_id)
639     char *linep;
640     size_t lsize;
641     char mount_path[PATH_MAX];
642     int mi_mount_id, found;
643     ssize_t nread;
644     FILE *fp;
646     fp = fopen("/proc/self/mountinfo", "r");
647     if (fp == NULL)
648         errExit("fopen");
650     found = 0;
651     linep = NULL;
652     while (!found) {
653         nread = getline(&linep, &lsize, fp);
654         if (nread == \-1)
655             break;
657         nread = sscanf(linep, "%d %*d %*s %*s %s",
658                        &mi_mount_id, mount_path);
659         if (nread != 2) {
660             fprintf(stderr, "Bad sscanf()\en");
661             exit(EXIT_FAILURE);
662         }
664         if (mi_mount_id == mount_id)
665             found = 1;
666     }
667     free(linep);
669     fclose(fp);
671     if (!found) {
672         fprintf(stderr, "Could not find mount point\en");
673         exit(EXIT_FAILURE);
674     }
676     return open(mount_path, O_RDONLY);
680 main(int argc, char *argv[])
682     struct file_handle *fhp;
683     int mount_id, fd, mount_fd, handle_bytes;
684     ssize_t nread;
685     char buf[1000];
686 #define LINE_SIZE 100
687     char line1[LINE_SIZE], line2[LINE_SIZE];
688     char *nextp;
690     if ((argc > 1 && strcmp(argv[1], "\-\-help") == 0) || argc > 2) {
691         fprintf(stderr, "Usage: %s [mount\-path]\en", argv[0]);
692         exit(EXIT_FAILURE);
693     }
695     /* Standard input contains mount ID and file handle information:
697          Line 1: <mount_id>
698          Line 2: <handle_bytes> <handle_type>   <bytes of handle in hex>
699     */
701     if ((fgets(line1, sizeof(line1), stdin) == NULL) ||
702            (fgets(line2, sizeof(line2), stdin) == NULL)) {
703         fprintf(stderr, "Missing mount_id / file handle\en");
704         exit(EXIT_FAILURE);
705     }
707     mount_id = atoi(line1);
709     handle_bytes = strtoul(line2, &nextp, 0);
711     /* Given handle_bytes, we can now allocate file_handle structure. */
713     fhp = malloc(sizeof(*fhp) + handle_bytes);
714     if (fhp == NULL)
715         errExit("malloc");
717     fhp\->handle_bytes = handle_bytes;
719     fhp\->handle_type = strtoul(nextp, &nextp, 0);
721     for (int j = 0; j < fhp\->handle_bytes; j++)
722         fhp\->f_handle[j] = strtoul(nextp, &nextp, 16);
724     /* Obtain file descriptor for mount point, either by opening
725        the pathname specified on the command line, or by scanning
726        /proc/self/mounts to find a mount that matches the \(aqmount_id\(aq
727        that we received from stdin. */
729     if (argc > 1)
730         mount_fd = open(argv[1], O_RDONLY);
731     else
732         mount_fd = open_mount_path_by_id(mount_id);
734     if (mount_fd == \-1)
735         errExit("opening mount fd");
737     /* Open file using handle and mount point. */
739     fd = open_by_handle_at(mount_fd, fhp, O_RDONLY);
740     if (fd == \-1)
741         errExit("open_by_handle_at");
743     /* Try reading a few bytes from the file. */
745     nread = read(fd, buf, sizeof(buf));
746     if (nread == \-1)
747         errExit("read");
749     printf("Read %zd bytes\en", nread);
751     exit(EXIT_SUCCESS);
754 .SH SEE ALSO
755 .BR open (2),
756 .BR libblkid (3),
757 .BR blkid (8),
758 .BR findfs (8),
759 .BR mount (8)
762 .I libblkid
764 .I libmount
765 documentation in the latest
766 .I util\-linux
767 release at
768 .UR https://www.kernel.org/pub/linux/utils/util\-linux/