title: kexec_load(2)

summary: load a new kernel for later execution

text:
# kexec_load(2)

## NAME
kexec_load, kexec_file_load - load a new kernel for later execution

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/kexec.h>      /* Definition of KEXEC_* constants */
#include <sys/syscall.h>      /* Definition of SYS_* constants */
#include <unistd.h>
```

```
long syscall(SYS_kexec_load, unsigned long entry,
             unsigned long nr_segments, struct kexec_segment *segments,
             unsigned long flags);
long syscall(SYS_kexec_file_load, int kernel_fd, int initrd_fd,
             unsigned long cmdline_len, const char *cmdline,
             unsigned long flags);
```

Note: glibc provides no wrappers for these system calls, necessitating the use of syscall(2).

## DESCRIPTION
The kexec_load() system call loads a new kernel that can be executed later by reboot(2).

The flags argument is a bit mask that controls the operation of the call. The following values can be specified in flags:

KEXEC_ON_CRASH (since Linux 2.6.13)

Execute the new kernel automatically on a system crash. This "crash kernel" is loaded into an area of reserved memory that is determined at boot time using the crashkernel kernel command-line parameter. The location of this reserved memory is exported to user space via the /proc/iomem file, in an entry labeled "Crash kernel". A user-space application can parse this file and prepare a list of segments (see below) that specify this reserved memory as destination. If this flag is specified, the kernel checks that the target segments specified in segments fall within the reserved region.

KEXEC_PRESERVE_CONTEXT (since Linux 2.6.27)

Preserve the system hardware and software states before executing the new kernel. This could be used for system suspend. This flag is available only if the kernel was configured with CONFIG_KEXEC_JUMP, and is effective only if nr_segments is greater than 0.

The high-order bits (corresponding to the mask 0xffff0000) of flags contain the architecture of the to-be-executed kernel. Specify (OR) the constant KEXEC_ARCH_DEFAULT to use the current architecture, or one of the following architecture constants KEXEC_ARCH_386, KEXEC_ARCH_68K, KEXEC_ARCH_X86_64, KEXEC_ARCH_PPC, KEXEC_ARCH_PPC64, KEXEC_ARCH_IA_64, KEXEC_ARCH_ARM, KEXEC_ARCH_S390, KEXEC_ARCH_SH, KEXEC_ARCH_MIPS, and KEXEC_ARCH_MIPS_LE. The architecture must be executable on the CPU of the system.

The entry argument is the physical entry address in the kernel image. The nr_segments argument is the number of segments pointed to by the segments pointer; the kernel imposes an (arbitrary) limit of 16 on the number of segments. The segments argument is an array of kexec_segment structures which define the kernel layout:

```
struct kexec_segment {

    void   *buf;        /* Buffer in user space */

    size_t  bufsz;      /* Buffer length in user space */

    void   *mem;        /* Physical address of kernel */

    size_t  memsz;      /* Physical address length */
};
```

The kernel image defined by segments is copied from the calling process into the kernel either in regular memory or in reserved memory (if KEXEC_ON_CRASH is set). The kernel first performs various sanity checks on the information passed in segments. If these checks pass, the kernel copies the segment data to kernel memory. Each segment specified in segments is copied as follows:

•

buf and bufsz identify a memory region in the caller's virtual address space that is the source of the copy. The value in bufsz may not exceed the value in the memsz field.

•

mem and memsz specify a physical address range that is the target of the copy. The values specified in both fields must be multiples of the system page size.

•

bufsz bytes are copied from the source buffer to the target kernel buffer. If bufsz is less than memsz, then the excess bytes in the kernel buffer are zeroed out.

In case of a normal kexec (i.e., the KEXEC_ON_CRASH flag is not set), the segment data is loaded in any available memory and is moved to the final destination at kexec reboot time (e.g., when the kexec(8) command is executed with the -e option).

In case of kexec on panic (i.e., the KEXEC_ON_CRASH flag is set), the segment data is loaded to reserved memory at the time of the call, and, after a crash, the kexec mechanism simply passes control to that kernel.

The kexec_load() system call is available only if the kernel was configured with CONFIG_KEXEC.

### kexec_file_load()
The kexec_file_load() system call is similar to kexec_load(), but it takes a different set of arguments. It reads the kernel to be loaded from the file referred to by the file descriptor kernel_fd, and the initrd (initial RAM disk) to be loaded from file referred to by the file descriptor initrd_fd. The cmdline argument is a pointer to a buffer containing the command line for the new kernel. The cmdline_len argument specifies size of the buffer. The last byte in the buffer must be a null byte ('\0').

The flags argument is a bit mask which modifies the behavior of the call. The following values can be specified in flags:

KEXEC_FILE_UNLOAD

Unload the currently loaded kernel.

KEXEC_FILE_ON_CRASH

Load the new kernel in the memory region reserved for the crash kernel (as for KEXEC_ON_CRASH). This kernel is booted if the currently running kernel crashes.

KEXEC_FILE_NO_INITRAMFS

Loading initrd/initramfs is optional. Specify this flag if no initramfs is being loaded. If this flag is set, the value passed in initrd_fd is ignored.

The kexec_file_load() system call was added to provide support for systems where "kexec" loading should be restricted to only kernels that are signed. This system call is available only if the kernel was configured with CONFIG_KEXEC_FILE.

## RETURN VALUE
On success, these system calls returns 0. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EADDRNOTAVAIL

The KEXEC_ON_CRASH flags was specified, but the region specified by the mem and memsz fields of one of the segments entries lies outside the range of memory reserved for the crash kernel.

EADDRNOTAVAIL

The value in a mem or memsz field in one of the segments entries is not a multiple of the system page size.

EBADF

kernel_fd or initrd_fd is not a valid file descriptor.

EBUSY

Another crash kernel is already being loaded or a crash kernel is already in use.

EINVAL

flags is invalid.

EINVAL

The value of a bufsz field in one of the segments entries exceeds the value in the corresponding memsz field.

EINVAL

nr_segments exceeds KEXEC_SEGMENT_MAX (16).

EINVAL

Two or more of the kernel target buffers overlap.

EINVAL

The value in cmdline[cmdline_len-1] is not '\0'.

EINVAL

The file referred to by kernel_fd or initrd_fd is empty (length zero).

ENOEXEC

kernel_fd does not refer to an open file, or the kernel can't load this file. Currently, the file must be a bzImage and contain an x86 kernel that is loadable above 4 GiB in memory (see the kernel source file Documentation/x86/boot.txt).

ENOMEM

Could not allocate memory.

EPERM

The caller does not have the CAP_SYS_BOOT capability.

## STANDARDS
Linux.

## HISTORY
kexec_load()

Linux 2.6.13.

kexec_file_load()

Linux 3.17.

## SEE ALSO
reboot(2), syscall(2), kexec(8)

The kernel source files Documentation/kdump/kdump.txt and Documentation/admin-guide/kernel-parameters.txt


keyctl

package: man-pages

title: keyctl(2)

text:
# keyctl(2)

## NAME
keyctl - manipulate the kernel's key management facility

## LIBRARY
Standard C library (libc, -lc)

Alternatively, Linux Key Management Utilities (libkeyutils, -lkeyutils); see VERSIONS.

## SYNOPSIS

```
#include <linux/keyctl.h>     /* Definition of KEY* constants */
#include <sys/syscall.h>      /* Definition of SYS_* constants */
#include <unistd.h>
```

```
long syscall(SYS_keyctl, int operation, unsigned long arg2,
             unsigned long arg3, unsigned long arg4,
             unsigned long arg5);
```

Note: glibc provides no wrapper for keyctl(), necessitating the use of syscall(2).

## DESCRIPTION
keyctl() allows user-space programs to perform key manipulation.

The operation performed by keyctl() is determined by the value of the operation argument. Each of these operations is wrapped by the libkeyutils library (provided by the keyutils package) into individual functions (noted below) to permit the compiler to check types.

The permitted values for operation are:

KEYCTL_GET_KEYRING_ID (since Linux 2.6.10)

Map a special key ID to a real key ID for this process.

This operation looks up the special key whose ID is provided in arg2 (cast to key_serial_t). If the special key is found, the ID of the corresponding real key is returned as the function result. The following values may be specified in arg2:

KEY_SPEC_THREAD_KEYRING

This specifies the calling thread's thread-specific keyring. See thread-keyring(7).

KEY_SPEC_PROCESS_KEYRING

This specifies the caller's process-specific keyring. See process-keyring(7).

KEY_SPEC_SESSION_KEYRING

This specifies the caller's session-specific keyring. See session-keyring(7).

KEY_SPEC_USER_KEYRING

This specifies the caller's UID-specific keyring. See user-keyring(7).

KEY_SPEC_USER_SESSION_KEYRING

This specifies the caller's UID-session keyring. See user-session-keyring(7).

KEY_SPEC_REQKEY_AUTH_KEY (since Linux 2.6.16)

This specifies the authorization key created by request_key(2) and passed to the process it spawns to generate a key. This key is available only in a request-key(8)-style program that was passed an authorization key by the kernel and ceases to be available once the requested key has been instantiated; see request_key(2).

KEY_SPEC_REQUESTOR_KEYRING (since Linux 2.6.29)

This specifies the key ID for the request_key(2) destination keyring. This keyring is available only in a request-key(8)-style program that was passed an authorization key by the kernel and ceases to be available once the requested key has been instantiated; see request_key(2).

The behavior if the key specified in arg2 does not exist depends on the value of arg3 (cast to int). If arg3 contains a nonzero value, then—if it is appropriate to do so (e.g., when looking up the user, user-session, or session key)—a new key is created and its real key ID returned as the function result. Otherwise, the operation fails with the error ENOKEY.

If a valid key ID is specified in arg2, and the key exists, then this operation simply returns the key ID. If the key does not exist, the call fails with error ENOKEY.

The caller must have search permission on a keyring in order for it to be found.

The arguments arg4 and arg5 are ignored.

This operation is exposed by libkeyutils via the function keyctl_get_keyring_ID(3).

KEYCTL_JOIN_SESSION_KEYRING (since Linux 2.6.10)

Replace the session keyring this process subscribes to with a new session keyring.

If arg2 is NULL, an anonymous keyring with the description "_ses" is created and the process is subscribed to that keyring as its session keyring, displacing the previous session keyring.

Otherwise, arg2 (cast to char *) is treated as the description (name) of a keyring, and the behavior is as follows:

•

If a keyring with a matching description exists, the process will attempt to subscribe to that keyring as its session keyring if possible; if that is not possible, an error is returned. In order to subscribe to the keyring, the caller must have search permission on the keyring.

•

If a keyring with a matching description does not exist, then a new keyring with the specified description is created, and the process is subscribed to that keyring as its session keyring.

The arguments arg3, arg4, and arg5 are ignored.

This operation is exposed by libkeyutils via the function keyctl_join_session_keyring(3).

KEYCTL_UPDATE (since Linux 2.6.10)

Update a key's data payload.

The arg2 argument (cast to key_serial_t) specifies the ID of the key to be updated. The arg3 argument (cast to void *) points to the new payload and arg4 (cast to size_t) contains the new payload size in bytes.

The caller must have write permission on the key specified and the key type must support updating.

A negatively instantiated key (see the description of KEYCTL_REJECT) can be positively instantiated with this operation.

The arg5 argument is ignored.

This operation is exposed by libkeyutils via the function keyctl_update(3).

KEYCTL_REVOKE (since Linux 2.6.10)

Revoke the key with the ID provided in arg2 (cast to key_serial_t). The key is scheduled for garbage collection; it will no longer be findable, and will be unavailable for further operations. Further attempts to use the key will fail with the error EKEYREVOKED.

The caller must have write or setattr permission on the key.

The arguments arg3, arg4, and arg5 are ignored.

This operation is exposed by libkeyutils via the function keyctl_revoke(3).

KEYCTL_CHOWN (since Linux 2.6.10)

Change the ownership (user and group ID) of a key.

The arg2 argument (cast to key_serial_t) contains the key ID. The arg3 argument (cast to uid_t) contains the new user ID (or -1 in case the user ID shouldn't be changed). The arg4 argument (cast to gid_t) contains the new group ID (or -1 in case the group ID shouldn't be changed).

The key must grant the caller setattr permission.

For the UID to be changed, or for the GID to be changed to a group the caller is not a member of, the caller must have the CAP_SYS_ADMIN capability (see capabilities(7)).

If the UID is to be changed, the new user must have sufficient quota to accept the key. The quota deduction will be removed from the old user to the new user should the UID be changed.

The arg5 argument is ignored.

This operation is exposed by libkeyutils via the function keyctl_chown(3).

KEYCTL_SETPERM (since Linux 2.6.10)

Change the permissions of the key with the ID provided in the arg2 argument (cast to key_serial_t) to the permissions provided in the arg3 argument (cast to key_perm_t).

If the caller doesn't have the CAP_SYS_ADMIN capability, it can change permissions only for the keys it owns. (More precisely: the caller's filesystem UID must match the UID of the key.)

The key must grant setattr permission to the caller regardless of the caller's capabilities.

The permissions in arg3 specify masks of available operations for each of the following user categories:

possessor (since Linux 2.6.14)

This is the permission granted to a process that possesses the key (has it attached searchably to one of the process's keyrings); see keyrings(7).

user

This is the permission granted to a process whose filesystem UID matches the UID of the key.

group

This is the permission granted to a process whose filesystem GID or any of its supplementary GIDs matches the GID of the key.

other

This is the permission granted to other processes that do not match the user and group categories.

The user, group, and other categories are exclusive: if a process matches the user category, it will not receive permissions granted in the group category; if a process matches the user or group category, then it will not receive permissions granted in the other category.

The possessor category grants permissions that are cumulative with the grants from the user, group, or other category.

Each permission mask is eight bits in size, with only six bits currently used. The available permissions are:

view

This permission allows reading attributes of a key.

This permission is required for the KEYCTL_DESCRIBE operation.

The permission bits for each category are KEY_POS_VIEW, KEY_USR_VIEW, KEY_GRP_VIEW, and KEY_OTH_VIEW.

read

This permission allows reading a key's payload.

This permission is required for the KEYCTL_READ operation.

The permission bits for each category are KEY_POS_READ, KEY_USR_READ, KEY_GRP_READ, and KEY_OTH_READ.

write

This permission allows update or instantiation of a key's payload. For a keyring, it allows keys to be linked and unlinked from the keyring,

This permission is required for the KEYCTL_UPDATE, KEYCTL_REVOKE, KEYCTL_CLEAR, KEYCTL_LINK, and KEYCTL_UNLINK operations.

The permission bits for each category are KEY_POS_WRITE, KEY_USR_WRITE, KEY_GRP_WRITE, and KEY_OTH_WRITE.

search

This permission allows keyrings to be searched and keys to be found. Searches can recurse only into nested keyrings that have search permission set.

This permission is required for the KEYCTL_GET_KEYRING_ID, KEYCTL_JOIN_SESSION_KEYRING, KEYCTL_SEARCH, and KEYCTL_INVALIDATE operations.

The permission bits for each category are KEY_POS_SEARCH, KEY_USR_SEARCH, KEY_GRP_SEARCH, and KEY_OTH_SEARCH.

link

This permission allows a key or keyring to be linked to.

This permission is required for the KEYCTL_LINK and KEYCTL_SESSION_TO_PARENT operations.

The permission bits for each category are KEY_POS_LINK, KEY_USR_LINK, KEY_GRP_LINK, and KEY_OTH_LINK.

setattr (since Linux 2.6.15).

This permission allows a key's UID, GID, and permissions mask to be changed.

This permission is required for the KEYCTL_REVOKE, KEYCTL_CHOWN, and KEYCTL_SETPERM operations.

The permission bits for each category are KEY_POS_SETATTR, KEY_USR_SETATTR, KEY_GRP_SETATTR, and KEY_OTH_SETATTR.

As a convenience, the following macros are defined as masks for all of the permission bits in each of the user categories: KEY_POS_ALL, KEY_USR_ALL, KEY_GRP_ALL, and KEY_OTH_ALL.

The arg4 and arg5 arguments are ignored.

This operation is exposed by libkeyutils via the function keyctl_setperm(3).

KEYCTL_DESCRIBE (since Linux 2.6.10)

Obtain a string describing the attributes of a specified key.

The ID of the key to be described is specified in arg2 (cast to key_serial_t). The descriptive string is returned in the buffer pointed to by arg3 (cast to char *); arg4 (cast to size_t) specifies the size of that buffer in bytes.

The key must grant the caller view permission.

The returned string is null-terminated and contains the following information about the key:

type;uid;gid;perm;description

In the above, type and description are strings, uid and gid are decimal strings, and perm is a hexadecimal permissions mask. The descriptive string is written with the following format:

```
%s;%d;%d;%08x;%s

```

Note: the intention is that the descriptive string should be extensible in future kernel versions. In particular, the description field will not contain semicolons; it should be parsed by working backwards from the end of the string to find the last semicolon. This allows future semicolon-delimited fields to be inserted in the descriptive string in the future.

Writing to the buffer is attempted only when arg3 is non-NULL and the specified buffer size is large enough to accept the descriptive string (including the terminating null byte). In order to determine whether the buffer size was too small, check to see if the return value of the operation is greater than arg4.

The arg5 argument is ignored.

This operation is exposed by libkeyutils via the function keyctl_describe(3).

KEYCTL_CLEAR

Clear the contents of (i.e., unlink all keys from) a keyring.

The ID of the key (which must be of keyring type) is provided in arg2 (cast to key_serial_t).

The caller must have write permission on the keyring.

The arguments arg3, arg4, and arg5 are ignored.

This operation is exposed by libkeyutils via the function keyctl_clear(3).

KEYCTL_LINK (since Linux 2.6.10)

Create a link from a keyring to a key.

The key to be linked is specified in arg2 (cast to key_serial_t); the keyring is specified in arg3 (cast to key_serial_t).

If a key with the same type and description is already linked in the keyring, then that key is displaced from the keyring.

Before creating the link, the kernel checks the nesting of the keyrings and returns appropriate errors if the link would produce a cycle or if the nesting of keyrings would be too deep (The limit on the nesting of keyrings is determined by the kernel constant KEYRING_SEARCH_MAX_DEPTH, defined with the value 6, and is necessary to prevent overflows on the kernel stack when recursively searching keyrings).

The caller must have link permission on the key being added and write permission on the keyring.

The arguments arg4 and arg5 are ignored.

This operation is exposed by libkeyutils via the function keyctl_link(3).

KEYCTL_UNLINK (since Linux 2.6.10)

Unlink a key from a keyring.

The ID of the key to be unlinked is specified in arg2 (cast to key_serial_t); the ID of the keyring from which it is to be unlinked is specified in arg3 (cast to key_serial_t).

If the key is not currently linked into the keyring, an error results.

The caller must have write permission on the keyring from which the key is being removed.

If the last link to a key is removed, then that key will be scheduled for destruction.

The arguments arg4 and arg5 are ignored.

This operation is exposed by libkeyutils via the function keyctl_unlink(3).

KEYCTL_SEARCH (since Linux 2.6.10)

Search for a key in a keyring tree, returning its ID and optionally linking it to a specified keyring.

The tree to be searched is specified by passing the ID of the head keyring in arg2 (cast to key_serial_t). The search is performed breadth-first and recursively.

The arg3 and arg4 arguments specify the key to be searched for: arg3 (cast as char *) contains the key type (a null-terminated character string up to 32 bytes in size, including the terminating null byte), and arg4 (cast as char *) contains the description of the key (a null-terminated character string up to 4096 bytes in size, including the terminating null byte).

The source keyring must grant search permission to the caller. When performing the recursive search, only keyrings that grant the caller search permission will be searched. Only keys with for which the caller has search permission can be found.

If the key is found, its ID is returned as the function result.

If the key is found and arg5 (cast to key_serial_t) is nonzero, then, subject to the same constraints and rules as KEYCTL_LINK, the key is linked into the keyring whose ID is specified in arg5. If the destination keyring specified in arg5 already contains a link to a key that has the same type and description, then that link will be displaced by a link to the key found by this operation.

Instead of valid existing keyring IDs, the source (arg2) and destination (arg5) keyrings can be one of the special keyring IDs listed under KEYCTL_GET_KEYRING_ID.

This operation is exposed by libkeyutils via the function keyctl_search(3).

KEYCTL_READ (since Linux 2.6.10)

Read the payload data of a key.

The ID of the key whose payload is to be read is specified in arg2 (cast to key_serial_t). This can be the ID of an existing key, or any of the special key IDs listed for KEYCTL_GET_KEYRING_ID.

The payload is placed in the buffer pointed by arg3 (cast to char *); the size of that buffer must be specified in arg4 (cast to size_t).

The returned data will be processed for presentation according to the key type. For example, a keyring will return an array of key_serial_t entries representing the IDs of all the keys that are linked to it. The user key type will return its data as is. If a key type does not implement this function, the operation fails with the error EOPNOTSUPP.

If arg3 is not NULL, as much of the payload data as will fit is copied into the buffer. On a successful return, the return value is always the total size of the payload data. To determine whether the buffer was of sufficient size, check to see that the return value is less than or equal to the value supplied in arg4.

The key must either grant the caller read permission, or grant the caller search permission when searched for from the process keyrings (i.e., the key is possessed).

The arg5 argument is ignored.

This operation is exposed by libkeyutils via the function keyctl_read(3).

KEYCTL_INSTANTIATE (since Linux 2.6.10)

(Positively) instantiate an uninstantiated key with a specified payload.

The ID of the key to be instantiated is provided in arg2 (cast to key_serial_t).

The key payload is specified in the buffer pointed to by arg3 (cast to void *); the size of that buffer is specified in arg4 (cast to size_t).

The payload may be a NULL pointer and the buffer size may be 0 if this is supported by the key type (e.g., it is a keyring).

The operation may be fail if the payload data is in the wrong format or is otherwise invalid.

If arg5 (cast to key_serial_t) is nonzero, then, subject to the same constraints and rules as KEYCTL_LINK, the instantiated key is linked into the keyring whose ID specified in arg5.

The caller must have the appropriate authorization key, and once the uninstantiated key has been instantiated, the authorization key is revoked. In other words, this operation is available only from a request-key(8)-style program. See request_key(2) for an explanation of uninstantiated keys and key instantiation.

This operation is exposed by libkeyutils via the function keyctl_instantiate(3).

KEYCTL_NEGATE (since Linux 2.6.10)

Negatively instantiate an uninstantiated key.

This operation is equivalent to the call:

```
keyctl(KEYCTL_REJECT, arg2, arg3, ENOKEY, arg4);

```

The arg5 argument is ignored.

This operation is exposed by libkeyutils via the function keyctl_negate(3).

KEYCTL_SET_REQKEY_KEYRING (since Linux 2.6.13)

Set the default keyring to which implicitly requested keys will be linked for this thread, and return the previous setting. Implicit key requests are those made by internal kernel components, such as can occur when, for example, opening files on an AFS or NFS filesystem. Setting the default keyring also has an effect when requesting a key from user space; see request_key(2) for details.

The arg2 argument (cast to int) should contain one of the following values, to specify the new default keyring:

KEY_REQKEY_DEFL_NO_CHANGE

Don't change the default keyring. This can be used to discover the current default keyring (without changing it).

KEY_REQKEY_DEFL_DEFAULT

This selects the default behaviour, which is to use the thread-specific keyring if there is one, otherwise the process-specific keyring if there is one, otherwise the session keyring if there is one, otherwise the UID-specific session keyring, otherwise the user-specific keyring.

KEY_REQKEY_DEFL_THREAD_KEYRING

Use the thread-specific keyring (thread-keyring(7)) as the new default keyring.

KEY_REQKEY_DEFL_PROCESS_KEYRING

Use the process-specific keyring (process-keyring(7)) as the new default keyring.

KEY_REQKEY_DEFL_SESSION_KEYRING

Use the session-specific keyring (session-keyring(7)) as the new default keyring.

KEY_REQKEY_DEFL_USER_KEYRING

Use the UID-specific keyring (user-keyring(7)) as the new default keyring.

KEY_REQKEY_DEFL_USER_SESSION_KEYRING

Use the UID-specific session keyring (user-session-keyring(7)) as the new default keyring.

KEY_REQKEY_DEFL_REQUESTOR_KEYRING (since Linux 2.6.29)

Use the requestor keyring.

All other values are invalid.

The arguments arg3, arg4, and arg5 are ignored.

The setting controlled by this operation is inherited by the child of fork(2) and preserved across execve(2).

This operation is exposed by libkeyutils via the function keyctl_set_reqkey_keyring(3).

KEYCTL_SET_TIMEOUT (since Linux 2.6.16)

Set a timeout on a key.

The ID of the key is specified in arg2 (cast to key_serial_t). The timeout value, in seconds from the current time, is specified in arg3 (cast to unsigned int). The timeout is measured against the realtime clock.

Specifying the timeout value as 0 clears any existing timeout on the key.

The /proc/keys file displays the remaining time until each key will expire. (This is the only method of discovering the timeout on a key.)

The caller must either have the setattr permission on the key or hold an instantiation authorization token for the key (see request_key(2)).

The key and any links to the key will be automatically garbage collected after the timeout expires. Subsequent attempts to access the key will then fail with the error EKEYEXPIRED.

This operation cannot be used to set timeouts on revoked, expired, or negatively instantiated keys.

The arguments arg4 and arg5 are ignored.

This operation is exposed by libkeyutils via the function keyctl_set_timeout(3).

KEYCTL_ASSUME_AUTHORITY (since Linux 2.6.16)

Assume (or divest) the authority for the calling thread to instantiate a key.

The arg2 argument (cast to key_serial_t) specifies either a nonzero key ID to assume authority, or the value 0 to divest authority.

If arg2 is nonzero, then it specifies the ID of an uninstantiated key for which authority is to be assumed. That key can then be instantiated using one of KEYCTL_INSTANTIATE, KEYCTL_INSTANTIATE_IOV, KEYCTL_REJECT, or KEYCTL_NEGATE. Once the key has been instantiated, the thread is automatically divested of authority to instantiate the key.

Authority over a key can be assumed only if the calling thread has present in its keyrings the authorization key that is associated with the specified key. (In other words, the KEYCTL_ASSUME_AUTHORITY operation is available only from a request-key(8)-style program; see request_key(2) for an explanation of how this operation is used.) The caller must have search permission on the authorization key.

If the specified key has a matching authorization key, then the ID of that key is returned. The authorization key can be read (KEYCTL_READ) to obtain the callout information passed to request_key(2).

If the ID given in arg2 is 0, then the currently assumed authority is cleared (divested), and the value 0 is returned.

The KEYCTL_ASSUME_AUTHORITY mechanism allows a program such as request-key(8) to assume the necessary authority to instantiate a new uninstantiated key that was created as a consequence of a call to request_key(2). For further information, see request_key(2) and the kernel source file Documentation/security/keys-request-key.txt.

The arguments arg3, arg4, and arg5 are ignored.

This operation is exposed by libkeyutils via the function keyctl_assume_authority(3).

KEYCTL_GET_SECURITY (since Linux 2.6.26)

Get the LSM (Linux Security Module) security label of the specified key.

The ID of the key whose security label is to be fetched is specified in arg2 (cast to key_serial_t). The security label (terminated by a null byte) will be placed in the buffer pointed to by arg3 argument (cast to char *); the size of the buffer must be provided in arg4 (cast to size_t).

If arg3 is specified as NULL or the buffer size specified in arg4 is too small, the full size of the security label string (including the terminating null byte) is returned as the function result, and nothing is copied to the buffer.

The caller must have view permission on the specified key.

The returned security label string will be rendered in a form appropriate to the LSM in force. For example, with SELinux, it may look like:

```
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

```

If no LSM is currently in force, then an empty string is placed in the buffer.

The arg5 argument is ignored.

This operation is exposed by libkeyutils via the functions keyctl_get_security(3) and keyctl_get_security_alloc(3).

KEYCTL_SESSION_TO_PARENT (since Linux 2.6.32)

Replace the session keyring to which the parent of the calling process subscribes with the session keyring of the calling process.

The keyring will be replaced in the parent process at the point where the parent next transitions from kernel space to user space.

The keyring must exist and must grant the caller link permission. The parent process must be single-threaded and have the same effective ownership as this process and must not be set-user-ID or set-group-ID. The UID of the parent process's existing session keyring (f it has one), as well as the UID of the caller's session keyring much match the caller's effective UID.

The fact that it is the parent process that is affected by this operation allows a program such as the shell to start a child process that uses this operation to change the shell's session keyring. (This is what the keyctl(1) new_session command does.)

The arguments arg2, arg3, arg4, and arg5 are ignored.

This operation is exposed by libkeyutils via the function keyctl_session_to_parent(3).

KEYCTL_REJECT (since Linux 2.6.39)

Mark a key as negatively instantiated and set an expiration timer on the key. This operation provides a superset of the functionality of the earlier KEYCTL_NEGATE operation.

The ID of the key that is to be negatively instantiated is specified in arg2 (cast to key_serial_t). The arg3 (cast to unsigned int) argument specifies the lifetime of the key, in seconds. The arg4 argument (cast to unsigned int) specifies the error to be returned when a search hits this key; typically, this is one of EKEYREJECTED, EKEYREVOKED, or EKEYEXPIRED.

If arg5 (cast to key_serial_t) is nonzero, then, subject to the same constraints and rules as KEYCTL_LINK, the negatively instantiated key is linked into the keyring whose ID is specified in arg5.

The caller must have the appropriate authorization key. In other words, this operation is available only from a request-key(8)-style program. See request_key(2).

The caller must have the appropriate authorization key, and once the uninstantiated key has been instantiated, the authorization key is revoked. In other words, this operation is available only from a request-key(8)-style program. See request_key(2) for an explanation of uninstantiated keys and key instantiation.

This operation is exposed by libkeyutils via the function keyctl_reject(3).

KEYCTL_INSTANTIATE_IOV (since Linux 2.6.39)

Instantiate an uninstantiated key with a payload specified via a vector of buffers.

This operation is the same as KEYCTL_INSTANTIATE, but the payload data is specified as an array of iovec structures (see iovec(3type)).

The pointer to the payload vector is specified in arg3 (cast as const struct iovec *). The number of items in the vector is specified in arg4 (cast as unsigned int).

The arg2 (key ID) and arg5 (keyring ID) are interpreted as for KEYCTL_INSTANTIATE.

This operation is exposed by libkeyutils via the function keyctl_instantiate_iov(3).

KEYCTL_INVALIDATE (since Linux 3.5)

Mark a key as invalid.

The ID of the key to be invalidated is specified in arg2 (cast to key_serial_t).

To invalidate a key, the caller must have search permission on the key.

This operation marks the key as invalid and schedules immediate garbage collection. The garbage collector removes the invalidated key from all keyrings and deletes the key when its reference count reaches zero. After this operation, the key will be ignored by all searches, even if it is not yet deleted.

Keys that are marked invalid become invisible to normal key operations immediately, though they are still visible in /proc/keys (marked with an 'i' flag) until they are actually removed.

The arguments arg3, arg4, and arg5 are ignored.

This operation is exposed by libkeyutils via the function keyctl_invalidate(3).

KEYCTL_GET_PERSISTENT (since Linux 3.13)

Get the persistent keyring (persistent-keyring(7)) for a specified user and link it to a specified keyring.

The user ID is specified in arg2 (cast to uid_t). If the value -1 is specified, the caller's real user ID is used. The ID of the destination keyring is specified in arg3 (cast to key_serial_t).

The caller must have the CAP_SETUID capability in its user namespace in order to fetch the persistent keyring for a user ID that does not match either the real or effective user ID of the caller.

If the call is successful, a link to the persistent keyring is added to the keyring whose ID was specified in arg3.

The caller must have write permission on the keyring.

The persistent keyring will be created by the kernel if it does not yet exist.

Each time the KEYCTL_GET_PERSISTENT operation is performed, the persistent keyring will have its expiration timeout reset to the value in:

```
/proc/sys/kernel/keys/persistent_keyring_expiry

```

Should the timeout be reached, the persistent keyring will be removed and everything it pins can then be garbage collected.

Persistent keyrings were added in Linux 3.13.

The arguments arg4 and arg5 are ignored.

This operation is exposed by libkeyutils via the function keyctl_get_persistent(3).

KEYCTL_DH_COMPUTE (since Linux 4.7)

Compute a Diffie-Hellman shared secret or public key, optionally applying key derivation function (KDF) to the result.

The arg2 argument is a pointer to a set of parameters containing serial numbers for three "user" keys used in the Diffie-Hellman calculation, packaged in a structure of the following form:

```
struct keyctl_dh_params {

    int32_t private; /* The local private key */

    int32_t prime; /* The prime, known to both parties */

    int32_t base;  /* The base integer: either a shared

                      generator or the remote public key */
};

```

Each of the three keys specified in this structure must grant the caller read permission. The payloads of these keys are used to calculate the Diffie-Hellman result as:

```
base ^ private mod prime

```

If the base is the shared generator, the result is the local public key. If the base is the remote public key, the result is the shared secret.

The arg3 argument (cast to char *) points to a buffer where the result of the calculation is placed. The size of that buffer is specified in arg4 (cast to size_t).

The buffer must be large enough to accommodate the output data, otherwise an error is returned. If arg4 is specified zero, in which case the buffer is not used and the operation returns the minimum required buffer size (i.e., the length of the prime).

Diffie-Hellman computations can be performed in user space, but require a multiple-precision integer (MPI) library. Moving the implementation into the kernel gives access to the kernel MPI implementation, and allows access to secure or acceleration hardware.

Adding support for DH computation to the keyctl() system call was considered a good fit due to the DH algorithm's use for deriving shared keys; it also allows the type of the key to determine which DH implementation (software or hardware) is appropriate.

If the arg5 argument is NULL, then the DH result itself is returned. Otherwise (since Linux 4.12), it is a pointer to a structure which specifies parameters of the KDF operation to be applied:

```
struct keyctl_kdf_params {

    char *hashname;     /* Hash algorithm name */

    char *otherinfo;    /* SP800-56A OtherInfo */

    __u32 otherinfolen; /* Length of otherinfo data */

    __u32 __spare[8];   /* Reserved */
};

```

The hashname field is a null-terminated string which specifies a hash name (available in the kernel's crypto API; the list of the hashes available is rather tricky to observe; please refer to the "Kernel Crypto API Architecture" documentation for the information regarding how hash names are constructed and your kernel's source and configuration regarding what ciphers and templates with type CRYPTO_ALG_TYPE_SHASH are available) to be applied to DH result in KDF operation.

The otherinfo field is an OtherInfo data as described in SP800-56A section 5.8.1.2 and is algorithm-specific. This data is concatenated with the result of DH operation and is provided as an input to the KDF operation. Its size is provided in the otherinfolen field and is limited by KEYCTL_KDF_MAX_OI_LEN constant that defined in security/keys/internal.h to a value of 64.

The __spare field is currently unused. It was ignored until Linux 4.13 (but still should be user-addressable since it is copied to the kernel), and should contain zeros since Linux 4.13.

The KDF implementation complies with SP800-56A as well as with SP800-108 (the counter KDF).

This operation is exposed by libkeyutils (from libkeyutils 1.5.10 onwards) via the functions keyctl_dh_compute(3) and keyctl_dh_compute_alloc(3).

KEYCTL_RESTRICT_KEYRING (since Linux 4.12)

Apply a key-linking restriction to the keyring with the ID provided in arg2 (cast to key_serial_t). The caller must have setattr permission on the key. If arg3 is NULL, any attempt to add a key to the keyring is blocked; otherwise it contains a pointer to a string with a key type name and arg4 contains a pointer to string that describes the type-specific restriction. As of Linux 4.12, only the type "asymmetric" has restrictions defined:

builtin_trusted

Allows only keys that are signed by a key linked to the built-in keyring (".builtin_trusted_keys").

builtin_and_secondary_trusted

Allows only keys that are signed by a key linked to the secondary keyring (".secondary_trusted_keys") or, by extension, a key in a built-in keyring, as the latter is linked to the former.

key_or_keyring:key

key_or_keyring:key:chain

If key specifies the ID of a key of type "asymmetric", then only keys that are signed by this key are allowed.

If key specifies the ID of a keyring, then only keys that are signed by a key linked to this keyring are allowed.

If ":chain" is specified, keys that are signed by a keys linked to the destination keyring (that is, the keyring with the ID specified in the arg2 argument) are also allowed.

Note that a restriction can be configured only once for the specified keyring; once a restriction is set, it can't be overridden.

The argument arg5 is ignored.

## RETURN VALUE
For a successful call, the return value depends on the operation:

KEYCTL_GET_KEYRING_ID

The ID of the requested keyring.

KEYCTL_JOIN_SESSION_KEYRING

The ID of the joined session keyring.

KEYCTL_DESCRIBE

The size of the description (including the terminating null byte), irrespective of the provided buffer size.

KEYCTL_SEARCH

The ID of the key that was found.

KEYCTL_READ

The amount of data that is available in the key, irrespective of the provided buffer size.

KEYCTL_SET_REQKEY_KEYRING

The ID of the previous default keyring to which implicitly requested keys were linked (one of KEY_REQKEY_DEFL_USER_*).

KEYCTL_ASSUME_AUTHORITY

Either 0, if the ID given was 0, or the ID of the authorization key matching the specified key, if a nonzero key ID was provided.

KEYCTL_GET_SECURITY

The size of the LSM security label string (including the terminating null byte), irrespective of the provided buffer size.

KEYCTL_GET_PERSISTENT

The ID of the persistent keyring.

KEYCTL_DH_COMPUTE

The number of bytes copied to the buffer, or, if arg4 is 0, the required buffer size.

All other operations

Zero.

On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EACCES

The requested operation wasn't permitted.

EAGAIN

operation was KEYCTL_DH_COMPUTE and there was an error during crypto module initialization.

EDEADLK

operation was KEYCTL_LINK and the requested link would result in a cycle.

EDEADLK

operation was KEYCTL_RESTRICT_KEYRING and the requested keyring restriction would result in a cycle.

EDQUOT

The key quota for the caller's user would be exceeded by creating a key or linking it to the keyring.

EEXIST

operation was KEYCTL_RESTRICT_KEYRING and keyring provided in arg2 argument already has a restriction set.

EFAULT

operation was KEYCTL_DH_COMPUTE and one of the following has failed:

•

copying of the struct keyctl_dh_params, provided in the arg2 argument, from user space;

•

copying of the struct keyctl_kdf_params, provided in the non-NULL arg5 argument, from user space (in case kernel supports performing KDF operation on DH operation result);

•

copying of data pointed by the hashname field of the struct keyctl_kdf_params from user space;

•

copying of data pointed by the otherinfo field of the struct keyctl_kdf_params from user space if the otherinfolen field was nonzero;

•

copying of the result to user space.

EINVAL

operation was KEYCTL_SETPERM and an invalid permission bit was specified in arg3.

EINVAL

operation was KEYCTL_SEARCH and the size of the description in arg4 (including the terminating null byte) exceeded 4096 bytes.

EINVAL

size of the string (including the terminating null byte) specified in arg3 (the key type) or arg4 (the key description) exceeded the limit (32 bytes and 4096 bytes respectively).

EINVAL (before Linux 4.12)

operation was KEYCTL_DH_COMPUTE, argument arg5 was non-NULL.

EINVAL

operation was KEYCTL_DH_COMPUTE And the digest size of the hashing algorithm supplied is zero.

EINVAL

operation was KEYCTL_DH_COMPUTE and the buffer size provided is not enough to hold the result. Provide 0 as a buffer size in order to obtain the minimum buffer size.

EINVAL

operation was KEYCTL_DH_COMPUTE and the hash name provided in the hashname field of the struct keyctl_kdf_params pointed by arg5 argument is too big (the limit is implementation-specific and varies between kernel versions, but it is deemed big enough for all valid algorithm names).

EINVAL

operation was KEYCTL_DH_COMPUTE and the __spare field of the struct keyctl_kdf_params provided in the arg5 argument contains nonzero values.

EKEYEXPIRED

An expired key was found or specified.

EKEYREJECTED

A rejected key was found or specified.

EKEYREVOKED

A revoked key was found or specified.

ELOOP

operation was KEYCTL_LINK and the requested link would cause the maximum nesting depth for keyrings to be exceeded.

EMSGSIZE

operation was KEYCTL_DH_COMPUTE and the buffer length exceeds KEYCTL_KDF_MAX_OUTPUT_LEN (which is 1024 currently) or the otherinfolen field of the struct keyctl_kdf_parms passed in arg5 exceeds KEYCTL_KDF_MAX_OI_LEN (which is 64 currently).

ENFILE (before Linux 3.13)

operation was KEYCTL_LINK and the keyring is full. (Before Linux 3.13, the available space for storing keyring links was limited to a single page of memory; since Linux 3.13, there is no fixed limit.)

ENOENT

operation was KEYCTL_UNLINK and the key to be unlinked isn't linked to the keyring.

ENOENT

operation was KEYCTL_DH_COMPUTE and the hashing algorithm specified in the hashname field of the struct keyctl_kdf_params pointed by arg5 argument hasn't been found.

ENOENT

operation was KEYCTL_RESTRICT_KEYRING and the type provided in arg3 argument doesn't support setting key linking restrictions.

ENOKEY

No matching key was found or an invalid key was specified.

ENOKEY

The value KEYCTL_GET_KEYRING_ID was specified in operation, the key specified in arg2 did not exist, and arg3 was zero (meaning don't create the key if it didn't exist).

ENOMEM

One of kernel memory allocation routines failed during the execution of the syscall.

ENOTDIR

A key of keyring type was expected but the ID of a key with a different type was provided.

EOPNOTSUPP

operation was KEYCTL_READ and the key type does not support reading (e.g., the type is "login").

EOPNOTSUPP

operation was KEYCTL_UPDATE and the key type does not support updating.

EOPNOTSUPP

operation was KEYCTL_RESTRICT_KEYRING, the type provided in arg3 argument was "asymmetric", and the key specified in the restriction specification provided in arg4 has type other than "asymmetric" or "keyring".

EPERM

operation was KEYCTL_GET_PERSISTENT, arg2 specified a UID other than the calling thread's real or effective UID, and the caller did not have the CAP_SETUID capability.

EPERM

operation was KEYCTL_SESSION_TO_PARENT and either: all of the UIDs (GIDs) of the parent process do not match the effective UID (GID) of the calling process; the UID of the parent's existing session keyring or the UID of the caller's session keyring did not match the effective UID of the caller; the parent process is not single-thread; or the parent process is init(1) or a kernel thread.

ETIMEDOUT

operation was KEYCTL_DH_COMPUTE and the initialization of crypto modules has timed out.

## VERSIONS
A wrapper is provided in the libkeyutils library. (The accompanying package provides the <keyutils.h> header file.) However, rather than using this system call directly, you probably want to use the various library functions mentioned in the descriptions of individual operations above.

## STANDARDS
Linux.

## HISTORY
Linux 2.6.10.

## EXAMPLES
The program below provide subset of the functionality of the request-key(8) program provided by the keyutils package. For informational purposes, the program records various information in a log file.

As described in request_key(2), the request-key(8) program is invoked with command-line arguments that describe a key that is to be instantiated. The example program fetches and logs these arguments. The program assumes authority to instantiate the requested key, and then instantiates that key.

The following shell session demonstrates the use of this program. In the session, we compile the program and then use it to temporarily replace the standard request-key(8) program. (Note that temporarily disabling the standard request-key(8) program may not be safe on some systems.) While our example program is installed, we use the example program shown in request_key(2) to request a key.

```
$ cc -o key_instantiate key_instantiate.c -lkeyutils
$ sudo mv /sbin/request-key /sbin/request-key.backup
$ sudo cp key_instantiate /sbin/request-key
$ ./t_request_key user mykey somepayloaddata
Key ID is 20d035bf
$ sudo mv /sbin/request-key.backup /sbin/request-key
```

Looking at the log file created by this program, we can see the command-line arguments supplied to our example program:

```
$ cat /tmp/key_instantiate.log
Time: Mon Nov  7 13:06:47 2016
Command line arguments:

  argv[0]:            /sbin/request-key

  operation:          create

  key_to_instantiate: 20d035bf

  UID:                1000

  GID:                1000

  thread_keyring:     0

  process_keyring:    0

  session_keyring:    256e6a6
Key description:      user;1000;1000;3f010000;mykey
Auth key payload:     somepayloaddata
Destination keyring:  256e6a6
Auth key description: .request_key_auth;1000;1000;0b010000;20d035bf
```

The last few lines of the above output show that the example program was able to fetch:

•

the description of the key to be instantiated, which included the name of the key (mykey);

•

the payload of the authorization key, which consisted of the data (somepayloaddata) passed to request_key(2);

•

the destination keyring that was specified in the call to request_key(2); and

•

the description of the authorization key, where we can see that the name of the authorization key matches the ID of the key that is to be instantiated (20d035bf).

The example program in request_key(2) specified the destination keyring as KEY_SPEC_SESSION_KEYRING. By examining the contents of /proc/keys, we can see that this was translated to the ID of the destination keyring (0256e6a6) shown in the log output above; we can also see the newly created key with the name mykey and ID 20d035bf.

```
$ cat /proc/keys | egrep 'mykey|256e6a6'
0256e6a6 I--Q---  194 perm 3f030000  1000  1000 keyring  _ses: 3
20d035bf I--Q---    1 perm 3f010000  1000  1000 user     mykey: 16
```

### Program source

```
/* key_instantiate.c */
#include <errno.h>
#include <keyutils.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#ifndef KEY_SPEC_REQUESTOR_KEYRING
#define KEY_SPEC_REQUESTOR_KEYRING      (-8)
#endif
int
main(int argc, char *argv[])
{

    int           akp_size;       /* Size of auth_key_payload */

    int           auth_key;

    char          dbuf[256];

    char          auth_key_payload[256];

    char          *operation;

    FILE          *fp;

    gid_t         gid;

    uid_t         uid;

    time_t        t;

    key_serial_t  key_to_instantiate, dest_keyring;

    key_serial_t  thread_keyring, process_keyring, session_keyring;

    if (argc != 8) {

        fprintf(stderr, "Usage: %s op key uid gid thread_keyring "

                        "process_keyring session_keyring\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    fp = fopen("/tmp/key_instantiate.log", "w");

    if (fp == NULL)

        exit(EXIT_FAILURE);

    setbuf(fp, NULL);

    t = time(NULL);

    fprintf(fp, "Time: %s\n", ctime(&t));

    /*

     * The kernel passes a fixed set of arguments to the program

     * that it execs; fetch them.

     */

    operation = argv[1];

    key_to_instantiate = atoi(argv[2]);

    uid = atoi(argv[3]);

    gid = atoi(argv[4]);

    thread_keyring = atoi(argv[5]);

    process_keyring = atoi(argv[6]);

    session_keyring = atoi(argv[7]);

    fprintf(fp, "Command line arguments:\n");

    fprintf(fp, "  argv[0]:            %s\n", argv[0]);

    fprintf(fp, "  operation:          %s\n", operation);

    fprintf(fp, "  key_to_instantiate: %jx\n",

            (uintmax_t) key_to_instantiate);

    fprintf(fp, "  UID:                %jd\n", (intmax_t) uid);

    fprintf(fp, "  GID:                %jd\n", (intmax_t) gid);

    fprintf(fp, "  thread_keyring:     %jx\n",

            (uintmax_t) thread_keyring);

    fprintf(fp, "  process_keyring:    %jx\n",

            (uintmax_t) process_keyring);

    fprintf(fp, "  session_keyring:    %jx\n",

            (uintmax_t) session_keyring);

    fprintf(fp, "\n");

    /*

     * Assume the authority to instantiate the key named in argv[2].

     */

    if (keyctl(KEYCTL_ASSUME_AUTHORITY, key_to_instantiate) == -1) {

        fprintf(fp, "KEYCTL_ASSUME_AUTHORITY failed: %s\n",

                strerror(errno));

        exit(EXIT_FAILURE);

    }

    /*

     * Fetch the description of the key that is to be instantiated.

     */

    if (keyctl(KEYCTL_DESCRIBE, key_to_instantiate,

               dbuf, sizeof(dbuf)) == -1) {

        fprintf(fp, "KEYCTL_DESCRIBE failed: %s\n", strerror(errno));

        exit(EXIT_FAILURE);

    }

    fprintf(fp, "Key description:      %s\n", dbuf);

    /*

     * Fetch the payload of the authorization key, which is

     * actually the callout data given to request_key().

     */

    akp_size = keyctl(KEYCTL_READ, KEY_SPEC_REQKEY_AUTH_KEY,

                      auth_key_payload, sizeof(auth_key_payload));

    if (akp_size == -1) {

        fprintf(fp, "KEYCTL_READ failed: %s\n", strerror(errno));

        exit(EXIT_FAILURE);

    }

    auth_key_payload[akp_size] = '\0';

    fprintf(fp, "Auth key payload:     %s\n", auth_key_payload);

    /*

     * For interest, get the ID of the authorization key and

     * display it.

     */

    auth_key = keyctl(KEYCTL_GET_KEYRING_ID,

                      KEY_SPEC_REQKEY_AUTH_KEY);

    if (auth_key == -1) {

        fprintf(fp, "KEYCTL_GET_KEYRING_ID failed: %s\n",

                strerror(errno));

        exit(EXIT_FAILURE);

    }

    fprintf(fp, "Auth key ID:          %jx\n", (uintmax_t) auth_key);

    /*

     * Fetch key ID for the request_key(2) destination keyring.

     */

    dest_keyring = keyctl(KEYCTL_GET_KEYRING_ID,

                          KEY_SPEC_REQUESTOR_KEYRING);

    if (dest_keyring == -1) {

        fprintf(fp, "KEYCTL_GET_KEYRING_ID failed: %s\n",

                strerror(errno));

        exit(EXIT_FAILURE);

    }

    fprintf(fp, "Destination keyring:  %jx\n", (uintmax_t) dest_keyring);

    /*

     * Fetch the description of the authorization key. This

     * allows us to see the key type, UID, GID, permissions,

     * and description (name) of the key. Among other things,

     * we will see that the name of the key is a hexadecimal

     * string representing the ID of the key to be instantiated.

     */

    if (keyctl(KEYCTL_DESCRIBE, KEY_SPEC_REQKEY_AUTH_KEY,

               dbuf, sizeof(dbuf)) == -1)

    {

        fprintf(fp, "KEYCTL_DESCRIBE failed: %s\n", strerror(errno));

        exit(EXIT_FAILURE);

    }

    fprintf(fp, "Auth key description: %s\n", dbuf);

    /*

     * Instantiate the key using the callout data that was supplied

     * in the payload of the authorization key.

     */

    if (keyctl(KEYCTL_INSTANTIATE, key_to_instantiate,

               auth_key_payload, akp_size + 1, dest_keyring) == -1)

    {

        fprintf(fp, "KEYCTL_INSTANTIATE failed: %s\n",

                strerror(errno));

        exit(EXIT_FAILURE);

    }

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
keyctl(1), add_key(2), request_key(2), keyctl(3), keyctl_assume_authority(3), keyctl_chown(3), keyctl_clear(3), keyctl_describe(3), keyctl_describe_alloc(3), keyctl_dh_compute(3), keyctl_dh_compute_alloc(3), keyctl_get_keyring_ID(3), keyctl_get_persistent(3), keyctl_get_security(3), keyctl_get_security_alloc(3), keyctl_instantiate(3), keyctl_instantiate_iov(3), keyctl_invalidate(3), keyctl_join_session_keyring(3), keyctl_link(3), keyctl_negate(3), keyctl_read(3), keyctl_read_alloc(3), keyctl_reject(3), keyctl_revoke(3), keyctl_search(3), keyctl_session_to_parent(3), keyctl_set_reqkey_keyring(3), keyctl_set_timeout(3), keyctl_setperm(3), keyctl_unlink(3), keyctl_update(3), recursive_key_scan(3), recursive_session_key_scan(3), capabilities(7), credentials(7), keyrings(7), keyutils(7), persistent-keyring(7), process-keyring(7), session-keyring(7), thread-keyring(7), user-keyring(7), user_namespaces(7), user-session-keyring(7), request-key(8)

The kernel source files under Documentation/security/keys/ (or, before Linux 4.13, in the file Documentation/security/keys.txt).


kill

title: kill(2)

summary: send signal to a process

text:
# kill(2)

## NAME
kill - send signal to a process

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <signal.h>
```

```
int kill(pid_t pid, int sig);
```

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

kill():

```
    _POSIX_C_SOURCE
```

## DESCRIPTION
The kill() system call can be used to send any signal to any process group or process.

If pid is positive, then signal sig is sent to the process with the ID specified by pid.

If pid equals 0, then sig is sent to every process in the process group of the calling process.

If pid equals -1, then sig is sent to every process for which the calling process has permission to send signals, except for process 1 (init), but see below.

If pid is less than -1, then sig is sent to every process in the process group whose ID is -pid.

If sig is 0, then no signal is sent, but existence and permission checks are still performed; this can be used to check for the existence of a process ID or process group ID that the caller is permitted to signal.

For a process to have permission to send a signal, it must either be privileged (under Linux: have the CAP_KILL capability in the user namespace of the target process), or the real or effective user ID of the sending process must equal the real or saved set-user-ID of the target process. In the case of SIGCONT, it suffices when the sending and receiving processes belong to the same session. (Historically, the rules were different; see NOTES.)

## RETURN VALUE
On success (at least one signal was sent), zero is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EINVAL

An invalid signal was specified.

EPERM

The calling process does not have permission to send the signal to any of the target processes.

ESRCH

The target process or process group does not exist. Note that an existing process might be a zombie, a process that has terminated execution, but has not yet been wait(2)ed for.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, SVr4, 4.3BSD.

### Linux notes
Across different kernel versions, Linux has enforced different rules for the permissions required for an unprivileged process to send a signal to another process. In Linux 1.0 to 1.2.2, a signal could be sent if the effective user ID of the sender matched effective user ID of the target, or the real user ID of the sender matched the real user ID of the target. From Linux 1.2.3 until 1.3.77, a signal could be sent if the effective user ID of the sender matched either the real or effective user ID of the target. The current rules, which conform to POSIX.1, were adopted in Linux 1.3.78.

## NOTES
The only signals that can be sent to process ID 1, the init process, are those for which init has explicitly installed signal handlers. This is done to assure the system is not brought down accidentally.

POSIX.1 requires that kill(-1,sig) send sig to all processes that the calling process may send signals to, except possibly for some implementation-defined system processes. Linux allows a process to signal itself, but on Linux the call kill(-1,sig) does not signal the calling process.

POSIX.1 requires that if a process sends a signal to itself, and the sending thread does not have the signal blocked, and no other thread has it unblocked or is waiting for it in sigwait(3), at least one unblocked signal must be delivered to the sending thread before the kill() returns.

## BUGS
In Linux 2.6 up to and including Linux 2.6.7, there was a bug that meant that when sending signals to a process group, kill() failed with the error EPERM if the caller did not have permission to send the signal to any (rather than all) of the members of the process group. Notwithstanding this error return, the signal was still delivered to all of the processes for which the caller had permission to signal.

## SEE ALSO
kill(1), _exit(2), pidfd_send_signal(2), signal(2), tkill(2), exit(3), killpg(3), sigqueue(3), capabilities(7), credentials(7), signal(7)


title: landlock_add_rule(2)

summary: add a new Landlock rule to a ruleset

text:
# landlock_add_rule(2)

## NAME
landlock_add_rule - add a new Landlock rule to a ruleset

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/landlock.h>  /* Definition of LANDLOCK_* constants */
#include <sys/syscall.h>     /* Definition of SYS_* constants */
```

```
int syscall(SYS_landlock_add_rule, int ruleset_fd,
            enum landlock_rule_type rule_type,
            const void *rule_attr, uint32_t flags);
```

## DESCRIPTION
A Landlock rule describes an action on an object. An object is currently a file hierarchy, and the related filesystem actions are defined with a set of access rights. This landlock_add_rule() system call enables adding a new Landlock rule to an existing ruleset created with landlock_create_ruleset(2). See landlock(7) for a global overview.

ruleset_fd is a Landlock ruleset file descriptor obtained with landlock_create_ruleset(2).

rule_type identifies the structure type pointed to by rule_attr. Currently, Linux supports the following rule_type value:

LANDLOCK_RULE_PATH_BENEATH

This defines the object type as a file hierarchy. In this case, rule_attr points to the following structure:

```
struct landlock_path_beneath_attr {

    __u64 allowed_access;

    __s32 parent_fd;
} __attribute__((packed));

```

allowed_access contains a bitmask of allowed filesystem actions for this file hierarchy (see Filesystem actions in landlock(7)).

parent_fd is an opened file descriptor, preferably with the O_PATH flag, which identifies the parent directory of the file hierarchy or just a file.

flags must be 0.

## RETURN VALUE
On success, landlock_add_rule() returns 0.

## ERRORS
landlock_add_rule() can fail for the following reasons:

EOPNOTSUPP

Landlock is supported by the kernel but disabled at boot time.

EINVAL

flags is not 0, or the rule accesses are inconsistent (i.e., rule_attr->allowed_access is not a subset of the ruleset handled accesses).

ENOMSG

Empty accesses (i.e., rule_attr->allowed_access is 0).

EBADF

ruleset_fd is not a file descriptor for the current thread, or a member of rule_attr is not a file descriptor as expected.

EBADFD

ruleset_fd is not a ruleset file descriptor, or a member of rule_attr is not the expected file descriptor type.

EPERM

ruleset_fd has no write access to the underlying ruleset.

EFAULT

rule_attr was not a valid address.

## STANDARDS
Linux.

## HISTORY
Linux 5.13.

## EXAMPLES
See landlock(7).

## SEE ALSO
landlock_create_ruleset(2), landlock_restrict_self(2), landlock(7)


title: landlock_create_ruleset(2)

summary: create a new Landlock ruleset

text:
# landlock_create_ruleset(2)

## NAME
landlock_create_ruleset - create a new Landlock ruleset

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/landlock.h>  /* Definition of LANDLOCK_* constants */
#include <sys/syscall.h>     /* Definition of SYS_* constants */
```

```
int syscall(SYS_landlock_create_ruleset,
            const struct landlock_ruleset_attr *attr,
            size_t size , uint32_t flags);
```

## DESCRIPTION
A Landlock ruleset identifies a set of rules (i.e., actions on objects). This landlock_create_ruleset() system call enables creating a new file descriptor identifying a ruleset. This file descriptor can then be used by landlock_add_rule(2) and landlock_restrict_self(2). See landlock(7) for a global overview.

attr specifies the properties of the new ruleset. It points to the following structure:

```
struct landlock_ruleset_attr {

    __u64 handled_access_fs;
};

```

handled_access_fs is a bitmask of actions that is handled by this ruleset and should then be forbidden if no rule explicitly allows them (see Filesystem actions in landlock(7)). This enables simply restricting ambient rights (e.g., global filesystem access) and is needed for compatibility reasons.

size must be specified as sizeof(struct landlock_ruleset_attr) for compatibility reasons.

flags must be 0 if attr is used. Otherwise, flags can be set to:

LANDLOCK_CREATE_RULESET_VERSION

If attr is NULL and size is 0, then the returned value is the highest supported Landlock ABI version (starting at 1). This version can be used for a best-effort security approach, which is encouraged when user space is not pinned to a specific kernel version. All features documented in these man pages are available with the version 1.

## RETURN VALUE
On success, landlock_create_ruleset() returns a new Landlock ruleset file descriptor, or a Landlock ABI version, according to flags.

## ERRORS
landlock_create_ruleset() can fail for the following reasons:

EOPNOTSUPP

Landlock is supported by the kernel but disabled at boot time.

EINVAL

Unknown flags, or unknown access, or too small size.

E2BIG

size is too big.

EFAULT

attr was not a valid address.

ENOMSG

Empty accesses (i.e., attr->handled_access_fs is 0).

## STANDARDS
Linux.

## HISTORY
Linux 5.13.

## EXAMPLES
See landlock(7).

## SEE ALSO
landlock_add_rule(2), landlock_restrict_self(2), landlock(7)


title: landlock_restrict_self(2)

summary: enforce a Landlock ruleset

text:
# landlock_restrict_self(2)

## NAME
landlock_restrict_self - enforce a Landlock ruleset

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/landlock.h>  /* Definition of LANDLOCK_* constants */
#include <sys/syscall.h>     /* Definition of SYS_* constants */
```

```
int syscall(SYS_landlock_restrict_self, int ruleset_fd,
            uint32_t flags);
```

## DESCRIPTION
Once a Landlock ruleset is populated with the desired rules, the landlock_restrict_self() system call enables enforcing this ruleset on the calling thread. See landlock(7) for a global overview.

A thread can be restricted with multiple rulesets that are then composed together to form the thread's Landlock domain. This can be seen as a stack of rulesets but it is implemented in a more efficient way. A domain can only be updated in such a way that the constraints of each past and future composed rulesets will restrict the thread and its future children for their entire life. It is then possible to gradually enforce tailored access control policies with multiple independent rulesets coming from different sources (e.g., init system configuration, user session policy, built-in application policy). However, most applications should only need one call to landlock_restrict_self() and they should avoid arbitrary numbers of such calls because of the composed rulesets limit. Instead, developers are encouraged to build a tailored ruleset thanks to multiple calls to landlock_add_rule(2).

In order to enforce a ruleset, either the caller must have the CAP_SYS_ADMIN capability in its user namespace, or the thread must already have the no_new_privs bit set. As for seccomp(2), this avoids scenarios where unprivileged processes can affect the behavior of privileged children (e.g., because of set-user-ID binaries). If that bit was not already set by an ancestor of this thread, the thread must make the following call:

```
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);

```

ruleset_fd is a Landlock ruleset file descriptor obtained with landlock_create_ruleset(2) and fully populated with a set of calls to landlock_add_rule(2).

flags must be 0.

## RETURN VALUE
On success, landlock_restrict_self() returns 0.

## ERRORS
landlock_restrict_self() can fail for the following reasons:

EOPNOTSUPP

Landlock is supported by the kernel but disabled at boot time.

EINVAL

flags is not 0.

EBADF

ruleset_fd is not a file descriptor for the current thread.

EBADFD

ruleset_fd is not a ruleset file descriptor.

EPERM

ruleset_fd has no read access to the underlying ruleset, or the calling thread is not running with no_new_privs, or it doesn't have the CAP_SYS_ADMIN in its user namespace.

E2BIG

The maximum number of composed rulesets is reached for the calling thread. This limit is currently 64.

## STANDARDS
Linux.

## HISTORY
Linux 5.13.

## EXAMPLES
See landlock(7).

## SEE ALSO
landlock_create_ruleset(2), landlock_add_rule(2), landlock(7)


link

title: link(2)

summary: make a new name for a file

text:
# link(2)

## NAME
link, linkat - make a new name for a file

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <unistd.h>
```

```
int link(const char *oldpath, const char *newpath);
```

```
#include <fcntl.h>           /* Definition of AT_* constants */
#include <unistd.h>
```

```
int linkat(int olddirfd, const char *oldpath,
           int newdirfd, const char *newpath, int flags);
```

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

linkat():

```
    Since glibc 2.10:

        _POSIX_C_SOURCE >= 200809L

    Before glibc 2.10:

        _ATFILE_SOURCE
```

## DESCRIPTION
link() creates a new link (also known as a hard link) to an existing file.

If newpath exists, it will not be overwritten.

This new name may be used exactly as the old one for any operation; both names refer to the same file (and so have the same permissions and ownership) and it is impossible to tell which name was the "original".

### linkat()
The linkat() system call operates in exactly the same way as link(), except for the differences described here.

If the pathname given in oldpath is relative, then it is interpreted relative to the directory referred to by the file descriptor olddirfd (rather than relative to the current working directory of the calling process, as is done by link() for a relative pathname).

If oldpath is relative and olddirfd is the special value AT_FDCWD, then oldpath is interpreted relative to the current working directory of the calling process (like link()).

If oldpath is absolute, then olddirfd is ignored.

The interpretation of newpath is as for oldpath, except that a relative pathname is interpreted relative to the directory referred to by the file descriptor newdirfd.

The following values can be bitwise ORed in flags:

AT_EMPTY_PATH (since Linux 2.6.39)

If oldpath is an empty string, create a link to the file referenced by olddirfd (which may have been obtained using the open(2) O_PATH flag). In this case, olddirfd can refer to any type of file except a directory. This will generally not work if the file has a link count of zero (files created with O_TMPFILE and without O_EXCL are an exception). The caller must have the CAP_DAC_READ_SEARCH capability in order to use this flag. This flag is Linux-specific; define _GNU_SOURCE to obtain its definition.

AT_SYMLINK_FOLLOW (since Linux 2.6.18)

By default, linkat(), does not dereference oldpath if it is a symbolic link (like link()). The flag AT_SYMLINK_FOLLOW can be specified in flags to cause oldpath to be dereferenced if it is a symbolic link. If procfs is mounted, this can be used as an alternative to AT_EMPTY_PATH, like this:

```
linkat(AT_FDCWD, "/proc/self/fd/<fd>", newdirfd,

       newname, AT_SYMLINK_FOLLOW);

```

Before Linux 2.6.18, the flags argument was unused, and had to be specified as 0.

See openat(2) for an explanation of the need for linkat().

## RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EACCES

Write access to the directory containing newpath is denied, or search permission is denied for one of the directories in the path prefix of oldpath or newpath. (See also path_resolution(7).)

EDQUOT

The user's quota of disk blocks on the filesystem has been exhausted.

EEXIST

newpath already exists.

EFAULT

oldpath or newpath points outside your accessible address space.

EIO

An I/O error occurred.

ELOOP

Too many symbolic links were encountered in resolving oldpath or newpath.

EMLINK

The file referred to by oldpath already has the maximum number of links to it. For example, on an ext4(5) filesystem that does not employ the dir_index feature, the limit on the number of hard links to a file is 65,000; on btrfs(5), the limit is 65,535 links.

ENAMETOOLONG

oldpath or newpath was too long.

ENOENT

A directory component in oldpath or newpath does not exist or is a dangling symbolic link.

ENOMEM

Insufficient kernel memory was available.

ENOSPC

The device containing the file has no room for the new directory entry.

ENOTDIR

A component used as a directory in oldpath or newpath is not, in fact, a directory.

EPERM

oldpath is a directory.

EPERM

The filesystem containing oldpath and newpath does not support the creation of hard links.

EPERM (since Linux 3.6)

The caller does not have permission to create a hard link to this file (see the description of /proc/sys/fs/protected_hardlinks in proc(5)).

EPERM

oldpath is marked immutable or append-only. (See ioctl_iflags(2).)

EROFS

The file is on a read-only filesystem.

EXDEV

oldpath and newpath are not on the same mounted filesystem. (Linux permits a filesystem to be mounted at multiple points, but link() does not work across different mounts, even if the same filesystem is mounted on both.)

The following additional errors can occur for linkat():

EBADF

oldpath (newpath) is relative but olddirfd (newdirfd) is neither AT_FDCWD nor a valid file descriptor.

EINVAL

An invalid flag value was specified in flags.

ENOENT

AT_EMPTY_PATH was specified in flags, but the caller did not have the CAP_DAC_READ_SEARCH capability.

ENOENT

An attempt was made to link to the /proc/self/fd/NN file corresponding to a file descriptor created with

```
open(path, O_TMPFILE | O_EXCL, mode);

```

See open(2).

ENOENT

An attempt was made to link to a /proc/self/fd/NN file corresponding to a file that has been deleted.

ENOENT

oldpath is a relative pathname and olddirfd refers to a directory that has been deleted, or newpath is a relative pathname and newdirfd refers to a directory that has been deleted.

ENOTDIR

oldpath is relative and olddirfd is a file descriptor referring to a file other than a directory; or similar for newpath and newdirfd

EPERM

AT_EMPTY_PATH was specified in flags, oldpath is an empty string, and olddirfd refers to a directory.

## VERSIONS
POSIX.1-2001 says that link() should dereference oldpath if it is a symbolic link. However, since Linux 2.0, Linux does not do so: if oldpath is a symbolic link, then newpath is created as a (hard) link to the same symbolic link file (i.e., newpath becomes a symbolic link to the same file that oldpath refers to). Some other implementations behave in the same manner as Linux. POSIX.1-2008 changes the specification of link(), making it implementation-dependent whether or not oldpath is dereferenced if it is a symbolic link. For precise control over the treatment of symbolic links when creating a link, use linkat().

### glibc
On older kernels where linkat() is unavailable, the glibc wrapper function falls back to the use of link(), unless the AT_SYMLINK_FOLLOW is specified. When oldpath and newpath are relative pathnames, glibc constructs pathnames based on the symbolic links in /proc/self/fd that correspond to the olddirfd and newdirfd arguments.

## STANDARDS
link()

POSIX.1-2008.

## HISTORY
link()

SVr4, 4.3BSD, POSIX.1-2001 (but see VERSIONS).

linkat()

POSIX.1-2008. Linux 2.6.16, glibc 2.4.

## NOTES
Hard links, as created by link(), cannot span filesystems. Use symlink(2) if this is required.

## BUGS
On NFS filesystems, the return code may be wrong in case the NFS server performs the link creation and dies before it can say so. Use stat(2) to find out if the link got created.

## SEE ALSO
ln(1), open(2), rename(2), stat(2), symlink(2), unlink(2), path_resolution(7), symlink(7)


listen

title: listen(2)

summary: listen for connections on a socket

text:
# listen(2)

## NAME
listen - listen for connections on a socket

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <sys/socket.h>
```

```
int listen(int sockfd, int backlog);
```

## DESCRIPTION
listen() marks the socket referred to by sockfd as a passive socket, that is, as a socket that will be used to accept incoming connection requests using accept(2).

The sockfd argument is a file descriptor that refers to a socket of type SOCK_STREAM or SOCK_SEQPACKET.

The backlog argument defines the maximum length to which the queue of pending connections for sockfd may grow. If a connection request arrives when the queue is full, the client may receive an error with an indication of ECONNREFUSED or, if the underlying protocol supports retransmission, the request may be ignored so that a later reattempt at connection succeeds.

## RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EADDRINUSE

Another socket is already listening on the same port.

EADDRINUSE

(Internet domain sockets) The socket referred to by sockfd had not previously been bound to an address and, upon attempting to bind it to an ephemeral port, it was determined that all port numbers in the ephemeral port range are currently in use. See the discussion of /proc/sys/net/ipv4/ip_local_port_range in ip(7).

EBADF

The argument sockfd is not a valid file descriptor.

ENOTSOCK

The file descriptor sockfd does not refer to a socket.

EOPNOTSUPP

The socket is not of a type that supports the listen() operation.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, 4.4BSD (first appeared in 4.2BSD).

## NOTES
To accept connections, the following steps are performed:

(1)

A socket is created with socket(2).

(2)

The socket is bound to a local address using bind(2), so that other sockets may be connect(2)ed to it.

(3)

A willingness to accept incoming connections and a queue limit for incoming connections are specified with listen().

(4)

Connections are accepted with accept(2).

The behavior of the backlog argument on TCP sockets changed with Linux 2.2. Now it specifies the queue length for completely established sockets waiting to be accepted, instead of the number of incomplete connection requests. The maximum length of the queue for incomplete sockets can be set using /proc/sys/net/ipv4/tcp_max_syn_backlog. When syncookies are enabled there is no logical maximum length and this setting is ignored. See tcp(7) for more information.

If the backlog argument is greater than the value in /proc/sys/net/core/somaxconn, then it is silently capped to that value. Since Linux 5.4, the default in this file is 4096; in earlier kernels, the default value is 128. Before Linux 2.4.25, this limit was a hard coded value, SOMAXCONN, with the value 128.

## EXAMPLES
See bind(2).

## SEE ALSO
accept(2), bind(2), connect(2), socket(2), socket(7)


listxattr

title: listxattr(2)

summary: list extended attribute names

text:
# listxattr(2)

## NAME
listxattr, llistxattr, flistxattr - list extended attribute names

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <sys/xattr.h>
```

```
ssize_t listxattr(const char *path, char *_Nullable list, size_t size);
ssize_t llistxattr(const char *path, char *_Nullable list, size_t size);
ssize_t flistxattr(int fd, char *_Nullable list, size_t size);
```

## DESCRIPTION
Extended attributes are name:value pairs associated with inodes (files, directories, symbolic links, etc.). They are extensions to the normal attributes which are associated with all inodes in the system (i.e., the stat(2) data). A complete overview of extended attributes concepts can be found in xattr(7).

listxattr() retrieves the list of extended attribute names associated with the given path in the filesystem. The retrieved list is placed in list, a caller-allocated buffer whose size (in bytes) is specified in the argument size. The list is the set of (null-terminated) names, one after the other. Names of extended attributes to which the calling process does not have access may be omitted from the list. The length of the attribute name list is returned.

llistxattr() is identical to listxattr(), except in the case of a symbolic link, where the list of names of extended attributes associated with the link itself is retrieved, not the file that it refers to.

flistxattr() is identical to listxattr(), only the open file referred to by fd (as returned by open(2)) is interrogated in place of path.

A single extended attribute name is a null-terminated string. The name includes a namespace prefix; there may be several, disjoint namespaces associated with an individual inode.

If size is specified as zero, these calls return the current size of the list of extended attribute names (and leave list unchanged). This can be used to determine the size of the buffer that should be supplied in a subsequent call. (But, bear in mind that there is a possibility that the set of extended attributes may change between the two calls, so that it is still necessary to check the return status from the second call.)

### Example
The list of names is returned as an unordered array of null-terminated character strings (attribute names are separated by null bytes ('\0')), like this:

```
user.name1\0system.name1\0user.name2\0
```

Filesystems that implement POSIX ACLs using extended attributes might return a list like this:

```
system.posix_acl_access\0system.posix_acl_default\0
```

## RETURN VALUE
On success, a nonnegative number is returned indicating the size of the extended attribute name list. On failure, -1 is returned and errno is set to indicate the error.

## ERRORS
E2BIG

The size of the list of extended attribute names is larger than the maximum size allowed; the list cannot be retrieved. This can happen on filesystems that support an unlimited number of extended attributes per file such as XFS, for example. See BUGS.

ENOTSUP

Extended attributes are not supported by the filesystem, or are disabled.

ERANGE

The size of the list buffer is too small to hold the result.

In addition, the errors documented in stat(2) can also occur.

## STANDARDS
Linux.

## HISTORY
Linux 2.4, glibc 2.3.

## BUGS
As noted in xattr(7), the VFS imposes a limit of 64 kB on the size of the extended attribute name list returned by listxattr(). If the total size of attribute names attached to a file exceeds this limit, it is no longer possible to retrieve the list of attribute names.

## EXAMPLES
The following program demonstrates the usage of listxattr() and getxattr(2). For the file whose pathname is provided as a command-line argument, it lists all extended file attributes and their values.

To keep the code simple, the program assumes that attribute keys and values are constant during the execution of the program. A production program should expect and handle changes during execution of the program. For example, the number of bytes required for attribute keys might increase between the two calls to listxattr(). An application could handle this possibility using a loop that retries the call (perhaps up to a predetermined maximum number of attempts) with a larger buffer each time it fails with the error ERANGE. Calls to getxattr(2) could be handled similarly.

The following output was recorded by first creating a file, setting some extended file attributes, and then listing the attributes with the example program.

### Example output

```
$ touch /tmp/foo
$ setfattr -n user.fred -v chocolate /tmp/foo
$ setfattr -n user.frieda -v bar /tmp/foo
$ setfattr -n user.empty /tmp/foo
$ ./listxattr /tmp/foo
user.fred: chocolate
user.frieda: bar
user.empty: <no value>
```

### Program source (listxattr.c)

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/xattr.h>
int
main(int argc, char *argv[])
{

    char     *buf, *key, *val;

    ssize_t  buflen, keylen, vallen;

    if (argc != 2) {

        fprintf(stderr, "Usage: %s path\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    /*

     * Determine the length of the buffer needed.

     */

    buflen = listxattr(argv[1], NULL, 0);

    if (buflen == -1) {

        perror("listxattr");

        exit(EXIT_FAILURE);

    }

    if (buflen == 0) {

        printf("%s has no attributes.\n", argv[1]);

        exit(EXIT_SUCCESS);

    }

    /*

     * Allocate the buffer.

     */

    buf = malloc(buflen);

    if (buf == NULL) {

        perror("malloc");

        exit(EXIT_FAILURE);

    }

    /*

     * Copy the list of attribute keys to the buffer.

     */

    buflen = listxattr(argv[1], buf, buflen);

    if (buflen == -1) {

        perror("listxattr");

        exit(EXIT_FAILURE);

    }

    /*

     * Loop over the list of zero terminated strings with the

     * attribute keys. Use the remaining buffer length to determine

     * the end of the list.

     */

    key = buf;

    while (buflen > 0) {

        /*

         * Output attribute key.

         */

        printf("%s: ", key);

        /*

         * Determine length of the value.

         */

        vallen = getxattr(argv[1], key, NULL, 0);

        if (vallen == -1)

            perror("getxattr");

        if (vallen > 0) {

            /*

             * Allocate value buffer.

             * One extra byte is needed to append 0x00.

             */

            val = malloc(vallen + 1);

            if (val == NULL) {

                perror("malloc");

                exit(EXIT_FAILURE);

            }

            /*

             * Copy value to buffer.

             */

            vallen = getxattr(argv[1], key, val, vallen);

            if (vallen == -1) {

                perror("getxattr");

            } else {

                /*

                 * Output attribute value.

                 */

                val[vallen] = 0;

                printf("%s", val);

            }

            free(val);

        } else if (vallen == 0) {

            printf("<no value>");

        }

        printf("\n");

        /*

         * Forward to next attribute key.

         */

        keylen = strlen(key) + 1;

        buflen -= keylen;

        key += keylen;

    }

    free(buf);

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
getfattr(1), setfattr(1), getxattr(2), open(2), removexattr(2), setxattr(2), stat(2), symlink(7), xattr(7)


llseek

title: llseek(2)

summary: reposition read/write file offset

text:
# llseek(2)

## NAME
_llseek - reposition read/write file offset

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <sys/syscall.h>      /* Definition of SYS_* constants */
#include <unistd.h>
```

```
int syscall(SYS__llseek, unsigned int fd, unsigned long offset_high,
            unsigned long offset_low, loff_t *result,
            unsigned int whence);
```

Note: glibc provides no wrapper for _llseek(), necessitating the use of syscall(2).

## DESCRIPTION
Note: for information about the llseek(3) library function, see lseek64(3).

The _llseek() system call repositions the offset of the open file description associated with the file descriptor fd to the value

(offset_high << 32) | offset_low

This new offset is a byte offset relative to the beginning of the file, the current file offset, or the end of the file, depending on whether whence is SEEK_SET, SEEK_CUR, or SEEK_END, respectively.

The new file offset is returned in the argument result. The type loff_t is a 64-bit signed type.

This system call exists on various 32-bit platforms to support seeking to large file offsets.

## RETURN VALUE
Upon successful completion, _llseek() returns 0. Otherwise, a value of -1 is returned and errno is set to indicate the error.

## ERRORS
EBADF

fd is not an open file descriptor.

EFAULT

Problem with copying results to user space.

EINVAL

whence is invalid.

## VERSIONS
You probably want to use the lseek(2) wrapper function instead.

## STANDARDS
Linux.

## SEE ALSO
lseek(2), open(2), lseek64(3)


title: lookup_dcookie(2)

summary: return a directory entry's path

text:
# lookup_dcookie(2)

## NAME
lookup_dcookie - return a directory entry's path

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <sys/syscall.h>      /* Definition of SYS_* constants */
#include <unistd.h>
```

```
int syscall(SYS_lookup_dcookie, uint64_t cookie, char *buffer,
            size_t len);
```

Note: glibc provides no wrapper for lookup_dcookie(), necessitating the use of syscall(2).

## DESCRIPTION
Look up the full path of the directory entry specified by the value cookie. The cookie is an opaque identifier uniquely identifying a particular directory entry. The buffer given is filled in with the full path of the directory entry.

For lookup_dcookie() to return successfully, the kernel must still hold a cookie reference to the directory entry.

## RETURN VALUE
On success, lookup_dcookie() returns the length of the path string copied into the buffer. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EFAULT

The buffer was not valid.

EINVAL

The kernel has no registered cookie/directory entry mappings at the time of lookup, or the cookie does not refer to a valid directory entry.

ENAMETOOLONG

The name could not fit in the buffer.

ENOMEM

The kernel could not allocate memory for the temporary buffer holding the path.

EPERM

The process does not have the capability CAP_SYS_ADMIN required to look up cookie values.

ERANGE

The buffer was not large enough to hold the path of the directory entry.

## STANDARDS
Linux.

## HISTORY
Linux 2.5.43.

The ENAMETOOLONG error was added in Linux 2.5.70.

## NOTES
lookup_dcookie() is a special-purpose system call, currently used only by the oprofile(1) profiler. It relies on a kernel driver to register cookies for directory entries.

The path returned may be suffixed by the string " (deleted)" if the directory entry has been removed.

## SEE ALSO
oprofile(1)


lseek

title: lseek(2)

summary: reposition read/write file offset

text:
# lseek(2)

## NAME
lseek - reposition read/write file offset

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <unistd.h>
```

```
off_t lseek(int fd, off_t offset, int whence);
```

## DESCRIPTION
lseek() repositions the file offset of the open file description associated with the file descriptor fd to the argument offset according to the directive whence as follows:

SEEK_SET

The file offset is set to offset bytes.

SEEK_CUR

The file offset is set to its current location plus offset bytes.

SEEK_END

The file offset is set to the size of the file plus offset bytes.

lseek() allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a "hole") return null bytes ('\0') until data is actually written into the gap.

### Seeking file data and holes
Since Linux 3.1, Linux supports the following additional values for whence:

SEEK_DATA

Adjust the file offset to the next location in the file greater than or equal to offset containing data. If offset points to data, then the file offset is set to offset.

SEEK_HOLE

Adjust the file offset to the next hole in the file greater than or equal to offset. If offset points into the middle of a hole, then the file offset is set to offset. If there is no hole past offset, then the file offset is adjusted to the end of the file (i.e., there is an implicit hole at the end of any file).

In both of the above cases, lseek() fails if offset points past the end of the file.

These operations allow applications to map holes in a sparsely allocated file. This can be useful for applications such as file backup tools, which can save space when creating backups and preserve holes, if they have a mechanism for discovering holes.

For the purposes of these operations, a hole is a sequence of zeros that (normally) has not been allocated in the underlying file storage. However, a filesystem is not obliged to report holes, so these operations are not a guaranteed mechanism for mapping the storage space actually allocated to a file. (Furthermore, a sequence of zeros that actually has been written to the underlying storage may not be reported as a hole.) In the simplest implementation, a filesystem can support the operations by making SEEK_HOLE always return the offset of the end of the file, and making SEEK_DATA always return offset (i.e., even if the location referred to by offset is a hole, it can be considered to consist of data that is a sequence of zeros).

The _GNU_SOURCE feature test macro must be defined in order to obtain the definitions of SEEK_DATA and SEEK_HOLE from <unistd.h>.

The SEEK_HOLE and SEEK_DATA operations are supported for the following filesystems:

•

Btrfs (since Linux 3.1)

•

OCFS (since Linux 3.2)

•

XFS (since Linux 3.5)

•

ext4 (since Linux 3.8)

•

tmpfs(5) (since Linux 3.8)

•

NFS (since Linux 3.18)

•

FUSE (since Linux 4.5)

•

GFS2 (since Linux 4.15)

## RETURN VALUE
Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file. On error, the value (off_t) -1 is returned and errno is set to indicate the error.

## ERRORS
EBADF

fd is not an open file descriptor.

EINVAL

whence is not valid. Or: the resulting file offset would be negative, or beyond the end of a seekable device.

ENXIO

whence is SEEK_DATA or SEEK_HOLE, and offset is beyond the end of the file, or whence is SEEK_DATA and offset is within a hole at the end of the file.

EOVERFLOW

The resulting file offset cannot be represented in an off_t.

ESPIPE

fd is associated with a pipe, socket, or FIFO.

## VERSIONS
On Linux, using lseek() on a terminal device fails with the error ESPIPE.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, SVr4, 4.3BSD.

SEEK_DATA and SEEK_HOLE are nonstandard extensions also present in Solaris, FreeBSD, and DragonFly BSD; they are proposed for inclusion in the next POSIX revision (Issue 8).

## NOTES
See open(2) for a discussion of the relationship between file descriptors, open file descriptions, and files.

If the O_APPEND file status flag is set on the open file description, then a write(2) always moves the file offset to the end of the file, regardless of the use of lseek().

Some devices are incapable of seeking and POSIX does not specify which devices must support lseek().

## SEE ALSO
dup(2), fallocate(2), fork(2), open(2), fseek(3), lseek64(3), posix_fallocate(3)