lockfile.con commit commit_lock_file(): rollback lock file on failure to rename (1b1648f)
   1/*
   2 * Copyright (c) 2005, Junio C Hamano
   3 */
   4#include "cache.h"
   5#include "sigchain.h"
   6
   7/*
   8 * File write-locks as used by Git.
   9 *
  10 * For an overview of how to use the lockfile API, please see
  11 *
  12 *     Documentation/technical/api-lockfile.txt
  13 *
  14 * This module keeps track of all locked files in lock_file_list for
  15 * use at cleanup. This list and the lock_file objects that comprise
  16 * it must be kept in self-consistent states at all time, because the
  17 * program can be interrupted any time by a signal, in which case the
  18 * signal handler will walk through the list attempting to clean up
  19 * any open lock files.
  20 *
  21 * A lockfile is owned by the process that created it. The lock_file
  22 * object has an "owner" field that records its owner. This field is
  23 * used to prevent a forked process from closing a lockfile created by
  24 * its parent.
  25 *
  26 * A lock_file object can be in several states:
  27 *
  28 * - Uninitialized.  In this state the object's on_list field must be
  29 *   zero but the rest of its contents need not be initialized.  As
  30 *   soon as the object is used in any way, it is irrevocably
  31 *   registered in the lock_file_list, and on_list is set.
  32 *
  33 * - Locked, lockfile open (after hold_lock_file_for_update(),
  34 *   hold_lock_file_for_append(), or reopen_lock_file()). In this
  35 *   state, the lockfile exists, filename holds the filename of the
  36 *   lockfile, fd holds a file descriptor open for writing to the
  37 *   lockfile, and owner holds the PID of the process that locked the
  38 *   file.
  39 *
  40 * - Locked, lockfile closed (after successful close_lock_file()).
  41 *   Same as the previous state, except that the lockfile is closed
  42 *   and fd is -1.
  43 *
  44 * - Unlocked (after commit_lock_file(), rollback_lock_file(), a
  45 *   failed attempt to lock, or a failed close_lock_file()). In this
  46 *   state, filename[0] == '\0' and fd is -1. The object is left
  47 *   registered in the lock_file_list, and on_list is set.
  48 */
  49
  50static struct lock_file *lock_file_list;
  51
  52static void remove_lock_file(void)
  53{
  54        pid_t me = getpid();
  55
  56        while (lock_file_list) {
  57                if (lock_file_list->owner == me)
  58                        rollback_lock_file(lock_file_list);
  59                lock_file_list = lock_file_list->next;
  60        }
  61}
  62
  63static void remove_lock_file_on_signal(int signo)
  64{
  65        remove_lock_file();
  66        sigchain_pop(signo);
  67        raise(signo);
  68}
  69
  70/*
  71 * p = absolute or relative path name
  72 *
  73 * Return a pointer into p showing the beginning of the last path name
  74 * element.  If p is empty or the root directory ("/"), just return p.
  75 */
  76static char *last_path_elm(char *p)
  77{
  78        /* r starts pointing to null at the end of the string */
  79        char *r = strchr(p, '\0');
  80
  81        if (r == p)
  82                return p; /* just return empty string */
  83
  84        r--; /* back up to last non-null character */
  85
  86        /* back up past trailing slashes, if any */
  87        while (r > p && *r == '/')
  88                r--;
  89
  90        /*
  91         * then go backwards until I hit a slash, or the beginning of
  92         * the string
  93         */
  94        while (r > p && *(r-1) != '/')
  95                r--;
  96        return r;
  97}
  98
  99
 100/* We allow "recursive" symbolic links. Only within reason, though */
 101#define MAXDEPTH 5
 102
 103/*
 104 * p = path that may be a symlink
 105 * s = full size of p
 106 *
 107 * If p is a symlink, attempt to overwrite p with a path to the real
 108 * file or directory (which may or may not exist), following a chain of
 109 * symlinks if necessary.  Otherwise, leave p unmodified.
 110 *
 111 * This is a best-effort routine.  If an error occurs, p will either be
 112 * left unmodified or will name a different symlink in a symlink chain
 113 * that started with p's initial contents.
 114 *
 115 * Always returns p.
 116 */
 117
 118static char *resolve_symlink(char *p, size_t s)
 119{
 120        int depth = MAXDEPTH;
 121
 122        while (depth--) {
 123                char link[PATH_MAX];
 124                int link_len = readlink(p, link, sizeof(link));
 125                if (link_len < 0) {
 126                        /* not a symlink anymore */
 127                        return p;
 128                }
 129                else if (link_len < sizeof(link))
 130                        /* readlink() never null-terminates */
 131                        link[link_len] = '\0';
 132                else {
 133                        warning("%s: symlink too long", p);
 134                        return p;
 135                }
 136
 137                if (is_absolute_path(link)) {
 138                        /* absolute path simply replaces p */
 139                        if (link_len < s)
 140                                strcpy(p, link);
 141                        else {
 142                                warning("%s: symlink too long", p);
 143                                return p;
 144                        }
 145                } else {
 146                        /*
 147                         * link is a relative path, so I must replace the
 148                         * last element of p with it.
 149                         */
 150                        char *r = (char *)last_path_elm(p);
 151                        if (r - p + link_len < s)
 152                                strcpy(r, link);
 153                        else {
 154                                warning("%s: symlink too long", p);
 155                                return p;
 156                        }
 157                }
 158        }
 159        return p;
 160}
 161
 162/* Make sure errno contains a meaningful value on error */
 163static int lock_file(struct lock_file *lk, const char *path, int flags)
 164{
 165        /*
 166         * subtract LOCK_SUFFIX_LEN from size to make sure there's
 167         * room for adding ".lock" for the lock file name:
 168         */
 169        static const size_t max_path_len = sizeof(lk->filename) -
 170                                           LOCK_SUFFIX_LEN;
 171
 172        if (!lock_file_list) {
 173                /* One-time initialization */
 174                sigchain_push_common(remove_lock_file_on_signal);
 175                atexit(remove_lock_file);
 176        }
 177
 178        if (!lk->on_list) {
 179                /* Initialize *lk and add it to lock_file_list: */
 180                lk->fd = -1;
 181                lk->owner = 0;
 182                lk->filename[0] = 0;
 183                lk->next = lock_file_list;
 184                lock_file_list = lk;
 185                lk->on_list = 1;
 186        }
 187
 188        if (strlen(path) >= max_path_len) {
 189                errno = ENAMETOOLONG;
 190                return -1;
 191        }
 192        strcpy(lk->filename, path);
 193        if (!(flags & LOCK_NODEREF))
 194                resolve_symlink(lk->filename, max_path_len);
 195        strcat(lk->filename, LOCK_SUFFIX);
 196        lk->fd = open(lk->filename, O_RDWR | O_CREAT | O_EXCL, 0666);
 197        if (lk->fd < 0) {
 198                lk->filename[0] = 0;
 199                return -1;
 200        }
 201        lk->owner = getpid();
 202        if (adjust_shared_perm(lk->filename)) {
 203                int save_errno = errno;
 204                error("cannot fix permission bits on %s", lk->filename);
 205                rollback_lock_file(lk);
 206                errno = save_errno;
 207                return -1;
 208        }
 209        return lk->fd;
 210}
 211
 212void unable_to_lock_message(const char *path, int err, struct strbuf *buf)
 213{
 214        if (err == EEXIST) {
 215                strbuf_addf(buf, "Unable to create '%s.lock': %s.\n\n"
 216                    "If no other git process is currently running, this probably means a\n"
 217                    "git process crashed in this repository earlier. Make sure no other git\n"
 218                    "process is running and remove the file manually to continue.",
 219                            absolute_path(path), strerror(err));
 220        } else
 221                strbuf_addf(buf, "Unable to create '%s.lock': %s",
 222                            absolute_path(path), strerror(err));
 223}
 224
 225int unable_to_lock_error(const char *path, int err)
 226{
 227        struct strbuf buf = STRBUF_INIT;
 228
 229        unable_to_lock_message(path, err, &buf);
 230        error("%s", buf.buf);
 231        strbuf_release(&buf);
 232        return -1;
 233}
 234
 235NORETURN void unable_to_lock_die(const char *path, int err)
 236{
 237        struct strbuf buf = STRBUF_INIT;
 238
 239        unable_to_lock_message(path, err, &buf);
 240        die("%s", buf.buf);
 241}
 242
 243/* This should return a meaningful errno on failure */
 244int hold_lock_file_for_update(struct lock_file *lk, const char *path, int flags)
 245{
 246        int fd = lock_file(lk, path, flags);
 247        if (fd < 0 && (flags & LOCK_DIE_ON_ERROR))
 248                unable_to_lock_die(path, errno);
 249        return fd;
 250}
 251
 252int hold_lock_file_for_append(struct lock_file *lk, const char *path, int flags)
 253{
 254        int fd, orig_fd;
 255
 256        fd = lock_file(lk, path, flags);
 257        if (fd < 0) {
 258                if (flags & LOCK_DIE_ON_ERROR)
 259                        unable_to_lock_die(path, errno);
 260                return fd;
 261        }
 262
 263        orig_fd = open(path, O_RDONLY);
 264        if (orig_fd < 0) {
 265                if (errno != ENOENT) {
 266                        if (flags & LOCK_DIE_ON_ERROR)
 267                                die("cannot open '%s' for copying", path);
 268                        rollback_lock_file(lk);
 269                        return error("cannot open '%s' for copying", path);
 270                }
 271        } else if (copy_fd(orig_fd, fd)) {
 272                if (flags & LOCK_DIE_ON_ERROR)
 273                        exit(128);
 274                rollback_lock_file(lk);
 275                return -1;
 276        }
 277        return fd;
 278}
 279
 280int close_lock_file(struct lock_file *lk)
 281{
 282        int fd = lk->fd;
 283
 284        if (fd < 0)
 285                return 0;
 286
 287        lk->fd = -1;
 288        if (close(fd)) {
 289                int save_errno = errno;
 290                rollback_lock_file(lk);
 291                errno = save_errno;
 292                return -1;
 293        }
 294        return 0;
 295}
 296
 297int reopen_lock_file(struct lock_file *lk)
 298{
 299        if (0 <= lk->fd)
 300                die(_("BUG: reopen a lockfile that is still open"));
 301        if (!lk->filename[0])
 302                die(_("BUG: reopen a lockfile that has been committed"));
 303        lk->fd = open(lk->filename, O_WRONLY);
 304        return lk->fd;
 305}
 306
 307int commit_lock_file(struct lock_file *lk)
 308{
 309        char result_file[PATH_MAX];
 310
 311        if (!lk->filename[0])
 312                die("BUG: attempt to commit unlocked object");
 313
 314        if (close_lock_file(lk))
 315                return -1;
 316
 317        strcpy(result_file, lk->filename);
 318        /* remove ".lock": */
 319        result_file[strlen(result_file) - LOCK_SUFFIX_LEN] = 0;
 320
 321        if (rename(lk->filename, result_file)) {
 322                int save_errno = errno;
 323                rollback_lock_file(lk);
 324                errno = save_errno;
 325                return -1;
 326        }
 327
 328        lk->filename[0] = 0;
 329        return 0;
 330}
 331
 332int hold_locked_index(struct lock_file *lk, int die_on_error)
 333{
 334        return hold_lock_file_for_update(lk, get_index_file(),
 335                                         die_on_error
 336                                         ? LOCK_DIE_ON_ERROR
 337                                         : 0);
 338}
 339
 340void rollback_lock_file(struct lock_file *lk)
 341{
 342        if (!lk->filename[0])
 343                return;
 344
 345        if (!close_lock_file(lk)) {
 346                unlink_or_warn(lk->filename);
 347                lk->filename[0] = 0;
 348        }
 349}