1 /* 2 * Copyright (C) 2026 Daniel Golle <daniel@makrotopia.org> 3 * 4 * This program is free software; you can redistribute it and/or modify 5 * it under the terms of the GNU Lesser General Public License version 2.1 6 * as published by the Free Software Foundation 7 * 8 * This program is distributed in the hope that it will be useful, 9 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * GNU General Public License for more details. 12 */ 13 14 #ifndef __STATE_FILE_H 15 #define __STATE_FILE_H 16 17 #include <errno.h> 18 #include <limits.h> 19 #include <stdio.h> 20 #include <stdlib.h> 21 #include <sys/stat.h> 22 #include <sys/types.h> 23 #include <unistd.h> 24 25 static inline int fd_write_all(int fd, const char *buf, size_t len) 26 { 27 ssize_t ret; 28 29 while (len) { 30 ret = write(fd, buf, len); 31 if (ret < 0) 32 return errno; 33 34 buf += ret; 35 len -= ret; 36 } 37 38 return 0; 39 } 40 41 static inline int file_write_atomic(const char *path, const char *buf, size_t len, mode_t mode) 42 { 43 char tmp[PATH_MAX]; 44 int fd, err; 45 46 if (snprintf(tmp, sizeof(tmp), "%s.XXXXXX", path) >= (int)sizeof(tmp)) 47 return -ENAMETOOLONG; 48 49 fd = mkstemp(tmp); 50 if (fd < 0) 51 return -errno; 52 53 err = 0; 54 if (fchmod(fd, mode)) 55 err = errno; 56 57 if (!err) 58 err = fd_write_all(fd, buf, len); 59 60 if (close(fd) && !err) 61 err = errno; 62 63 if (!err && rename(tmp, path)) 64 err = errno; 65 66 if (!err) 67 return 0; 68 69 unlink(tmp); 70 71 return -err; 72 } 73 74 #endif 75
This page was automatically generated by LXR 0.3.1. • OpenWrt