1 /* $OpenBSD: mmap-sysctl-copyin.c,v 1.3 2021/12/13 16:56:50 deraadt Exp $ */ 2 3 #include <sys/types.h> 4 #include <sys/mman.h> 5 #include <sys/queue.h> 6 #include <sys/socket.h> 7 #include <sys/sysctl.h> 8 9 #include <netinet/in.h> 10 #include <netinet/tcp.h> 11 #include <netinet/tcp_seq.h> 12 #include <netinet/tcp_timer.h> 13 #include <netinet/tcp_var.h> 14 15 #include <err.h> 16 #include <fcntl.h> 17 #include <stdlib.h> 18 #include <limits.h> 19 #include <stdio.h> 20 #include <string.h> 21 #include <unistd.h> 22 23 #define FILE "sysctl-net.inet.tcp.always_keepalive" 24 #define CLIENT "/mnt/regress-nfs-client" 25 #define SERVER "/mnt/regress-nfs-server" 26 27 int 28 main(void) 29 { 30 char *p, path[PATH_MAX]; 31 int mib[] = { CTL_NET, PF_INET, IPPROTO_TCP, TCPCTL_ALWAYS_KEEPALIVE }; 32 u_int miblen = sizeof(mib) / sizeof(mib[0]); 33 int fd, val; 34 size_t len; 35 36 /* 37 * Get current value of sysctl net.inet.tcp.always_keepalive 38 * and write it into a file on the NFS server. 39 */ 40 snprintf(path, sizeof(path), "%s/%s", SERVER, FILE); 41 if ((fd = open(path, O_WRONLY|O_CREAT|O_TRUNC, 0777)) == -1) 42 err(1, "open write '%s'", path); 43 len = sizeof(int); 44 if (sysctl(mib, miblen, &val, &len, NULL, 0) == -1) 45 err(1, "sysctl get keepalive"); 46 if (len != sizeof(int)) 47 errx(1, "len is not %zu: %zu", sizeof(int), len); 48 if (write(fd, &val, len) == -1) 49 err(1, "write"); 50 if (close(fd) == -1) 51 err(1, "close write"); 52 53 /* 54 * Map file on NFS client and read value to 55 * sysctl net.inet.tcp.always_keepalive. 56 */ 57 snprintf(path, sizeof(path), "%s/%s", CLIENT, FILE); 58 if ((fd = open(path, O_RDWR)) == -1) 59 err(1, "open mmap '%s'", path); 60 p = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); 61 if (p == MAP_FAILED) 62 err(1, "mmap"); 63 if (sysctl(mib, miblen, NULL, 0, p, sizeof(int)) == -1) 64 err(1, "sysctl set keepalive"); 65 if (close(fd) == -1) 66 err(1, "close mmap"); 67 68 return (0); 69 } 70