Coverage Report

Created: 2026-08-13 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gnupg/common/dotlock.c
Line
Count
Source
1
/* dotlock.c - dotfile locking
2
 * Copyright (C) 1998, 2000, 2001, 2003, 2004,
3
 *               2005, 2006, 2008, 2010, 2011 Free Software Foundation, Inc.
4
 *
5
 * This file is part of GnuPG.
6
 *
7
 * GnuPG is free software; you can redistribute and/or modify this
8
 * part of GnuPG under the terms of either
9
 *
10
 *   - the GNU Lesser General Public License as published by the Free
11
 *     Software Foundation; either version 3 of the License, or (at
12
 *     your option) any later version.
13
 *
14
 * or
15
 *
16
 *   - the GNU General Public License as published by the Free
17
 *     Software Foundation; either version 2 of the License, or (at
18
 *     your option) any later version.
19
 *
20
 * or both in parallel, as here.
21
 *
22
 * GnuPG is distributed in the hope that it will be useful, but
23
 * WITHOUT ANY WARRANTY; without even the implied warranty of
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25
 * General Public License for more details.
26
 *
27
 * You should have received a copies of the GNU General Public License
28
 * and the GNU Lesser General Public License along with this program;
29
 * if not, see <https://www.gnu.org/licenses/>.
30
 *
31
 * ALTERNATIVELY, this file may be distributed under the terms of the
32
 * following license, in which case the provisions of this license are
33
 * required INSTEAD OF the GNU Lesser General License or the GNU
34
 * General Public License. If you wish to allow use of your version of
35
 * this file only under the terms of the GNU Lesser General License or
36
 * the GNU General Public License, and not to allow others to use your
37
 * version of this file under the terms of the following license,
38
 * indicate your decision by deleting this paragraph and the license
39
 * below.
40
 *
41
 * Redistribution and use in source and binary forms, with or without
42
 * modification, are permitted provided that the following conditions
43
 * are met:
44
 *
45
 * 1. Redistributions of source code must retain the above copyright
46
 *    notice, and the entire permission notice in its entirety,
47
 *    including the disclaimer of warranties.
48
 * 2. Redistributions in binary form must reproduce the above copyright
49
 *    notice, this list of conditions and the following disclaimer in the
50
 *    documentation and/or other materials provided with the distribution.
51
 * 3. The name of the author may not be used to endorse or promote
52
 *    products derived from this software without specific prior
53
 *    written permission.
54
 *
55
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
56
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
57
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
58
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
59
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
60
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
61
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
63
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
65
 * OF THE POSSIBILITY OF SUCH DAMAGE.
66
 */
67
68
/*
69
   Overview:
70
   =========
71
72
   This module implements advisory file locking in a portable way.
73
   Due to the problems with POSIX fcntl locking a separate lock file
74
   is used.  It would be possible to use fcntl locking on this lock
75
   file and thus avoid the weird auto unlock bug of POSIX while still
76
   having an unproved better performance of fcntl locking.  However
77
   there are still problems left, thus we resort to use a hardlink
78
   which has the well defined property that a link call will fail if
79
   the target file already exists.
80
81
   Given that hardlinks are also available on NTFS file systems since
82
   Windows XP; it will be possible to enhance this module to use
83
   hardlinks even on Windows and thus allow Windows and Posix clients
84
   to use locking on the same directory.  This is not yet implemented;
85
   instead we use a lockfile on Windows along with W32 style file
86
   locking.
87
88
   On FAT file systems hardlinks are not supported.  Thus this method
89
   does not work.  Our solution is to use a O_EXCL locking instead.
90
   Querying the type of the file system is not easy to do in a
91
   portable way (e.g. Linux has a statfs, BSDs have a the same call
92
   but using different structures and constants).  What we do instead
93
   is to check at runtime whether link(2) works for a specific lock
94
   file.
95
96
97
   How to use:
98
   ===========
99
100
   At program initialization time, the module should be explicitly
101
   initialized:
102
103
      dotlock_create (NULL, 0);
104
105
   This installs an atexit handler and may also initialize mutex etc.
106
   It is optional for non-threaded applications.  Only the first call
107
   has an effect.  This needs to be done before any extra threads are
108
   started.
109
110
   To create a lock file (which  prepares it but does not take the
111
   lock) you do:
112
113
     dotlock_t h
114
115
     h = dotlock_create (fname, 0);
116
     if (!h)
117
       error ("error creating lock file: %s\n", strerror (errno));
118
119
   It is important to handle the error.  For example on a read-only
120
   file system a lock can't be created (but is usually not needed).
121
   FNAME is the file you want to lock; the actual lockfile is that
122
   name with the suffix ".lock" appended.  On success a handle to be
123
   used with the other functions is returned or NULL on error.  Note
124
   that the handle shall only be used by one thread at a time.  This
125
   function creates a unique file temporary file (".#lk*") in the same
126
   directory as FNAME and returns a handle for further operations.
127
   The module keeps track of these unique files so that they will be
128
   unlinked using the atexit handler.  If you don't need the lock file
129
   anymore, you may also explicitly remove it with a call to:
130
131
     dotlock_destroy (h);
132
133
   To actually lock the file, you use:
134
135
     if (dotlock_take (h, -1))
136
       error ("error taking lock: %s\n", strerror (errno));
137
138
   This function will wait until the lock is acquired.  If an
139
   unexpected error occurs if will return non-zero and set ERRNO.  If
140
   you pass (0) instead of (-1) the function does not wait in case the
141
   file is already locked but returns -1 and sets ERRNO to EACCES.
142
   Any other positive value for the second parameter is considered a
143
   timeout value in milliseconds.
144
145
   To release the lock you call:
146
147
     if (dotlock_release (h))
148
       error ("error releasing lock: %s\n", strerror (errno));
149
150
   or, if the lock file is not anymore needed, you may just call
151
   dotlock_destroy.  However dotlock_release does some extra checks
152
   before releasing the lock and prints diagnostics to help detecting
153
   bugs.
154
155
   If you want to explicitly destroy all lock files you may call
156
157
     dotlock_remove_lockfiles ();
158
159
   which is the core of the installed atexit handler.  In case your
160
   application wants to disable locking completely it may call
161
162
     dotlock_disable ()
163
164
   before any locks are created.
165
166
   There are two convenience functions to store an integer (e.g. a
167
   file descriptor) value with the handle:
168
169
     void dotlock_set_fd (dotlock_t h, int fd);
170
     int  dotlock_get_fd (dotlock_t h);
171
172
   If nothing has been stored dotlock_get_fd returns -1.
173
174
175
176
   How to build:
177
   =============
178
179
   This module was originally developed for GnuPG but later changed to
180
   allow its use without any GnuPG dependency.  If you want to use it
181
   with you application you may simply use it and it should figure out
182
   most things automagically.
183
184
   You may use the common config.h file to pass macros, but take care
185
   to pass -DHAVE_CONFIG_H to the compiler.  Macros used by this
186
   module are:
187
188
     DOTLOCK_USE_PTHREAD  - Define if POSIX threads are in use.
189
190
     DOTLOCK_EXT_SYM_PREFIX - Prefix all external symbols with the
191
                              string to which this macro evaluates.
192
193
     GNUPG_MAJOR_VERSION - Defined when used by GnuPG.
194
195
     HAVE_DOSISH_SYSTEM  - Defined for Windows etc.  Will be
196
                           automatically defined if a the target is
197
                           Windows.
198
199
     HAVE_POSIX_SYSTEM   - Internally defined to !HAVE_DOSISH_SYSTEM.
200
201
     HAVE_SIGNAL_H       - Should be defined on Posix systems.  If config.h
202
                           is not used defaults to defined.
203
204
     DIRSEP_C            - Separation character for file name parts.
205
                           Usually not redefined.
206
207
     EXTSEP_S            - Separation string for file name suffixes.
208
                           Usually not redefined.
209
210
   Note that there is a test program t-dotlock which has compile
211
   instructions at its end.  At least for SMBFS and CIFS it is
212
   important that 64 bit versions of stat are used; most programming
213
   environments do this these days, just in case you want to compile
214
   it on the command line, remember to pass -D_FILE_OFFSET_BITS=64
215
216
217
   Bugs:
218
   =====
219
220
   On Windows this module is not yet thread-safe.
221
222
223
   Miscellaneous notes:
224
   ====================
225
226
   On hardlinks:
227
   - Hardlinks are supported under Windows with NTFS since XP/Server2003.
228
   - In Linux 2.6.33 both SMBFS and CIFS seem to support hardlinks.
229
   - NFS supports hard links.  But there are solvable problems.
230
   - FAT does not support links
231
232
   On the file locking API:
233
   - CIFS on Linux 2.6.33 supports several locking methods.
234
     SMBFS seems not to support locking.  No closer checks done.
235
   - NFS supports Posix locks.  flock is emulated in the server.
236
     However there are a couple of problems; see below.
237
   - FAT does not support locks.
238
   - An advantage of fcntl locking is that R/W locks can be
239
     implemented which is not easy with a straight lock file.
240
241
   On O_EXCL:
242
   - Does not work reliable on NFS
243
   - Should work on CIFS and SMBFS but how can we delete lockfiles?
244
245
   On NFS problems:
246
   - Locks vanish if the server crashes and reboots.
247
   - Client crashes keep the lock in the server until the client
248
     re-connects.
249
   - Communication problems may return unreliable error codes.  The
250
     MUA Postfix's workaround is to compare the link count after
251
     seeing an error for link.  However that gives a race.  If using a
252
     unique file to link to a lockfile and using stat to check the
253
     link count instead of looking at the error return of link(2) is
254
     the best solution.
255
   - O_EXCL seems to have a race and may re-create a file anyway.
256
257
*/
258
259
#ifdef HAVE_CONFIG_H
260
# include <config.h>
261
#endif
262
263
/* Some quick replacements for stuff we usually expect to be defined
264
   in config.h.  Define HAVE_POSIX_SYSTEM for better readability. */
265
#if !defined (HAVE_DOSISH_SYSTEM) && defined(_WIN32)
266
# define HAVE_DOSISH_SYSTEM 1
267
#endif
268
#if !defined (HAVE_DOSISH_SYSTEM) && !defined (HAVE_POSIX_SYSTEM)
269
# define HAVE_POSIX_SYSTEM 1
270
#endif
271
272
/* With no config.h assume that we have sitgnal.h.  */
273
#if !defined (HAVE_CONFIG_H) && defined (HAVE_POSIX_SYSTEM)
274
# define HAVE_SIGNAL_H 1
275
#endif
276
277
/* Standard headers.  */
278
#include <stdlib.h>
279
#include <stdio.h>
280
#include <string.h>
281
#include <errno.h>
282
#include <ctype.h>
283
#include <errno.h>
284
#include <unistd.h>
285
#ifdef  HAVE_DOSISH_SYSTEM
286
# define WIN32_LEAN_AND_MEAN  /* We only need the OS core stuff.  */
287
# include <windows.h>
288
#else
289
# include <sys/types.h>
290
# include <sys/stat.h>
291
# include <sys/utsname.h>
292
# include <dirent.h>
293
#endif
294
#include <sys/types.h>
295
#include <sys/time.h>
296
#include <sys/stat.h>
297
#include <fcntl.h>
298
#ifdef HAVE_SIGNAL_H
299
# include <signal.h>
300
#endif
301
#ifdef DOTLOCK_USE_PTHREAD
302
# include <pthread.h>
303
#endif
304
305
#ifdef GNUPG_MAJOR_VERSION
306
# include "util.h"
307
# include "common-defs.h"
308
# include "stringhelp.h"  /* For stpcpy and w32_strerror. */
309
#endif
310
311
#include "dotlock.h"
312
313
314
/* Define constants for file name construction.  */
315
#if !defined(DIRSEP_C) && !defined(EXTSEP_S)
316
# ifdef HAVE_DOSISH_SYSTEM
317
#  define DIRSEP_C '\\'
318
#  define EXTSEP_S "."
319
#else
320
#  define DIRSEP_C '/'
321
#  define EXTSEP_S "."
322
# endif
323
#endif
324
325
/* In GnuPG we use wrappers around the malloc functions.  If they are
326
   not defined we assume that this code is used outside of GnuPG and
327
   fall back to the regular malloc functions.  */
328
#ifndef xtrymalloc
329
# define xtrymalloc(a)     malloc ((a))
330
# define xtrycalloc(a,b)   calloc ((a), (b))
331
# define xfree(a)    free ((a))
332
#endif
333
334
/* Wrapper to set ERRNO.  */
335
#ifdef GPG_ERROR_VERSION
336
3
#  define my_set_errno(e)  gpg_err_set_errno ((e))
337
#else
338
#  define my_set_errno(e)  do { errno = (e); } while (0)
339
#endif
340
341
/* Gettext macro replacement.  */
342
#ifndef _
343
0
# define _(a) (a)
344
#endif
345
346
#ifdef GNUPG_MAJOR_VERSION
347
# define my_fatal_0(a)      default_msg_cb (NULL, DOTLOCK_FATAL, (a))
348
#else
349
# define my_fatal_0(a)      do { fprintf (stderr,(a)); fflush (stderr); \
350
                                 abort (); } while (0)
351
#endif
352
353
354
355
356

357
/* The object describing a lock.  */
358
struct dotlock_handle
359
{
360
  struct dotlock_handle *next;
361
  char *lockname;             /* Name of the actual lockfile.          */
362
  unsigned int locked     :1; /* Lock status.                          */
363
  unsigned int disable    :1; /* If true, locking is disabled.         */
364
  unsigned int use_o_excl :1; /* Use open (O_EXCL) for locking.        */
365
  unsigned int by_parent  :1; /* Parent does the locking.              */
366
  unsigned int no_write   :1; /* No write to the lockfile.             */
367
368
  int extra_fd;              /* A place for the caller to store an FD.  */
369
370
  int (*msg_cb)(dotlock_t, void *,
371
                enum dotlock_reasons reason,
372
                const char *, ...);
373
  void *msg_cb_arg;
374
375
376
#ifdef HAVE_DOSISH_SYSTEM
377
  HANDLE lockhd;       /* The W32 handle of the lock file.      */
378
#else /*!HAVE_DOSISH_SYSTEM */
379
  char *tname;         /* Name of the lockfile template.        */
380
  size_t nodename_off; /* Offset in TNAME of the nodename part. */
381
  size_t nodename_len; /* Length of the nodename part.          */
382
#endif /*!HAVE_DOSISH_SYSTEM */
383
};
384
385
386
/* A list of all lock handles.  The volatile attribute might help
387
   if used in an atexit handler.  Note that [UN]LOCK_all_lockfiles
388
   must not change ERRNO. */
389
static volatile dotlock_t all_lockfiles;
390
#ifdef DOTLOCK_USE_PTHREAD
391
static pthread_mutex_t all_lockfiles_mutex = PTHREAD_MUTEX_INITIALIZER;
392
# define LOCK_all_lockfiles() do {                               \
393
        if (pthread_mutex_lock (&all_lockfiles_mutex))           \
394
          my_fatal_0 ("locking all_lockfiles_mutex failed\n");   \
395
      } while (0)
396
# define UNLOCK_all_lockfiles() do {                             \
397
        if (pthread_mutex_unlock (&all_lockfiles_mutex))         \
398
          my_fatal_0 ("unlocking all_lockfiles_mutex failed\n"); \
399
      } while (0)
400
#else  /*!DOTLOCK_USE_PTHREAD*/
401
10
# define LOCK_all_lockfiles()   do { } while (0)
402
10
# define UNLOCK_all_lockfiles() do { } while (0)
403
#endif /*!DOTLOCK_USE_PTHREAD*/
404
405
/* If this has the value true all locking is disabled.  */
406
static int never_lock;
407
408
409
410

411
#ifdef HAVE_DOSISH_SYSTEM
412
/* FIXME: For use in GnuPG this can be replaced by
413
 *        gnupg_w32_set_errno.  */
414
static int
415
map_w32_to_errno (DWORD w32_err)
416
{
417
  switch (w32_err)
418
    {
419
    case 0:
420
      return 0;
421
422
    case ERROR_FILE_NOT_FOUND:
423
      return ENOENT;
424
425
    case ERROR_PATH_NOT_FOUND:
426
      return ENOENT;
427
428
    case ERROR_ACCESS_DENIED:
429
      return EPERM;
430
431
    case ERROR_INVALID_HANDLE:
432
    case ERROR_INVALID_BLOCK:
433
      return EINVAL;
434
435
    case ERROR_NOT_ENOUGH_MEMORY:
436
      return ENOMEM;
437
438
    case ERROR_NO_DATA:
439
    case ERROR_BROKEN_PIPE:
440
      return EPIPE;
441
442
    default:
443
      return EIO;
444
    }
445
}
446
447
448
static int
449
any8bitchar (const char *string)
450
{
451
  if (string)
452
    for ( ; *string; string++)
453
      if ((*string & 0x80))
454
        return 1;
455
  return 0;
456
}
457
#endif /*HAVE_DOSISH_SYSTEM*/
458
459
460
static int
461
default_msg_cb (dotlock_t h, void *opaque, enum dotlock_reasons reason,
462
                const char *format, ...)
463
0
{
464
0
  va_list arg_ptr;
465
0
  int level = GPGRT_LOGLVL_INFO;
466
467
0
  (void)h;
468
0
  (void)opaque;
469
0
#ifdef GNUPG_MAJOR_VERSION
470
0
  va_start (arg_ptr, format);
471
0
  log_logv (level, format, arg_ptr);
472
0
  va_end (arg_ptr);
473
474
0
  if (reason == DOTLOCK_FATAL)
475
0
    abort ();
476
#else
477
  (void)level;
478
  vfprintf (stderr, format, arg_ptr);
479
#endif
480
0
  return 0;
481
0
}
482

483
/* Entirely disable all locking.  This function should be called
484
   before any locking is done.  It may be called right at startup of
485
   the process as it only sets a global value.  */
486
void
487
dotlock_disable (void)
488
0
{
489
0
  never_lock = 1;
490
0
}
491
492
493
#ifdef HAVE_POSIX_SYSTEM
494
static int
495
maybe_deadlock (dotlock_t h)
496
0
{
497
0
  dotlock_t r;
498
0
  int res = 0;
499
500
0
  LOCK_all_lockfiles ();
501
0
  for (r=all_lockfiles; r; r = r->next)
502
0
    {
503
0
      if ( r != h && r->locked )
504
0
        {
505
0
          res = 1;
506
0
          break;
507
0
        }
508
0
    }
509
0
  UNLOCK_all_lockfiles ();
510
0
  return res;
511
0
}
512
#endif /*HAVE_POSIX_SYSTEM*/
513
514
515
/* Read the lock file and return the pid, returns -1 on error.  True
516
   will be stored in the integer at address SAME_NODE if the lock file
517
   has been created on the same node. */
518
#ifdef HAVE_POSIX_SYSTEM
519
static int
520
read_lockfile (dotlock_t h, int *same_node, int *r_fd)
521
3
{
522
3
  char buffer_space[10+1+70+1]; /* 70 is just an estimated value; node
523
                                   names are usually shorter. */
524
3
  int fd;
525
3
  int pid = -1;
526
3
  char *buffer, *p;
527
3
  size_t expected_len;
528
3
  int res, nread;
529
530
3
  *same_node = 0;
531
3
  expected_len = 10 + 1 + h->nodename_len + 1;
532
3
  if ( expected_len >= sizeof buffer_space)
533
0
    {
534
0
      buffer = xtrymalloc (expected_len);
535
0
      if (!buffer)
536
0
        return -1;
537
0
    }
538
3
  else
539
3
    buffer = buffer_space;
540
541
3
  if ( (fd = open (h->lockname, O_RDONLY)) == -1 )
542
0
    {
543
0
      int e = errno;
544
0
      if (errno != ENOENT)
545
0
        h->msg_cb (h, h->msg_cb_arg, DOTLOCK_FILE_ERROR,
546
0
                   "error opening lockfile '%s': %s\n",
547
0
                   h->lockname, strerror (errno) );
548
0
      if (buffer != buffer_space)
549
0
        xfree (buffer);
550
0
      my_set_errno (e); /* Need to return ERRNO here. */
551
0
      return -1;
552
0
    }
553
554
3
  p = buffer;
555
3
  nread = 0;
556
3
  do
557
3
    {
558
3
      res = read (fd, p, expected_len - nread);
559
3
      if (res == -1 && errno == EINTR)
560
0
        continue;
561
3
      if (res < 0)
562
0
        {
563
0
          int e = errno;
564
0
          h->msg_cb (h, h->msg_cb_arg, DOTLOCK_FILE_ERROR,
565
0
                     "error reading lockfile '%s': %s\n",
566
0
                     h->lockname, strerror (errno) );
567
0
          close (fd);
568
0
          if (buffer != buffer_space)
569
0
            xfree (buffer);
570
0
          my_set_errno (e);
571
0
          return -1;
572
0
        }
573
3
      p += res;
574
3
      nread += res;
575
3
    }
576
3
  while (res && nread != expected_len);
577
578
3
  if (r_fd)
579
0
    *r_fd = fd;
580
3
  else
581
3
    close(fd);
582
583
3
  if (nread < 11)
584
0
    {
585
0
      h->msg_cb (h, h->msg_cb_arg, DOTLOCK_INV_FILE,
586
0
                 "invalid size of lockfile '%s'\n", h->lockname);
587
0
      if (buffer != buffer_space)
588
0
        xfree (buffer);
589
0
      my_set_errno (EINVAL);
590
0
      return -1;
591
0
    }
592
593
3
  if (buffer[10] != '\n'
594
3
      || (buffer[10] = 0, pid = atoi (buffer)) == -1
595
3
      || !pid )
596
0
    {
597
0
      h->msg_cb (h, h->msg_cb_arg, DOTLOCK_INV_FILE,
598
0
                 "invalid pid %d in lockfile '%s'\n", pid, h->lockname);
599
0
      if (buffer != buffer_space)
600
0
        xfree (buffer);
601
0
      my_set_errno (EINVAL);
602
0
      return -1;
603
0
    }
604
605
3
  if (nread == expected_len
606
3
      && !memcmp (h->tname+h->nodename_off, buffer+11, h->nodename_len)
607
3
      && buffer[11+h->nodename_len] == '\n')
608
3
    *same_node = 1;
609
610
3
  if (buffer != buffer_space)
611
0
    xfree (buffer);
612
3
  return pid;
613
3
}
614
#endif /*HAVE_POSIX_SYSTEM */
615
616
617
/* Check whether the file system which stores TNAME supports
618
   hardlinks.  Instead of using the non-portable statsfs call which
619
   differs between various Unix versions, we do a runtime test.
620
   Returns: 0 supports hardlinks; 1 no hardlink support, -1 unknown
621
   (test error).  */
622
#ifdef HAVE_POSIX_SYSTEM
623
static int
624
use_hardlinks_p (const char *tname)
625
3
{
626
3
  char *lname;
627
3
  struct stat sb;
628
3
  unsigned int nlink;
629
3
  int res;
630
631
3
  if (stat (tname, &sb))
632
0
    return -1;
633
3
  nlink = (unsigned int)sb.st_nlink;
634
635
3
  lname = xtrymalloc (strlen (tname) + 1 + 1);
636
3
  if (!lname)
637
0
    return -1;
638
3
  strcpy (lname, tname);
639
3
  strcat (lname, "x");
640
641
  /* We ignore the return value of link() because it is unreliable.  */
642
3
  (void) link (tname, lname);
643
644
3
  if (stat (tname, &sb))
645
0
    res = -1;  /* Ooops.  */
646
3
  else if (sb.st_nlink == nlink + 1)
647
3
    res = 0;   /* Yeah, hardlinks are supported.  */
648
0
  else
649
0
    res = 1;   /* No hardlink support.  */
650
651
3
  unlink (lname);
652
3
  xfree (lname);
653
3
  return res;
654
3
}
655
#endif /*HAVE_POSIX_SYSTEM */
656
657
658

659
#ifdef  HAVE_POSIX_SYSTEM
660
static int
661
dotlock_get_process_id (dotlock_t h)
662
6
{
663
6
  return h->by_parent? (int)getppid(): (int)getpid();
664
6
}
665
666
static int
667
dotlock_detect_tname (dotlock_t h)
668
0
{
669
0
  struct stat sb;
670
0
  DIR *dir;
671
0
  char *dirname;
672
0
  char *basename;
673
0
  struct dirent *d;
674
0
  int r;
675
676
0
  if (stat (h->lockname, &sb))
677
0
    return -1;
678
679
0
  basename = make_basename (h->lockname, NULL);
680
0
  dirname = make_dirname (h->lockname);
681
682
0
  dir = opendir (dirname);
683
0
  if (dir == NULL)
684
0
    {
685
0
      xfree (basename);
686
0
      xfree (dirname);
687
0
      return -1;
688
0
    }
689
690
0
  while ((d = readdir (dir)))
691
0
    if (sb.st_ino == d->d_ino && strcmp (d->d_name, basename))
692
0
      break;
693
694
0
  if (d)
695
0
    {
696
0
      int len = strlen (h->tname);
697
0
      int dlen = strlen (d->d_name);
698
0
      const char *tname_path;
699
700
0
      if (dlen > len)
701
0
        {
702
0
          closedir (dir);
703
0
          xfree (basename);
704
0
          xfree (dirname);
705
0
          return -1;
706
0
        }
707
708
0
      strcpy (stpcpy (stpcpy (h->tname, dirname), DIRSEP_S), d->d_name);
709
0
      h->use_o_excl = 0;
710
0
      tname_path = strchr (h->tname + strlen (dirname) + 2, '.');
711
0
      if (!tname_path)
712
0
        {
713
0
          closedir (dir);
714
0
          xfree (basename);
715
0
          xfree (dirname);
716
0
          return -1;
717
0
        }
718
0
      h->nodename_off = tname_path - h->tname + 1;
719
0
    }
720
0
  else
721
0
    h->use_o_excl = 1;
722
723
0
  r = closedir (dir);
724
0
  if (r)
725
0
    {
726
0
      xfree (basename);
727
0
      xfree (dirname);
728
0
      return r;
729
0
    }
730
731
0
  xfree (basename);
732
0
  xfree (dirname);
733
0
  return 0;
734
0
}
735
736
/* Locking core for Unix.  It used a temporary file and the link
737
   system call to make locking an atomic operation. */
738
static dotlock_t
739
dotlock_create_unix (dotlock_t h, const char *file_to_lock)
740
3
{
741
3
  int  fd = -1;
742
3
  char pidstr[16];
743
3
  const char *nodename;
744
3
  const char *dirpart;
745
3
  int dirpartlen;
746
3
  struct utsname utsbuf;
747
3
  size_t tnamelen;
748
3
  int pid;
749
750
3
  pid = dotlock_get_process_id (h);
751
3
  snprintf (pidstr, sizeof pidstr, "%10d\n", pid);
752
753
  /* Create a temporary file. */
754
3
  if ( uname ( &utsbuf ) )
755
0
    nodename = "unknown";
756
3
  else
757
3
    nodename = utsbuf.nodename;
758
759
3
  if ( !(dirpart = strrchr (file_to_lock, DIRSEP_C)) )
760
0
    {
761
0
      dirpart = EXTSEP_S;
762
0
      dirpartlen = 1;
763
0
    }
764
3
  else
765
3
    {
766
3
      dirpartlen = dirpart - file_to_lock;
767
3
      dirpart = file_to_lock;
768
3
    }
769
770
3
  LOCK_all_lockfiles ();
771
3
  h->next = all_lockfiles;
772
3
  all_lockfiles = h;
773
774
3
  tnamelen = dirpartlen + 6 + 30 + strlen(nodename) + 10 + 1;
775
3
  h->tname = xtrymalloc (tnamelen + 1);
776
3
  if (!h->tname)
777
0
    {
778
0
      all_lockfiles = h->next;
779
0
      UNLOCK_all_lockfiles ();
780
0
      xfree (h);
781
0
      return NULL;
782
0
    }
783
3
  h->nodename_len = strlen (nodename);
784
785
3
  if (h->no_write)
786
0
    {
787
0
      memset (h->tname, '_', tnamelen);
788
0
      h->tname[tnamelen] = 0;
789
0
      goto skip_write;
790
0
    }
791
792
3
  snprintf (h->tname, tnamelen, "%.*s/.#lk%p.", dirpartlen, dirpart, h );
793
3
  h->nodename_off = strlen (h->tname);
794
3
  snprintf (h->tname+h->nodename_off, tnamelen - h->nodename_off,
795
3
           "%s.%d", nodename, pid);
796
797
3
  do
798
3
    {
799
3
      my_set_errno (0);
800
3
      fd = open (h->tname, O_WRONLY|O_CREAT|O_EXCL,
801
3
                 S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR );
802
3
    }
803
3
  while (fd == -1 && errno == EINTR);
804
805
3
  if ( fd == -1 )
806
0
    {
807
0
      int saveerrno = errno;
808
0
      all_lockfiles = h->next;
809
0
      UNLOCK_all_lockfiles ();
810
0
      h->msg_cb (h, h->msg_cb_arg, DOTLOCK_WAITING,
811
0
                 _("failed to create temporary file '%s': %s\n"),
812
0
                 h->tname, strerror (errno));
813
0
      xfree (h->tname);
814
0
      xfree (h);
815
0
      my_set_errno (saveerrno);
816
0
      return NULL;
817
0
    }
818
3
  if ( write (fd, pidstr, 11 ) != 11 )
819
0
    goto write_failed;
820
3
  if ( write (fd, nodename, strlen (nodename) ) != strlen (nodename) )
821
0
    goto write_failed;
822
3
  if ( write (fd, "\n", 1 ) != 1 )
823
0
    goto write_failed;
824
3
  if ( close (fd) )
825
0
    {
826
0
      if ( errno == EINTR )
827
0
        fd = -1;
828
0
      goto write_failed;
829
0
    }
830
3
  fd = -1;
831
832
  /* Check whether we support hard links.  */
833
3
  switch (use_hardlinks_p (h->tname))
834
3
    {
835
3
    case 0: /* Yes.  */
836
3
      break;
837
0
    case 1: /* No.  */
838
0
      unlink (h->tname);
839
0
      h->use_o_excl = 1;
840
0
      break;
841
0
    default:
842
0
      {
843
0
        int saveerrno = errno;
844
0
        h->msg_cb (h, h->msg_cb_arg, DOTLOCK_CONFIG_TEST,
845
0
                   "can't check whether hardlinks are supported for '%s': %s\n",
846
0
                   h->tname, strerror (saveerrno));
847
0
        my_set_errno (saveerrno);
848
0
      }
849
0
      goto write_failed;
850
3
    }
851
852
3
 skip_write:
853
3
  h->lockname = xtrymalloc (strlen (file_to_lock) + 6 );
854
3
  if (!h->lockname)
855
0
    {
856
0
      int saveerrno = errno;
857
0
      all_lockfiles = h->next;
858
0
      UNLOCK_all_lockfiles ();
859
0
      unlink (h->tname);
860
0
      xfree (h->tname);
861
0
      xfree (h);
862
0
      my_set_errno (saveerrno);
863
0
      return NULL;
864
0
    }
865
3
  strcpy (stpcpy (h->lockname, file_to_lock), EXTSEP_S "lock");
866
3
  UNLOCK_all_lockfiles ();
867
868
3
  if (h->no_write)
869
0
    {
870
0
      if (dotlock_detect_tname (h) < 0)
871
0
        {
872
0
          xfree (h->lockname);
873
0
          xfree (h->tname);
874
0
          xfree (h);
875
0
          my_set_errno (EACCES);
876
0
          return NULL;
877
0
        }
878
879
0
      h->locked = 1;
880
0
    }
881
882
3
  return h;
883
884
0
 write_failed:
885
0
  {
886
0
    int saveerrno = errno;
887
0
    all_lockfiles = h->next;
888
0
    UNLOCK_all_lockfiles ();
889
0
    h->msg_cb (h, h->msg_cb_arg, DOTLOCK_FILE_ERROR,
890
0
               _("error writing to '%s': %s\n"),
891
0
               h->tname, strerror (errno));
892
0
    if ( fd != -1 )
893
0
      close (fd);
894
0
    unlink (h->tname);
895
0
    xfree (h->tname);
896
0
    xfree (h);
897
0
    my_set_errno (saveerrno);
898
0
  }
899
0
  return NULL;
900
3
}
901
#endif /*HAVE_POSIX_SYSTEM*/
902
903
904
#ifdef HAVE_DOSISH_SYSTEM
905
/* Locking core for Windows.  This version does not need a temporary
906
   file but uses the plain lock file along with record locking.  We
907
   create this file here so that we later only need to do the file
908
   locking.  For error reporting it is useful to keep the name of the
909
   file in the handle.  */
910
static dotlock_t
911
dotlock_create_w32 (dotlock_t h, const char *file_to_lock)
912
{
913
  LOCK_all_lockfiles ();
914
  h->next = all_lockfiles;
915
  all_lockfiles = h;
916
917
  h->lockname = strconcat (file_to_lock, EXTSEP_S "lock", NULL);
918
  if (!h->lockname)
919
    {
920
      all_lockfiles = h->next;
921
      UNLOCK_all_lockfiles ();
922
      xfree (h);
923
      return NULL;
924
    }
925
926
  /* If would be nice if we would use the FILE_FLAG_DELETE_ON_CLOSE
927
     along with FILE_SHARE_DELETE but that does not work due to a race
928
     condition: Despite the OPEN_ALWAYS flag CreateFile may return an
929
     error and we can't reliable create/open the lock file unless we
930
     would wait here until it works - however there are other valid
931
     reasons why a lock file can't be created and thus the process
932
     would not stop as expected but spin until Windows crashes.  Our
933
     solution is to keep the lock file open; that does not harm. */
934
  if (any8bitchar (h->lockname))
935
    {
936
      wchar_t *wname = utf8_to_wchar (h->lockname);
937
938
      if (wname)
939
        h->lockhd = CreateFileW (wname,
940
                                 GENERIC_READ|GENERIC_WRITE,
941
                                 FILE_SHARE_READ|FILE_SHARE_WRITE,
942
                                 NULL, OPEN_ALWAYS, 0, NULL);
943
      else
944
        h->lockhd = INVALID_HANDLE_VALUE;
945
      xfree (wname);
946
    }
947
  else
948
    h->lockhd = CreateFileA (h->lockname,
949
                             GENERIC_READ|GENERIC_WRITE,
950
                             FILE_SHARE_READ|FILE_SHARE_WRITE,
951
                             NULL, OPEN_ALWAYS, 0, NULL);
952
  if (h->lockhd == INVALID_HANDLE_VALUE)
953
    {
954
      int saveerrno = map_w32_to_errno (GetLastError ());
955
      all_lockfiles = h->next;
956
      UNLOCK_all_lockfiles ();
957
      h->msg_cb (h, h->msg_cb_arg, DOTLOCK_FILE_ERROR,
958
                 _("can't create '%s': %s\n"),
959
                 h->lockname, w32_strerror (-1));
960
      xfree (h->lockname);
961
      xfree (h);
962
      my_set_errno (saveerrno);
963
      return NULL;
964
    }
965
  UNLOCK_all_lockfiles ();
966
  return h;
967
}
968
#endif /*HAVE_DOSISH_SYSTEM*/
969
970
971
/* Create a lockfile for a file name FILE_TO_LOCK and returns an
972
   object of type dotlock_t which may be used later to actually acquire
973
   the lock.  A cleanup routine gets installed to cleanup left over
974
   locks or other files used internally by the lock mechanism.
975
976
   Calling this function with NULL does only install the atexit
977
   handler and may thus be used to assure that the cleanup is called
978
   after all other atexit handlers.
979
980
   This function creates a lock file in the same directory as
981
   FILE_TO_LOCK using that name and a suffix of ".lock".  Note that on
982
   POSIX systems a temporary file ".#lk.<hostname>.pid[.threadid] is
983
   used.
984
985
   FLAGS may include DOTLOCK_LOCK_BY_PARENT bit, when it's the parent
986
   process controlling the lock.  This is used by dotlock_tool in
987
   gpgconf.
988
989
   FLAGS may include DOTLOCK_LOCKED bit, when it should not create the
990
   lockfile, but to unlock.  This is used by dotlock_tool in gpgconf.
991
992
   The function returns an new handle which needs to be released using
993
   destroy_dotlock but gets also released at the termination of the
994
   process.  On error NULL is returned.
995
 */
996
997
dotlock_t
998
dotlock_create_with (const char *file_to_lock, unsigned int flags,
999
                     int (*msg_cb)(dotlock_t, void *,
1000
                                   enum dotlock_reasons reason,
1001
                                   const char *, ...),
1002
                     void *msg_cb_arg)
1003
3
{
1004
3
  static int initialized;
1005
3
  dotlock_t h;
1006
3
#ifndef HAVE_DOSISH_SYSTEM
1007
3
  int by_parent = 0;
1008
3
  int no_write = 0;
1009
3
#endif
1010
1011
3
  if ( !(flags & DOTLOCK_LOCK_BY_PARENT)
1012
3
       && !initialized )
1013
1
    {
1014
1
      atexit (dotlock_remove_lockfiles);
1015
1
      initialized = 1;
1016
1
    }
1017
1018
3
  if ( !file_to_lock )
1019
0
    return NULL;  /* Only initialization was requested.  */
1020
1021
3
#ifndef HAVE_DOSISH_SYSTEM
1022
3
  if ((flags & DOTLOCK_LOCK_BY_PARENT) || (flags & DOTLOCK_LOCKED))
1023
0
    {
1024
0
      by_parent = !!(flags & DOTLOCK_LOCK_BY_PARENT);
1025
0
      no_write = !!(flags & DOTLOCK_LOCKED);
1026
0
      flags &= ~(DOTLOCK_LOCK_BY_PARENT | DOTLOCK_LOCKED);
1027
0
    }
1028
3
#endif
1029
3
  if (flags)
1030
0
    {
1031
0
      my_set_errno (EINVAL);
1032
0
      return NULL;
1033
0
    }
1034
1035
3
  h = xtrycalloc (1, sizeof *h);
1036
3
  if (!h)
1037
0
    return NULL;
1038
3
  h->extra_fd = -1;
1039
3
#ifndef HAVE_DOSISH_SYSTEM
1040
3
  h->by_parent = by_parent;
1041
3
  h->no_write = no_write;
1042
3
#endif
1043
3
  h->msg_cb = msg_cb;
1044
3
  h->msg_cb_arg = msg_cb_arg;
1045
1046
3
  if (never_lock)
1047
0
    {
1048
0
      h->disable = 1;
1049
0
      LOCK_all_lockfiles ();
1050
0
      h->next = all_lockfiles;
1051
0
      all_lockfiles = h;
1052
0
      UNLOCK_all_lockfiles ();
1053
0
      return h;
1054
0
    }
1055
1056
#ifdef HAVE_DOSISH_SYSTEM
1057
  return dotlock_create_w32 (h, file_to_lock);
1058
#else /*!HAVE_DOSISH_SYSTEM */
1059
3
  return dotlock_create_unix (h, file_to_lock);
1060
3
#endif /*!HAVE_DOSISH_SYSTEM*/
1061
3
}
1062
1063
1064

1065
/* Convenience function to store a file descriptor (or any other
1066
   integer value) in the context of handle H.  */
1067
void
1068
dotlock_set_fd (dotlock_t h, int fd)
1069
0
{
1070
0
  h->extra_fd = fd;
1071
0
}
1072
1073
/* Convenience function to retrieve a file descriptor (or any other
1074
   integer value) stored in the context of handle H.  */
1075
int
1076
dotlock_get_fd (dotlock_t h)
1077
0
{
1078
0
  return h->extra_fd;
1079
0
}
1080
1081
1082
dotlock_t
1083
dotlock_create (const char *file_to_lock, unsigned int flags)
1084
3
{
1085
3
  return dotlock_create_with (file_to_lock, flags, default_msg_cb, NULL);
1086
3
}
1087

1088
#ifdef HAVE_POSIX_SYSTEM
1089
/* Unix specific code of destroy_dotlock.  */
1090
static void
1091
dotlock_destroy_unix (dotlock_t h)
1092
3
{
1093
3
  if (h->locked && h->lockname)
1094
0
    unlink (h->lockname);
1095
3
  if (h->tname && !h->use_o_excl)
1096
3
    unlink (h->tname);
1097
3
}
1098
#endif /*HAVE_POSIX_SYSTEM*/
1099
1100
1101
#ifdef HAVE_DOSISH_SYSTEM
1102
/* Windows specific code of destroy_dotlock.  */
1103
static void
1104
dotlock_destroy_w32 (dotlock_t h)
1105
{
1106
  if (h->locked)
1107
    {
1108
      OVERLAPPED ovl;
1109
1110
      memset (&ovl, 0, sizeof ovl);
1111
      UnlockFileEx (h->lockhd, 0, 1, 0, &ovl);
1112
    }
1113
  CloseHandle (h->lockhd);
1114
}
1115
#endif /*HAVE_DOSISH_SYSTEM*/
1116
1117
1118
/* Destroy the lock handle H and release the lock.  */
1119
void
1120
dotlock_destroy (dotlock_t h)
1121
3
{
1122
3
  dotlock_t hprev, htmp;
1123
1124
3
  if ( !h )
1125
0
    return;
1126
1127
  /* First remove the handle from our global list of all locks. */
1128
3
  LOCK_all_lockfiles ();
1129
3
  for (hprev=NULL, htmp=all_lockfiles; htmp; hprev=htmp, htmp=htmp->next)
1130
1
    if (htmp == h)
1131
1
      {
1132
1
        if (hprev)
1133
0
          hprev->next = htmp->next;
1134
1
        else
1135
1
          all_lockfiles = htmp->next;
1136
1
        h->next = NULL;
1137
1
        break;
1138
1
      }
1139
3
  UNLOCK_all_lockfiles ();
1140
1141
  /* Then destroy the lock. */
1142
3
  if (!h->disable
1143
3
      && (!h->by_parent || h->no_write))
1144
3
    {
1145
      /* NOTE: under the condition of (by_parent && !no_write),
1146
         it doesn't come here.  So, the lock file remains.  */
1147
#ifdef HAVE_DOSISH_SYSTEM
1148
      dotlock_destroy_w32 (h);
1149
#else /* !HAVE_DOSISH_SYSTEM */
1150
3
      dotlock_destroy_unix (h);
1151
3
#endif /* HAVE_DOSISH_SYSTEM */
1152
3
    }
1153
1154
3
#ifdef HAVE_POSIX_SYSTEM
1155
  /* When DOTLOCK_LOCK_BY_PARENT and lock fails,
1156
     the temporary file created should be removed.  */
1157
3
  if (h->by_parent && !h->no_write && !h->locked)
1158
0
    if (h->tname && !h->use_o_excl)
1159
0
      unlink (h->tname);
1160
1161
3
  xfree (h->tname);
1162
3
#endif
1163
3
  xfree (h->lockname);
1164
3
  xfree(h);
1165
3
}
1166
1167
1168
/* Return true if H has been taken.  */
1169
int
1170
dotlock_is_locked (dotlock_t h)
1171
0
{
1172
0
  return h && !!h->locked;
1173
0
}
1174
1175
1176
/* Return the next interval to wait.  WTIME and TIMEOUT are pointers
1177
 * to the current state and are updated by this function.  The
1178
 * returned value might be different from the value of WTIME.  */
1179
static int
1180
next_wait_interval (int *wtime, long *timeout)
1181
0
{
1182
0
  int result;
1183
1184
  /* Wait until lock has been released.  We use retry intervals of 4,
1185
   * 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 512, 1024, 2048ms, and
1186
   * so on.  If wait-forever was requested we add a small random value
1187
   * to have different timeouts per process. */
1188
0
  if (!*wtime)
1189
0
    *wtime = 4;
1190
0
  else if (*wtime < 2048)
1191
0
    *wtime *= 2;
1192
0
  else
1193
0
    *wtime = 512;
1194
1195
0
  result = *wtime;
1196
0
  if (*wtime > 8 && *timeout < 0)
1197
0
    result += ((unsigned int)getpid() % 37);
1198
1199
0
  if (*timeout > 0)
1200
0
    {
1201
0
      if (result > *timeout)
1202
0
        result = *timeout;
1203
0
      *timeout -= result;
1204
0
    }
1205
1206
0
  return result;
1207
0
}
1208
1209
1210

1211
#ifdef HAVE_POSIX_SYSTEM
1212
/* Unix specific code of make_dotlock.  Returns 0 on success and -1 on
1213
   error.  */
1214
static int
1215
dotlock_take_unix (dotlock_t h, long timeout)
1216
3
{
1217
3
  int wtime = 0;
1218
3
  int timedout = 0;
1219
3
  int sumtime = 0;
1220
3
  int pid;
1221
3
  int lastpid = -1;
1222
3
  int ownerchanged;
1223
3
  const char *maybe_dead="";
1224
3
  int same_node;
1225
3
  int saveerrno;
1226
3
  int fd;
1227
1228
3
 again:
1229
3
  if (h->use_o_excl)
1230
0
    {
1231
      /* No hardlink support - use open(O_EXCL).  */
1232
0
      do
1233
0
        {
1234
0
          my_set_errno (0);
1235
0
          fd = open (h->lockname, O_WRONLY|O_CREAT|O_EXCL,
1236
0
                     S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR );
1237
0
        }
1238
0
      while (fd == -1 && errno == EINTR);
1239
1240
0
      if (fd == -1 && errno == EEXIST)
1241
0
        ; /* Lock held by another process.  */
1242
0
      else if (fd == -1)
1243
0
        {
1244
0
          saveerrno = errno;
1245
0
          h->msg_cb (h, h->msg_cb_arg, DOTLOCK_FILE_ERROR,
1246
0
                     "lock not made: open(O_EXCL) of '%s' failed: %s\n",
1247
0
                     h->lockname, strerror (saveerrno));
1248
0
          my_set_errno (saveerrno);
1249
0
          return -1;
1250
0
        }
1251
0
      else
1252
0
        {
1253
0
          char pidstr[16];
1254
1255
0
          snprintf (pidstr, sizeof pidstr, "%10d\n",
1256
0
                    dotlock_get_process_id (h));
1257
0
          if (write (fd, pidstr, 11 ) == 11
1258
0
              && write (fd, h->tname + h->nodename_off,h->nodename_len)
1259
0
              == h->nodename_len
1260
0
              && write (fd, "\n", 1) == 1
1261
0
              && !close (fd))
1262
0
            {
1263
0
              h->locked = 1;
1264
0
              return 0;
1265
0
            }
1266
          /* Write error.  */
1267
0
          saveerrno = errno;
1268
0
          h->msg_cb (h, h->msg_cb_arg, DOTLOCK_FILE_ERROR,
1269
0
                     "lock not made: writing to '%s' failed: %s\n",
1270
0
                     h->lockname, strerror (errno));
1271
0
          close (fd);
1272
0
          unlink (h->lockname);
1273
0
          my_set_errno (saveerrno);
1274
0
          return -1;
1275
0
        }
1276
0
    }
1277
3
  else /* Standard method:  Use hardlinks.  */
1278
3
    {
1279
3
      struct stat sb;
1280
1281
      /* We ignore the return value of link() because it is unreliable.  */
1282
3
      (void) link (h->tname, h->lockname);
1283
1284
3
      if (stat (h->tname, &sb))
1285
0
        {
1286
0
          saveerrno = errno;
1287
0
          h->msg_cb (h, h->msg_cb_arg, DOTLOCK_FILE_ERROR,
1288
0
                     "lock not made: Oops: stat of tmp file failed: %s\n",
1289
0
                     strerror (errno));
1290
          /* In theory this might be a severe error: It is possible
1291
             that link succeeded but stat failed due to changed
1292
             permissions.  We can't do anything about it, though.  */
1293
0
          my_set_errno (saveerrno);
1294
0
          return -1;
1295
0
        }
1296
1297
3
      if (sb.st_nlink == 2)
1298
3
        {
1299
3
          h->locked = 1;
1300
3
          return 0; /* Okay.  */
1301
3
        }
1302
3
    }
1303
1304
  /* Check for stale lock files.  */
1305
0
  if ( (pid = read_lockfile (h, &same_node, &fd)) == -1 )
1306
0
    {
1307
0
      if ( errno != ENOENT )
1308
0
        {
1309
0
          saveerrno = errno;
1310
0
          h->msg_cb (h, h->msg_cb_arg, DOTLOCK_FILE_ERROR,
1311
0
                     "cannot read lockfile\n");
1312
0
          my_set_errno (saveerrno);
1313
0
          return -1;
1314
0
        }
1315
0
      goto again;
1316
0
    }
1317
0
  else if ( (pid == dotlock_get_process_id (h) && same_node && !h->by_parent)
1318
0
            || (same_node && kill (pid, 0) && errno == ESRCH) )
1319
0
    {
1320
      /* Stale lockfile is detected. */
1321
0
      struct stat sb;
1322
1323
      /* Check if it's unlocked during examining the lockfile.  */
1324
0
      if (fstat (fd, &sb) || sb.st_nlink == 0)
1325
0
        {
1326
          /* It's gone already by another process.  */
1327
0
          close (fd);
1328
0
          goto again;
1329
0
        }
1330
1331
      /*
1332
       * Here, although it's quite _rare_, we have a race condition.
1333
       *
1334
       * When multiple processes race on a stale lockfile, detecting
1335
       * AND removing should be done atomically.  That is, to work
1336
       * correctly, the file to be removed should be the one which is
1337
       * examined for detection.
1338
       *
1339
       * But, when it's not atomic, consider the case for us where it
1340
       * takes some time between the detection and the removal of the
1341
       * lockfile.
1342
       *
1343
       * In this situation, it is possible that the file which was
1344
       * detected as stale is already removed by another process and
1345
       * then new lockfile is created (by that process or other one).
1346
       *
1347
       * And it is newly created valid lockfile which is going to be
1348
       * removed by us.
1349
       *
1350
       * Consider this long comment as it expresses possible (long)
1351
       * time between fstat above and unlink below; Meanwhile, the
1352
       * lockfile in question may be removed and there may be new
1353
       * valid one.
1354
       *
1355
       * In short, when you see the message of removing stale lockfile
1356
       * when there are multiple processes for the work, there is
1357
       * (very) little possibility something went wrong.
1358
       */
1359
1360
0
      unlink (h->lockname);
1361
0
      close (fd);
1362
0
      h->msg_cb (h, h->msg_cb_arg, DOTLOCK_STALE_REMOVED,
1363
0
                 _("removing stale lockfile (created by %d)\n"), pid);
1364
0
      goto again;
1365
0
    }
1366
1367
0
  close (fd);
1368
0
  if (lastpid == -1)
1369
0
    lastpid = pid;
1370
0
  ownerchanged = (pid != lastpid);
1371
1372
0
  if (timeout)
1373
0
    {
1374
0
      struct timeval tv;
1375
0
      int wtimereal;
1376
1377
0
      if (ownerchanged)
1378
0
        wtime = 0;  /* Reset because owner changed.  */
1379
1380
0
      wtimereal = next_wait_interval (&wtime, &timeout);
1381
0
      if (!timeout)
1382
0
        timedout = 1;  /* remember.  */
1383
1384
0
      sumtime += wtimereal;
1385
0
      if (sumtime >= 1500)
1386
0
        {
1387
0
          sumtime = 0;
1388
0
          if (h->msg_cb (h, h->msg_cb_arg, DOTLOCK_WAITING,
1389
0
                         _("waiting for lock (held by %d%s) %s...\n"),
1390
0
                         pid, maybe_dead,
1391
0
                         maybe_deadlock(h)? _("(deadlock?) "):""))
1392
0
            {
1393
0
              my_set_errno (ECANCELED);
1394
0
              return -1;
1395
0
            }
1396
0
        }
1397
1398
0
      tv.tv_sec = wtimereal / 1000;
1399
0
      tv.tv_usec = (wtimereal % 1000) * 1000;
1400
0
      select (0, NULL, NULL, NULL, &tv);
1401
0
      goto again;
1402
0
    }
1403
1404
0
  my_set_errno (timedout? ETIMEDOUT : EACCES);
1405
0
  return -1;
1406
0
}
1407
#endif /*HAVE_POSIX_SYSTEM*/
1408
1409
1410
#ifdef HAVE_DOSISH_SYSTEM
1411
/* Windows specific code of make_dotlock.  Returns 0 on success and -1 on
1412
   error.  */
1413
static int
1414
dotlock_take_w32 (dotlock_t h, long timeout)
1415
{
1416
  int wtime = 0;
1417
  int timedout = 0;
1418
  int w32err;
1419
  OVERLAPPED ovl;
1420
1421
 again:
1422
  /* Lock one byte at offset 0.  The offset is given by OVL.  */
1423
  memset (&ovl, 0, sizeof ovl);
1424
  if (LockFileEx (h->lockhd, (LOCKFILE_EXCLUSIVE_LOCK
1425
                              | LOCKFILE_FAIL_IMMEDIATELY), 0, 1, 0, &ovl))
1426
    {
1427
      h->locked = 1;
1428
      return 0; /* okay */
1429
    }
1430
1431
  w32err = GetLastError ();
1432
  if (w32err != ERROR_LOCK_VIOLATION)
1433
    {
1434
      h->msg_cb (h, h->msg_cb_arg, DOTLOCK_FILE_ERROR,
1435
                 _("lock '%s' not made: %s\n"),
1436
                 h->lockname, w32_strerror (w32err));
1437
      my_set_errno (map_w32_to_errno (w32err));
1438
      return -1;
1439
    }
1440
1441
  if (timeout)
1442
    {
1443
      int wtimereal;
1444
1445
      wtimereal = next_wait_interval (&wtime, &timeout);
1446
      if (!timeout)
1447
        timedout = 1;  /* remember.  */
1448
1449
      if (wtime >= 800)
1450
        {
1451
          if (h->msg_cb (h, h->msg_cb_arg, DOTLOCK_WAITING,
1452
                         _("waiting for lock %s...\n"), h->lockname))
1453
            {
1454
              my_set_errno (ECANCELED);
1455
              return -1;
1456
            }
1457
        }
1458
1459
      Sleep (wtimereal);
1460
      goto again;
1461
    }
1462
1463
  my_set_errno (timedout? ETIMEDOUT : EACCES);
1464
  return -1;
1465
}
1466
#endif /*HAVE_DOSISH_SYSTEM*/
1467
1468
1469
/* Take a lock on H.  A value of 0 for TIMEOUT returns immediately if
1470
   the lock can't be taken, -1 waits forever (hopefully not), other
1471
   values wait for TIMEOUT milliseconds.  Returns: 0 on success  */
1472
int
1473
dotlock_take (dotlock_t h, long timeout)
1474
3
{
1475
3
  int ret;
1476
1477
3
  if ( h->disable )
1478
0
    return 0; /* Locks are completely disabled.  Return success. */
1479
1480
3
  if ( h->locked )
1481
0
    {
1482
0
      h->msg_cb (h, h->msg_cb_arg, DOTLOCK_LOCKED_ALREADY,
1483
0
                 "Oops, '%s' is already locked\n", h->lockname);
1484
0
      return 0;
1485
0
    }
1486
1487
#ifdef HAVE_DOSISH_SYSTEM
1488
  ret = dotlock_take_w32 (h, timeout);
1489
#else /*!HAVE_DOSISH_SYSTEM*/
1490
3
  ret = dotlock_take_unix (h, timeout);
1491
3
#endif /*!HAVE_DOSISH_SYSTEM*/
1492
1493
3
  return ret;
1494
3
}
1495
1496
1497

1498
#ifdef HAVE_POSIX_SYSTEM
1499
/* Unix specific code of release_dotlock.  */
1500
static int
1501
dotlock_release_unix (dotlock_t h)
1502
3
{
1503
3
  int pid, same_node;
1504
3
  int saveerrno;
1505
1506
3
  pid = read_lockfile (h, &same_node, NULL);
1507
3
  if ( pid == -1 )
1508
0
    {
1509
0
      saveerrno = errno;
1510
0
      h->msg_cb (h, h->msg_cb_arg, DOTLOCK_FILE_ERROR,
1511
0
                 "release_dotlock: lockfile error\n");
1512
0
      my_set_errno (saveerrno);
1513
0
      return -1;
1514
0
    }
1515
3
  if ( pid != dotlock_get_process_id (h) || !same_node )
1516
0
    {
1517
0
      h->msg_cb (h, h->msg_cb_arg, DOTLOCK_CONFLICT,
1518
0
                 "release_dotlock: not our lock (pid=%d)\n", pid);
1519
0
      my_set_errno (EACCES);
1520
0
      return -1;
1521
0
    }
1522
1523
3
  if ( unlink( h->lockname ) )
1524
0
    {
1525
0
      saveerrno = errno;
1526
0
      h->msg_cb (h, h->msg_cb_arg, DOTLOCK_FILE_ERROR,
1527
0
                 "release_dotlock: error removing lockfile '%s'\n",
1528
0
                 h->lockname);
1529
0
      my_set_errno (saveerrno);
1530
0
      return -1;
1531
0
    }
1532
  /* Fixme: As an extra check we could check whether the link count is
1533
     now really at 1. */
1534
3
  return 0;
1535
3
}
1536
#endif /*HAVE_POSIX_SYSTEM */
1537
1538
1539
#ifdef HAVE_DOSISH_SYSTEM
1540
/* Windows specific code of release_dotlock.  */
1541
static int
1542
dotlock_release_w32 (dotlock_t h)
1543
{
1544
  OVERLAPPED ovl;
1545
1546
  memset (&ovl, 0, sizeof ovl);
1547
  if (!UnlockFileEx (h->lockhd, 0, 1, 0, &ovl))
1548
    {
1549
      int ec = (int)GetLastError ();
1550
1551
      h->msg_cb (h, h->msg_cb_arg, DOTLOCK_FILE_ERROR,
1552
                 "release_dotlock: error removing lockfile '%s': %s\n",
1553
                 h->lockname, w32_strerror (ec));
1554
      my_set_errno (map_w32_to_errno (ec));
1555
      return -1;
1556
    }
1557
1558
  return 0;
1559
}
1560
#endif /*HAVE_DOSISH_SYSTEM */
1561
1562
1563
/* Release a lock.  Returns 0 on success.  */
1564
int
1565
dotlock_release (dotlock_t h)
1566
3
{
1567
3
  int ret;
1568
1569
  /* To avoid atexit race conditions we first check whether there are
1570
     any locks left.  It might happen that another atexit handler
1571
     tries to release the lock while the atexit handler of this module
1572
     already ran and thus H is undefined.  */
1573
3
  LOCK_all_lockfiles ();
1574
3
  ret = !all_lockfiles;
1575
3
  UNLOCK_all_lockfiles ();
1576
3
  if (ret)
1577
0
    return 0;
1578
1579
3
  if ( h->disable )
1580
0
    return 0;
1581
1582
3
  if ( !h->locked )
1583
0
    {
1584
0
      if (!never_lock)
1585
0
        {
1586
0
          h->msg_cb (h, h->msg_cb_arg, DOTLOCK_NOT_LOCKED,
1587
0
                     "Oops, '%s' is not locked\n", h->lockname);
1588
0
        }
1589
0
      return 0;
1590
0
    }
1591
1592
#ifdef HAVE_DOSISH_SYSTEM
1593
  ret = dotlock_release_w32 (h);
1594
#else
1595
3
  ret = dotlock_release_unix (h);
1596
3
#endif
1597
1598
3
  if (!ret)
1599
3
    h->locked = 0;
1600
3
  return ret;
1601
3
}
1602
1603
1604

1605
/* Remove all lockfiles.  This is called by the atexit handler
1606
   installed by this module but may also be called by other
1607
   termination handlers.  */
1608
void
1609
dotlock_remove_lockfiles (void)
1610
1
{
1611
1
  dotlock_t h, h2;
1612
1613
  /* First set the lockfiles list to NULL so that for example
1614
     dotlock_release is aware that this function is currently
1615
     running.  */
1616
1
  LOCK_all_lockfiles ();
1617
1
  h = all_lockfiles;
1618
1
  all_lockfiles = NULL;
1619
1
  UNLOCK_all_lockfiles ();
1620
1621
3
  while ( h )
1622
2
    {
1623
2
      h2 = h->next;
1624
2
      dotlock_destroy (h);
1625
2
      h = h2;
1626
2
    }
1627
1
}