// retoor #include "socket_utils.h" #include "logging.h" #include #include #include #include #include #include int socket_set_non_blocking(int fd) { int flags = fcntl(fd, F_GETFL, 0); if (flags < 0) { log_error("fcntl F_GETFL failed"); return -1; } if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) { log_error("fcntl F_SETFL failed"); return -1; } return 0; } void socket_set_tcp_keepalive(int fd) { int yes = 1; if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes)) < 0) { log_debug("setsockopt SO_KEEPALIVE failed for fd %d: %s", fd, strerror(errno)); } int idle = 60; if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(idle)) < 0) { log_debug("setsockopt TCP_KEEPIDLE failed for fd %d: %s", fd, strerror(errno)); } int interval = 10; if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &interval, sizeof(interval)) < 0) { log_debug("setsockopt TCP_KEEPINTVL failed for fd %d: %s", fd, strerror(errno)); } int maxpkt = 6; if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &maxpkt, sizeof(maxpkt)) < 0) { log_debug("setsockopt TCP_KEEPCNT failed for fd %d: %s", fd, strerror(errno)); } } void socket_set_tcp_nodelay(int fd) { int yes = 1; if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) < 0) { log_debug("setsockopt TCP_NODELAY failed for fd %d: %s", fd, strerror(errno)); } } #ifdef TCP_QUICKACK void socket_set_tcp_quickack(int fd) { int yes = 1; if (setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, &yes, sizeof(yes)) < 0) { log_debug("setsockopt TCP_QUICKACK failed for fd %d: %s", fd, strerror(errno)); } } #else void socket_set_tcp_quickack(int fd) { (void)fd; } #endif void socket_optimize(int fd, int is_upstream) { socket_set_tcp_nodelay(fd); socket_set_tcp_keepalive(fd); #ifdef TCP_QUICKACK if (!is_upstream) { socket_set_tcp_quickack(fd); } #endif int sndbuf = is_upstream ? 262144 : 131072; int rcvbuf = is_upstream ? 524288 : 131072; setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf)); setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)); }