test_cgrp2_sock2.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // SPDX-License-Identifier: GPL-2.0
  2. /* eBPF example program:
  3. *
  4. * - Loads eBPF program
  5. *
  6. * The eBPF program loads a filter from file and attaches the
  7. * program to a cgroup using BPF_PROG_ATTACH
  8. */
  9. #define _GNU_SOURCE
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <stddef.h>
  13. #include <string.h>
  14. #include <unistd.h>
  15. #include <assert.h>
  16. #include <errno.h>
  17. #include <fcntl.h>
  18. #include <net/if.h>
  19. #include <linux/bpf.h>
  20. #include <bpf/bpf.h>
  21. #include <bpf/libbpf.h>
  22. #include "bpf_insn.h"
  23. static int usage(const char *argv0)
  24. {
  25. printf("Usage: %s cg-path filter-path [filter-id]\n", argv0);
  26. return EXIT_FAILURE;
  27. }
  28. int main(int argc, char **argv)
  29. {
  30. int cg_fd, err, ret = EXIT_FAILURE, filter_id = 0, prog_cnt = 0;
  31. const char *link_pin_path = "/sys/fs/bpf/test_cgrp2_sock2";
  32. struct bpf_link *link = NULL;
  33. struct bpf_program *progs[2];
  34. struct bpf_program *prog;
  35. struct bpf_object *obj;
  36. if (argc < 3)
  37. return usage(argv[0]);
  38. if (argc > 3)
  39. filter_id = atoi(argv[3]);
  40. cg_fd = open(argv[1], O_DIRECTORY | O_RDONLY);
  41. if (cg_fd < 0) {
  42. printf("Failed to open cgroup path: '%s'\n", strerror(errno));
  43. return ret;
  44. }
  45. obj = bpf_object__open_file(argv[2], NULL);
  46. if (libbpf_get_error(obj)) {
  47. printf("ERROR: opening BPF object file failed\n");
  48. return ret;
  49. }
  50. bpf_object__for_each_program(prog, obj) {
  51. progs[prog_cnt] = prog;
  52. prog_cnt++;
  53. }
  54. if (filter_id >= prog_cnt) {
  55. printf("Invalid program id; program not found in file\n");
  56. goto cleanup;
  57. }
  58. /* load BPF program */
  59. if (bpf_object__load(obj)) {
  60. printf("ERROR: loading BPF object file failed\n");
  61. goto cleanup;
  62. }
  63. link = bpf_program__attach_cgroup(progs[filter_id], cg_fd);
  64. if (libbpf_get_error(link)) {
  65. printf("ERROR: bpf_program__attach failed\n");
  66. link = NULL;
  67. goto cleanup;
  68. }
  69. err = bpf_link__pin(link, link_pin_path);
  70. if (err < 0) {
  71. printf("ERROR: bpf_link__pin failed: %d\n", err);
  72. goto cleanup;
  73. }
  74. ret = EXIT_SUCCESS;
  75. cleanup:
  76. bpf_link__destroy(link);
  77. bpf_object__close(obj);
  78. return ret;
  79. }