LCOV - code coverage report
Current view: top level - libbpfilter - ctx.c (source / functions) Coverage Total Hit
Test: coverage.lcov Lines: 55.4 % 112 62
Test Date: 2026-11-26 17:15:32 Functions: 76.9 % 13 10
Branches: 30.9 % 94 29

             Branch data     Line data    Source code
       1                 :             : /* SPDX-License-Identifier: GPL-2.0-only */
       2                 :             : /*
       3                 :             :  * Copyright (c) 2023 Meta Platforms, Inc. and affiliates.
       4                 :             :  */
       5                 :             : 
       6                 :             : #include <dirent.h>
       7                 :             : #include <errno.h>
       8                 :             : #include <fcntl.h>
       9                 :             : #include <stdbool.h>
      10                 :             : #include <stdlib.h>
      11                 :             : #include <sys/file.h>
      12                 :             : #include <unistd.h>
      13                 :             : 
      14                 :             : #include <bpfilter/bpf.h>
      15                 :             : #include <bpfilter/btf.h>
      16                 :             : #include <bpfilter/ctx.h>
      17                 :             : #include <bpfilter/dump.h>
      18                 :             : #include <bpfilter/elfstub.h>
      19                 :             : #include <bpfilter/helper.h>
      20                 :             : #include <bpfilter/io.h>
      21                 :             : #include <bpfilter/logger.h>
      22                 :             : 
      23                 :             : #include "core/lock.h"
      24                 :             : 
      25                 :             : #define _free_bf_ctx_ __attribute__((cleanup(_bf_ctx_free)))
      26                 :             : 
      27                 :             : /**
      28                 :             :  * @struct bf_ctx
      29                 :             :  *
      30                 :             :  * bpfilter working context. Only one context is used during the library's
      31                 :             :  * lifetime.
      32                 :             :  */
      33                 :             : struct bf_ctx
      34                 :             : {
      35                 :             :     /// BPF token file descriptor
      36                 :             :     int token_fd;
      37                 :             : 
      38                 :             :     struct bf_elfstub *stubs[_BF_ELFSTUB_MAX];
      39                 :             : 
      40                 :             :     /// Pass a token to BPF system calls, obtained from bpffs.
      41                 :             :     bool with_bpf_token;
      42                 :             : 
      43                 :             :     /// Path to the bpffs to pin the BPF objects into.
      44                 :             :     const char *bpffs_path;
      45                 :             : 
      46                 :             :     /// Verbose flags.
      47                 :             :     uint16_t verbose;
      48                 :             : };
      49                 :             : 
      50                 :             : static void _bf_ctx_free(struct bf_ctx **ctx);
      51                 :             : 
      52                 :             : /// Global runtime context. Hidden in this translation unit.
      53                 :             : static struct bf_ctx *_bf_global_ctx = NULL;
      54                 :             : 
      55                 :           0 : static int _bf_ctx_gen_token(const char *bpffs_path)
      56                 :             : {
      57                 :           0 :     _cleanup_close_ int mnt_fd = -1;
      58                 :           0 :     _cleanup_close_ int bpffs_fd = -1;
      59                 :           0 :     _cleanup_close_ int token_fd = -1;
      60                 :             : 
      61                 :           0 :     mnt_fd = open(bpffs_path, O_DIRECTORY);
      62         [ #  # ]:           0 :     if (mnt_fd < 0)
      63         [ #  # ]:           0 :         return bf_err_r(errno, "failed to open '%s'", bpffs_path);
      64                 :             : 
      65                 :           0 :     bpffs_fd = openat(mnt_fd, ".", 0, O_RDWR);
      66         [ #  # ]:           0 :     if (bpffs_fd < 0)
      67         [ #  # ]:           0 :         return bf_err_r(errno, "failed to get bpffs FD from '%s'", bpffs_path);
      68                 :             : 
      69                 :           0 :     token_fd = bf_bpf_token_create(bpffs_fd);
      70         [ #  # ]:           0 :     if (token_fd < 0) {
      71         [ #  # ]:           0 :         return bf_err_r(token_fd, "failed to create BPF token for '%s'",
      72                 :             :                         bpffs_path);
      73                 :             :     }
      74                 :             : 
      75                 :           0 :     return TAKE_FD(token_fd);
      76                 :             : }
      77                 :             : 
      78                 :             : /**
      79                 :             :  * Create and initialize a new context.
      80                 :             :  *
      81                 :             :  * On failure, @p ctx is left unchanged.
      82                 :             :  *
      83                 :             :  * @param ctx New context to create. Can't be NULL.
      84                 :             :  * @param with_bpf_token If true, create a BPF token from bpffs.
      85                 :             :  * @param bpffs_path Path to the bpffs mountpoint. Can't be NULL.
      86                 :             :  * @param verbose Bitmask of verbose flags.
      87                 :             :  * @return 0 on success, negative errno value on failure.
      88                 :             :  */
      89                 :         433 : static int _bf_ctx_new(struct bf_ctx **ctx, bool with_bpf_token,
      90                 :             :                        const char *bpffs_path, uint16_t verbose)
      91                 :             : {
      92                 :         433 :     _free_bf_ctx_ struct bf_ctx *_ctx = NULL;
      93                 :             :     int r;
      94                 :             : 
      95                 :             :     assert(ctx);
      96                 :             :     assert(bpffs_path);
      97                 :             : 
      98                 :         433 :     _ctx = calloc(1, sizeof(*_ctx));
      99         [ +  - ]:         433 :     if (!_ctx)
     100                 :             :         return -ENOMEM;
     101                 :             : 
     102                 :         433 :     _ctx->token_fd = -1;
     103                 :             : 
     104                 :         433 :     r = bf_btf_setup();
     105         [ -  + ]:         433 :     if (r)
     106         [ #  # ]:           0 :         return bf_err_r(r, "failed to load vmlinux BTF");
     107                 :             : 
     108                 :         433 :     _ctx->with_bpf_token = with_bpf_token;
     109                 :         433 :     _ctx->verbose = verbose;
     110                 :             : 
     111                 :         433 :     _ctx->bpffs_path = strdup(bpffs_path);
     112         [ +  - ]:         433 :     if (!_ctx->bpffs_path)
     113                 :             :         return -ENOMEM;
     114                 :             : 
     115         [ -  + ]:         433 :     if (_ctx->with_bpf_token) {
     116                 :           0 :         _cleanup_close_ int token_fd = -1;
     117                 :             : 
     118                 :           0 :         r = bf_btf_kernel_has_token();
     119         [ #  # ]:           0 :         if (r == -ENOENT) {
     120         [ #  # ]:           0 :             bf_err(
     121                 :             :                 "--with-bpf-token requested, but this kernel doesn't support BPF token");
     122                 :             :             return r;
     123                 :             :         }
     124         [ #  # ]:           0 :         if (r)
     125         [ #  # ]:           0 :             return bf_err_r(r, "failed to check for BPF token support");
     126                 :             : 
     127                 :           0 :         token_fd = _bf_ctx_gen_token(_ctx->bpffs_path);
     128         [ #  # ]:           0 :         if (token_fd < 0)
     129         [ #  # ]:           0 :             return bf_err_r(token_fd, "failed to generate a BPF token");
     130                 :             : 
     131                 :           0 :         _ctx->token_fd = TAKE_FD(token_fd);
     132                 :             :     }
     133                 :             : 
     134         [ +  + ]:        3897 :     for (enum bf_elfstub_id id = 0; id < _BF_ELFSTUB_MAX; ++id) {
     135                 :        3464 :         r = bf_elfstub_new(&_ctx->stubs[id], id);
     136         [ -  + ]:        3464 :         if (r)
     137         [ #  # ]:           0 :             return bf_err_r(r, "failed to create ELF stub ID %u", id);
     138                 :             :     }
     139                 :             : 
     140                 :         433 :     *ctx = TAKE_PTR(_ctx);
     141                 :             : 
     142                 :         433 :     return 0;
     143                 :             : }
     144                 :             : 
     145                 :             : /**
     146                 :             :  * Free a context.
     147                 :             :  *
     148                 :             :  * If @p ctx points to a NULL pointer, this function does nothing. Once
     149                 :             :  * the function returns, @p ctx points to a NULL pointer.
     150                 :             :  *
     151                 :             :  * @param ctx Context to free. Can't be NULL.
     152                 :             :  */
     153                 :         866 : static void _bf_ctx_free(struct bf_ctx **ctx)
     154                 :             : {
     155                 :             :     assert(ctx);
     156                 :             : 
     157         [ +  + ]:         866 :     if (!*ctx)
     158                 :             :         return;
     159                 :             : 
     160                 :         433 :     closep(&(*ctx)->token_fd);
     161                 :         433 :     BF_FREEP(&(*ctx)->bpffs_path);
     162                 :             : 
     163         [ +  + ]:        3897 :     for (enum bf_elfstub_id id = 0; id < _BF_ELFSTUB_MAX; ++id)
     164                 :        3464 :         bf_elfstub_free(&(*ctx)->stubs[id]);
     165                 :             : 
     166                 :         433 :     bf_btf_teardown();
     167                 :             : 
     168                 :         433 :     BF_FREEP(ctx);
     169                 :             : }
     170                 :             : 
     171                 :             : /**
     172                 :             :  * See @ref bf_ctx_dump for details.
     173                 :             :  */
     174                 :           0 : static void _bf_ctx_dump(const struct bf_ctx *ctx, prefix_t *prefix)
     175                 :             : {
     176         [ #  # ]:           0 :     DUMP(prefix, "struct bf_ctx at %p", ctx);
     177                 :             : 
     178                 :           0 :     bf_dump_prefix_push(prefix);
     179                 :             : 
     180         [ #  # ]:           0 :     DUMP(prefix, "token_fd: %d", ctx->token_fd);
     181                 :             : 
     182                 :           0 :     bf_dump_prefix_pop(prefix);
     183                 :           0 : }
     184                 :             : 
     185                 :             : static void _bf_free_dir(DIR **dir)
     186                 :             : {
     187                 :             :     if (!*dir)
     188                 :             :         return;
     189                 :             : 
     190                 :         433 :     closedir(*dir);
     191                 :             :     *dir = NULL;
     192                 :             : }
     193                 :             : 
     194                 :             : #define _free_dir_ __attribute__((__cleanup__(_bf_free_dir)))
     195                 :             : 
     196                 :             : /**
     197                 :             :  * @brief Sweep leftover staging directories from a previous run.
     198                 :             :  *
     199                 :             :  * `core/lock.c` creates uniquely-named `.staging.*` directories while
     200                 :             :  * publishing new chain dirs via `renameat2(RENAME_NOREPLACE)`. If a
     201                 :             :  * process crashes between the `mkdirat` and the `renameat2`, the staging
     202                 :             :  * dir is orphaned.
     203                 :             :  *
     204                 :             :  * This function walks the pindir under `BF_LOCK_WRITE` and removes any
     205                 :             :  * `.staging.*` entry whose `flock(LOCK_EX | LOCK_NB)` succeeds (meaning
     206                 :             :  * nobody currently owns it). Live staging dirs are left alone.
     207                 :             :  *
     208                 :             :  * Runs once from `bf_ctx_setup()`. Non-fatal: a failure to sweep only
     209                 :             :  * leaves garbage behind, it does not compromise correctness.
     210                 :             :  */
     211                 :         433 : static void _bf_ctx_sweep_staging(void)
     212                 :             : {
     213                 :         433 :     _clean_bf_lock_ struct bf_lock lock = bf_lock_default();
     214                 :             :     _free_dir_ DIR *dir = NULL;
     215                 :             :     struct dirent *entry;
     216                 :             :     int iter_fd;
     217                 :             :     int r;
     218                 :             : 
     219                 :         433 :     r = bf_lock_init(&lock, BF_LOCK_WRITE);
     220         [ -  + ]:         433 :     if (r) {
     221         [ #  # ]:           0 :         bf_warn_r(r, "failed to lock pindir for staging sweep, skipping");
     222                 :             :         return;
     223                 :             :     }
     224                 :             : 
     225                 :         433 :     iter_fd = dup(lock.pindir_fd);
     226         [ -  + ]:         433 :     if (iter_fd < 0) {
     227         [ #  # ]:           0 :         bf_warn_r(-errno, "failed to dup pindir fd for staging sweep");
     228                 :             :         return;
     229                 :             :     }
     230                 :             : 
     231                 :         433 :     dir = fdopendir(iter_fd);
     232         [ -  + ]:         433 :     if (!dir) {
     233                 :           0 :         close(iter_fd);
     234         [ #  # ]:           0 :         bf_warn_r(-errno, "failed to fdopendir pindir for staging sweep");
     235                 :             :         return;
     236                 :             :     }
     237                 :             : 
     238         [ +  + ]:        1691 :     while ((entry = readdir(dir))) {
     239                 :        1258 :         _cleanup_close_ int stage_fd = -1;
     240                 :             : 
     241         [ +  - ]:        1258 :         if (!bf_strneq(entry->d_name, BF_LOCK_STAGING_PREFIX,
     242                 :             :                        sizeof(BF_LOCK_STAGING_PREFIX) - 1))
     243                 :        1258 :             continue;
     244                 :             : 
     245         [ #  # ]:           0 :         if (entry->d_type != DT_DIR && entry->d_type != DT_UNKNOWN)
     246                 :           0 :             continue;
     247                 :             : 
     248                 :           0 :         stage_fd = openat(lock.pindir_fd, entry->d_name, O_DIRECTORY);
     249         [ #  # ]:           0 :         if (stage_fd < 0)
     250                 :           0 :             continue;
     251                 :             : 
     252                 :             :         /* LOCK_NB: if the staging dir is still live, skip it. */
     253         [ #  # ]:           0 :         if (flock(stage_fd, LOCK_EX | LOCK_NB) < 0)
     254                 :           0 :             continue;
     255                 :             : 
     256         [ #  # ]:           0 :         if (bf_rmdir_at(lock.pindir_fd, entry->d_name, true)) {
     257         [ #  # ]:           0 :             bf_warn("failed to sweep orphan staging dir '%s'", entry->d_name);
     258                 :             :         } else {
     259         [ #  # ]:           0 :             bf_dbg("removed left-over staging directory '%s'", entry->d_name);
     260                 :             :         }
     261                 :             :     }
     262                 :             : }
     263                 :             : 
     264                 :         434 : int bf_ctx_setup(bool with_bpf_token, const char *bpffs_path, uint16_t verbose)
     265                 :             : {
     266                 :             :     int r;
     267                 :             : 
     268         [ +  + ]:         434 :     if (_bf_global_ctx)
     269         [ +  - ]:           1 :         return bf_err_r(-EBUSY, "context is already initialized");
     270                 :             : 
     271                 :         433 :     r = _bf_ctx_new(&_bf_global_ctx, with_bpf_token, bpffs_path, verbose);
     272         [ -  + ]:         433 :     if (r)
     273         [ #  # ]:           0 :         return bf_err_r(r, "failed to create new context");
     274                 :             : 
     275                 :             :     /* Reclaim any orphan staging directory left by a previous crash. */
     276                 :         433 :     _bf_ctx_sweep_staging();
     277                 :             : 
     278                 :         433 :     return 0;
     279                 :             : }
     280                 :             : 
     281                 :         433 : void bf_ctx_teardown(void)
     282                 :             : {
     283                 :         433 :     _bf_ctx_free(&_bf_global_ctx);
     284                 :         433 : }
     285                 :             : 
     286                 :        7112 : bool bf_ctx_is_setup(void)
     287                 :             : {
     288                 :        7112 :     return _bf_global_ctx != NULL;
     289                 :             : }
     290                 :             : 
     291                 :           0 : void bf_ctx_dump(prefix_t *prefix)
     292                 :             : {
     293         [ #  # ]:           0 :     if (!_bf_global_ctx)
     294                 :             :         return;
     295                 :             : 
     296                 :           0 :     _bf_ctx_dump(_bf_global_ctx, prefix);
     297                 :             : }
     298                 :             : 
     299                 :        7809 : int bf_ctx_token(void)
     300                 :             : {
     301         [ +  + ]:        7809 :     if (!_bf_global_ctx)
     302                 :             :         return -1;
     303                 :             : 
     304                 :        7808 :     return _bf_global_ctx->token_fd;
     305                 :             : }
     306                 :             : 
     307                 :        3444 : const struct bf_elfstub *bf_ctx_get_elfstub(enum bf_elfstub_id id)
     308                 :             : {
     309         [ +  + ]:        3444 :     if (!_bf_global_ctx)
     310                 :             :         return NULL;
     311                 :             : 
     312                 :        3443 :     return _bf_global_ctx->stubs[id];
     313                 :             : }
     314                 :             : 
     315                 :        7693 : bool bf_ctx_is_verbose(enum bf_verbose opt)
     316                 :             : {
     317         [ +  + ]:        7693 :     if (!_bf_global_ctx)
     318                 :             :         return false;
     319                 :             : 
     320                 :        7692 :     return _bf_global_ctx->verbose & BF_FLAG(opt);
     321                 :             : }
     322                 :             : 
     323                 :        7689 : const char *bf_ctx_get_bpffs_path(void)
     324                 :             : {
     325         [ +  + ]:        7689 :     if (!_bf_global_ctx)
     326                 :             :         return NULL;
     327                 :             : 
     328                 :        7687 :     return _bf_global_ctx->bpffs_path;
     329                 :             : }
        

Generated by: LCOV version 2.0-1