1 /* Quintuple Agent
2 * Copyright (C) 1999 Robert Bihlmeyer <robbe@orcus.priv.at>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, see <https://www.gnu.org/licenses/>.
16 * SPDX-License-Identifier: GPL-2.0+
17 */
18
19 #ifdef HAVE_CONFIG_H
20 #include <config.h>
21 #endif
22
23 #define _GNU_SOURCE 1
24
25 #include <unistd.h>
26 #ifndef HAVE_W32CE_SYSTEM
27 # include <errno.h>
28 #endif
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <assert.h>
34
35 #include "util.h"
36
37 #ifndef HAVE_DOSISH_SYSTEM
38 static int uid_set = 0;
39 static uid_t real_uid, file_uid;
40 #endif /*!HAVE_DOSISH_SYSTEM*/
41
42 /* Write DATA of size BYTES to FD, until all is written or an error
43 occurs. */
44 ssize_t
xwrite(int fd,const void * data,size_t bytes)45 xwrite(int fd, const void *data, size_t bytes)
46 {
47 char *ptr;
48 size_t todo;
49 ssize_t written = 0;
50
51 for (ptr = (char *)data, todo = bytes; todo; ptr += written, todo -= written)
52 {
53 do
54 written = write (fd, ptr, todo);
55 while (
56 #ifdef HAVE_W32CE_SYSTEM
57 0
58 #else
59 written == -1 && errno == EINTR
60 #endif
61 );
62 if (written < 0)
63 break;
64 }
65 return written;
66 }
67
68 #if 0
69 extern int debug;
70
71 int
72 debugmsg(const char *fmt, ...)
73 {
74 va_list va;
75 int ret;
76
77 if (debug) {
78 va_start(va, fmt);
79 fprintf(stderr, "\e[4m");
80 ret = vfprintf(stderr, fmt, va);
81 fprintf(stderr, "\e[24m");
82 va_end(va);
83 return ret;
84 } else
85 return 0;
86 }
87 #endif
88
89 /* initialize uid variables */
90 #ifndef HAVE_DOSISH_SYSTEM
91 static void
init_uids(void)92 init_uids(void)
93 {
94 real_uid = getuid();
95 file_uid = geteuid();
96 uid_set = 1;
97 }
98 #endif
99
100
101 /* drop all additional privileges */
102 void
drop_privs()103 drop_privs()
104 {
105 #ifndef HAVE_DOSISH_SYSTEM
106 if (!uid_set)
107 init_uids();
108 if (real_uid != file_uid) {
109 if (setuid(real_uid) < 0) {
110 perror("dropping privileges failed");
111 exit(EXIT_FAILURE);
112 }
113 file_uid = real_uid;
114 }
115 #endif
116 }
117