/* * Software Updater - client side * * Copyright © 2012-2016 Intel Corporation. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 2 or later of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: * Arjan van de Ven * Tim Pepper * Eric Lapuyade * Jim Kukunas * */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include "config.h" #include "swupd.h" /* Try to get a write lock region on the lock file. Returns: * >= 0 an fcntl region lock'd fd or exits with a positive error * code and a recommended course of action for user. */ int p_lockfile(void) { int lock_fd, ret; pid_t pid = getpid(); struct flock fl = { .l_type = F_WRLCK, .l_whence = SEEK_SET, .l_start = 0, .l_len = 0, .l_pid = pid, }; char *lockfile; string_or_die(&lockfile, "%s/swupd_lock", state_dir); /* open lock file */ lock_fd = open(lockfile, O_RDWR | O_CREAT | O_CLOEXEC, 0600); if (lock_fd < 0) { fprintf(stderr, "Error: failed to open %s: %s\n", lockfile, strerror(errno)); free_string(&lockfile); return -1; } free_string(&lockfile); /* try to get an advisory region lock for the file */ ret = fcntl(lock_fd, F_SETLK, &fl); if (ret == -1) { if ((errno == EAGAIN) || (errno == EACCES)) { ret = -EAGAIN; } fprintf(stderr, "Error: cannot acquire lock file. Another swupd process is already running.\n"); close(lock_fd); return ret; } else { /* speculatively dump our pid in the file, * that may be useful for debug */ ret = ftruncate(lock_fd, 0); ret = write(lock_fd, &pid, sizeof(pid)); /* our lock_fd represents the lock */ return lock_fd; } } /* closes lock fd and must not unlink lock file (else race allowed) */ void v_lockfile(int fd) { close(fd); }