github.com/aporeto-inc/trireme-lib@v10.358.0+incompatible/controller/internal/enforcer/utils/nsenter/nsenter.c (about)

     1  // +build linux !darwin
     2  // +build !windows
     3  
     4  #define _GNU_SOURCE
     5  #include <errno.h>
     6  #include <fcntl.h>
     7  #include <sched.h>
     8  #include <stdio.h>
     9  #include <stdlib.h>
    10  #include <string.h>
    11  #include <sys/types.h>
    12  #include <sys/stat.h>
    13  #include <unistd.h>
    14  
    15  #define STRBUF_SIZE     128
    16  void nsexec(void) {
    17  
    18    int fd = 0;
    19    char path[STRBUF_SIZE*2]={0};
    20    char msg[STRBUF_SIZE*4];
    21    char mountpoint[STRBUF_SIZE] = {0};
    22    char *container_pid_env = getenv("TRIREME_ENV_CONTAINER_PID");
    23    char *netns_path_env = getenv("TRIREME_ENV_NS_PATH");
    24    char *proc_mountpoint = getenv("TRIREME_ENV_PROC_MOUNTPOINT");
    25    if(container_pid_env == NULL){
    26      // We are not running as remote enforcer
    27      setenv("TRIREME_ENV_NSENTER_LOGS", "no container pid", 1);
    28      return;
    29    }
    30    if(netns_path_env == NULL){
    31      // This means the PID Needs to be used to determine the NetNsPath.
    32      if(proc_mountpoint == NULL){
    33        strncpy(mountpoint, "/proc", strlen("/proc")+1);
    34      }else{
    35        strncpy(mountpoint, proc_mountpoint, STRBUF_SIZE-1);
    36      }
    37      // Setup proc symlink
    38      snprintf(path, sizeof(path), "%s/%s/ns/net", mountpoint, container_pid_env);
    39    } else {
    40      // We use the env variable as the Path.
    41      strncpy(path, netns_path_env, STRBUF_SIZE);
    42    }
    43  
    44    // Setup FD to symlink
    45    fd = open(path, O_RDONLY);
    46    if(fd < 0) {
    47      snprintf(msg, sizeof(msg), "path:%s fd:%d", path, fd);
    48      setenv("TRIREME_ENV_NSENTER_ERROR_STATE",strerror(-ENOENT), 1);
    49      setenv("TRIREME_ENV_NSENTER_LOGS", path, 1);
    50      return;
    51    }
    52  
    53    // Set namespace
    54    int retval =syscall(308,fd,CLONE_NEWNET);
    55    snprintf(msg, sizeof(msg), "path:%s fd:%d retval:%d", path, fd, retval);
    56    setenv("TRIREME_ENV_NSENTER_LOGS",msg,1);
    57    if(retval < 0){
    58      setenv("TRIREME_ENV_NSENTER_ERROR_STATE",strerror(errno),1); 		
    59    }
    60  }