summaryrefslogtreecommitdiffstats
path: root/src/pulsecore/pid.c
blob: dd2e699d0d829cbf4d57b279d0f87cf645f4627a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/* $Id$ */

/***
  This file is part of PulseAudio.

  Copyright 2004-2006 Lennart Poettering
  Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB

  PulseAudio is free software; you can redistribute it and/or modify
  it under the terms of the GNU Lesser General Public License as
  published by the Free Software Foundation; either version 2 of the
  License, or (at your option) any later version.

  PulseAudio 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 Lesser General Public
  License along with PulseAudio; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  USA.
***/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <signal.h>

#ifdef HAVE_WINDOWS_H
#include <windows.h>
#endif

#include <pulse/xmalloc.h>
#include <pulse/util.h>

#include <pulsecore/core-error.h>
#include <pulsecore/core-util.h>
#include <pulsecore/log.h>
#include <pulsecore/macro.h>

#include "pid.h"

/* Read the PID data from the file descriptor fd, and return it. If no
 * pid could be read, return 0, on failure (pid_t) -1 */
static pid_t read_pid(const char *fn, int fd) {
    ssize_t r;
    char t[20], *e;
    uint32_t pid;

    pa_assert(fn);
    pa_assert(fd >= 0);

    if ((r = pa_loop_read(fd, t, sizeof(t)-1, NULL)) < 0) {
        pa_log_warn("Failed to read PID file '%s': %s", fn, pa_cstrerror(errno));
        return (pid_t) -1;
    }

    if (r == 0)
        return (pid_t) 0;

    t[r] = 0;
    if ((e = strchr(t, '\n')))
        *e = 0;

    if (pa_atou(t, &pid) < 0) {
        pa_log_warn("Failed to parse PID file '%s'", fn);
        return (pid_t) -1;
    }

    return (pid_t) pid;
}

static int open_pid_file(const char *fn, int mode) {
    int fd = -1;

    pa_assert(fn);

    for (;;) {
        struct stat st;

        if ((fd = open(fn, mode
#ifdef O_NOCTTY
                       |O_NOCTTY
#endif
#ifdef O_NOFOLLOW
                       |O_NOFOLLOW
#endif
                       , S_IRUSR|S_IWUSR
             )) < 0) {
            if (mode != O_RDONLY || errno != ENOENT)
                pa_log_warn("Failed to open PID file '%s': %s", fn, pa_cstrerror(errno));
            goto fail;
        }

        /* Try to lock the file. If that fails, go without */
        if (pa_lock_fd(fd, 1) < 0)
            goto fail;

        if (fstat(fd, &st) < 0) {
            pa_log_warn("Failed to fstat() PID file '%s': %s", fn, pa_cstrerror(errno));
            goto fail;
        }

        /* Does the file still exist in the file system? When ye, w're done, otherwise restart */
        if (st.st_nlink >= 1)
            break;

        if (pa_lock_fd(fd, 0) < 0)
            goto fail;

        if (pa_close(fd) < 0) {
            pa_log_warn("Failed to close file '%s': %s", fn, pa_cstrerror(errno));
            fd = -1;
            goto fail;
        }

        fd = -1;
    }

    return fd;

fail:

    if (fd >= 0) {
        pa_lock_fd(fd, 0);
        pa_close(fd);
    }

    return -1;
}

static int proc_name_ours(pid_t pid, const char *procname) {
#ifdef __linux__
    char bn[PATH_MAX];
    FILE *f;

    pa_snprintf(bn, sizeof(bn), "/proc/%lu/stat", (unsigned long) pid);

    if (!(f = fopen(bn, "r"))) {
        pa_log_info("Failed to open %s: %s", bn, pa_cstrerror(errno));
        return -1;
    } else {
        char *expected;
        pa_bool_t good;
        char stored[64];

        if (!(fgets(stored, sizeof(stored), f))) {
            pa_log_info("Failed to read from %s: %s", bn, feof(f) ? "EOF" : pa_cstrerror(errno));
            fclose(f);
            return -1;
        }

        fclose(f);

        expected = pa_sprintf_malloc("%lu (%s)", (unsigned long) pid, procname);
        good = pa_startswith(stored, expected);
        pa_xfree(expected);

#if !defined(__OPTIMIZE__)
        if (!good) {
            /* libtool likes to rename our binary names ... */
            expected = pa_sprintf_malloc("%lu (lt-%s)", (unsigned long) pid, procname);
            good = pa_startswith(stored, expected);
            pa_xfree(expected);
        }
#endif

        return !!good;
    }
#endif

    return 1;
}

/* Create a new PID file for the current process. */
int pa_pid_file_create(const char *procname) {
    int fd = -1;
    int ret = -1;
    char t[20];
    pid_t pid;
    size_t l;
    char *fn;

#ifdef OS_IS_WIN32
    HANDLE process;
#endif

    if (!(fn = pa_runtime_path("pid")))
        goto fail;

    if ((fd = open_pid_file(fn, O_CREAT|O_RDWR)) < 0)
        goto fail;

    if ((pid = read_pid(fn, fd)) == (pid_t) -1)
        pa_log_warn("Corrupt PID file, overwriting.");
    else if (pid > 0) {

#ifdef OS_IS_WIN32
        if ((process = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid)) != NULL) {
            CloseHandle(process);
#else
        if (kill(pid, 0) >= 0 || errno != ESRCH) {
#endif
            int ours = 1;

            if (procname)
                if ((ours = proc_name_ours(pid, procname)) < 0)
                    goto fail;

            if (ours) {
                pa_log("Daemon already running.");
                ret = 1;
                goto fail;
            }
        }

        pa_log_warn("Stale PID file, overwriting.");
    }

    /* Overwrite the current PID file */
    if (lseek(fd, 0, SEEK_SET) == (off_t) -1 || ftruncate(fd, 0) < 0) {
        pa_log("Failed to truncate PID file '%s': %s", fn, pa_cstrerror(errno));
        goto fail;
    }

    pa_snprintf(t, sizeof(t), "%lu\n", (unsigned long) getpid());
    l = strlen(t);

    if (pa_loop_write(fd, t, l, NULL) != (ssize_t) l) {
        pa_log("Failed to write PID file.");
        goto fail;
    }

    ret = 0;

fail:
    if (fd >= 0) {
        pa_lock_fd(fd, 0);

        if (pa_close(fd) < 0) {
            pa_log("Failed to close PID file '%s': %s", fn, pa_cstrerror(errno));
            ret = -1;
        }
    }

    pa_xfree(fn);

    return ret;
}

/* Remove the PID file, if it is ours */
int pa_pid_file_remove(void) {
    int fd = -1;
    char *fn;
    int ret = -1;
    pid_t pid;

    if (!(fn = pa_runtime_path("pid")))
        goto fail;

    if ((fd = open_pid_file(fn, O_RDWR)) < 0) {
        pa_log_warn("Failed to open PID file '%s': %s", fn, pa_cstrerror(errno));
        goto fail;
    }

    if ((pid = read_pid(fn, fd)) == (pid_t) -1)
        goto fail;

    if (pid != getpid()) {
        pa_log("PID file '%s' not mine!", fn);
        goto fail;
    }

    if (ftruncate(fd, 0) < 0) {
        pa_log_warn("Failed to truncate PID file '%s': %s", fn, pa_cstrerror(errno));
        goto fail;
    }

#ifdef OS_IS_WIN32
    pa_lock_fd(fd, 0);
    pa_close(fd);
    fd = -1;
#endif

    if (unlink(fn) < 0) {
        pa_log_warn("Failed to remove PID file '%s': %s", fn, pa_cstrerror(errno));
        goto fail;
    }

    ret = 0;

fail:

    if (fd >= 0) {
        pa_lock_fd(fd, 0);

        if (pa_close(fd) < 0) {
            pa_log_warn("Failed to close PID file '%s': %s", fn, pa_cstrerror(errno));
            ret = -1;
        }
    }

    pa_xfree(fn);

    return ret;
}

/* Check whether the daemon is currently running, i.e. if a PID file
 * exists and the PID therein too. Returns 0 on succcess, -1
 * otherwise. If pid is non-NULL and a running daemon was found,
 * return its PID therein */
int pa_pid_file_check_running(pid_t *pid, const char *procname) {
    return pa_pid_file_kill(0, pid, procname);
}

#ifndef OS_IS_WIN32

/* Kill a current running daemon. Return non-zero on success, -1
 * otherwise. If successful *pid contains the PID of the daemon
 * process. */
int pa_pid_file_kill(int sig, pid_t *pid, const char *procname) {
    int fd = -1;
    char *fn;
    int ret = -1;
    pid_t _pid;
#ifdef __linux__
    char *e = NULL;
#endif

    if (!pid)
        pid = &_pid;

    if (!(fn = pa_runtime_path("pid")))
        goto fail;

    if ((fd = open_pid_file(fn, O_RDONLY)) < 0)
        goto fail;

    if ((*pid = read_pid(fn, fd)) == (pid_t) -1)
        goto fail;

    if (procname) {
        int ours;

        if ((ours = proc_name_ours(*pid, procname)) < 0)
            goto fail;

        if (!ours)
            goto fail;
    }

    ret = kill(*pid, sig);

fail:

    if (fd >= 0) {
        pa_lock_fd(fd, 0);
        pa_close(fd);
    }

#ifdef __linux__
    pa_xfree(e);
#endif

    pa_xfree(fn);

    return ret;

}

#else /* OS_IS_WIN32 */

int pa_pid_file_kill(int sig, pid_t *pid, const char *exe_name) {
    return -1;
}

#endif