s4-process_model: Do not close random fds while forking.
[Samba.git] / source3 / lib / system.c
blob4f3859749697ce7193d6ffc5ccabfb92b87eb8dd
1 /*
2 Unix SMB/CIFS implementation.
3 Samba system utilities
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 1998-2005
6 Copyright (C) Timur Bakeyev 2005
7 Copyright (C) Bjoern Jacke 2006-2007
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "includes.h"
24 #include "system/syslog.h"
25 #include "system/capability.h"
26 #include "system/passwd.h"
27 #include "system/filesys.h"
28 #include "../lib/util/setid.h"
30 #ifdef HAVE_SYS_SYSCTL_H
31 #include <sys/sysctl.h>
32 #endif
34 #ifdef HAVE_SYS_PRCTL_H
35 #include <sys/prctl.h>
36 #endif
39 The idea is that this file will eventually have wrappers around all
40 important system calls in samba. The aims are:
42 - to enable easier porting by putting OS dependent stuff in here
44 - to allow for hooks into other "pseudo-filesystems"
46 - to allow easier integration of things like the japanese extensions
48 - to support the philosophy of Samba to expose the features of
49 the OS within the SMB model. In general whatever file/printer/variable
50 expansions/etc make sense to the OS should be acceptable to Samba.
55 /*******************************************************************
56 A read wrapper that will deal with EINTR.
57 ********************************************************************/
59 ssize_t sys_read(int fd, void *buf, size_t count)
61 ssize_t ret;
63 do {
64 ret = read(fd, buf, count);
65 #if defined(EWOULDBLOCK)
66 } while (ret == -1 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK));
67 #else
68 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
69 #endif
70 return ret;
73 /*******************************************************************
74 A write wrapper that will deal with EINTR.
75 ********************************************************************/
77 ssize_t sys_write(int fd, const void *buf, size_t count)
79 ssize_t ret;
81 do {
82 ret = write(fd, buf, count);
83 #if defined(EWOULDBLOCK)
84 } while (ret == -1 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK));
85 #else
86 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
87 #endif
88 return ret;
91 /*******************************************************************
92 A writev wrapper that will deal with EINTR.
93 ********************************************************************/
95 ssize_t sys_writev(int fd, const struct iovec *iov, int iovcnt)
97 ssize_t ret;
99 #if 0
100 /* Try to confuse write_data_iov a bit */
101 if ((random() % 5) == 0) {
102 return sys_write(fd, iov[0].iov_base, iov[0].iov_len);
104 if (iov[0].iov_len > 1) {
105 return sys_write(fd, iov[0].iov_base,
106 (random() % (iov[0].iov_len-1)) + 1);
108 #endif
110 do {
111 ret = writev(fd, iov, iovcnt);
112 #if defined(EWOULDBLOCK)
113 } while (ret == -1 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK));
114 #else
115 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
116 #endif
117 return ret;
120 /*******************************************************************
121 A pread wrapper that will deal with EINTR
122 ********************************************************************/
124 #if defined(HAVE_PREAD)
125 ssize_t sys_pread(int fd, void *buf, size_t count, off_t off)
127 ssize_t ret;
129 do {
130 ret = pread(fd, buf, count, off);
131 } while (ret == -1 && errno == EINTR);
132 return ret;
134 #endif
136 /*******************************************************************
137 A write wrapper that will deal with EINTR
138 ********************************************************************/
140 #if defined(HAVE_PWRITE)
141 ssize_t sys_pwrite(int fd, const void *buf, size_t count, off_t off)
143 ssize_t ret;
145 do {
146 ret = pwrite(fd, buf, count, off);
147 } while (ret == -1 && errno == EINTR);
148 return ret;
150 #endif
152 /*******************************************************************
153 A send wrapper that will deal with EINTR or EAGAIN or EWOULDBLOCK.
154 ********************************************************************/
156 ssize_t sys_send(int s, const void *msg, size_t len, int flags)
158 ssize_t ret;
160 do {
161 ret = send(s, msg, len, flags);
162 #if defined(EWOULDBLOCK)
163 } while (ret == -1 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK));
164 #else
165 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
166 #endif
167 return ret;
170 /*******************************************************************
171 A recvfrom wrapper that will deal with EINTR.
172 NB. As used with non-blocking sockets, return on EAGAIN/EWOULDBLOCK
173 ********************************************************************/
175 ssize_t sys_recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen)
177 ssize_t ret;
179 do {
180 ret = recvfrom(s, buf, len, flags, from, fromlen);
181 } while (ret == -1 && (errno == EINTR));
182 return ret;
185 /*******************************************************************
186 A fcntl wrapper that will deal with EINTR.
187 ********************************************************************/
189 int sys_fcntl_ptr(int fd, int cmd, void *arg)
191 int ret;
193 do {
194 ret = fcntl(fd, cmd, arg);
195 } while (ret == -1 && errno == EINTR);
196 return ret;
199 /*******************************************************************
200 A fcntl wrapper that will deal with EINTR.
201 ********************************************************************/
203 int sys_fcntl_long(int fd, int cmd, long arg)
205 int ret;
207 do {
208 ret = fcntl(fd, cmd, arg);
209 } while (ret == -1 && errno == EINTR);
210 return ret;
213 /****************************************************************************
214 Get/Set all the possible time fields from a stat struct as a timespec.
215 ****************************************************************************/
217 static struct timespec get_atimespec(const struct stat *pst)
219 #if !defined(HAVE_STAT_HIRES_TIMESTAMPS)
220 struct timespec ret;
222 /* Old system - no ns timestamp. */
223 ret.tv_sec = pst->st_atime;
224 ret.tv_nsec = 0;
225 return ret;
226 #else
227 #if defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
228 struct timespec ret;
229 ret.tv_sec = pst->st_atim.tv_sec;
230 ret.tv_nsec = pst->st_atim.tv_nsec;
231 return ret;
232 #elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
233 struct timespec ret;
234 ret.tv_sec = pst->st_atime;
235 ret.tv_nsec = pst->st_atimensec;
236 return ret;
237 #elif defined(HAVE_STRUCT_STAT_ST_MTIME_N)
238 struct timespec ret;
239 ret.tv_sec = pst->st_atime;
240 ret.tv_nsec = pst->st_atime_n;
241 return ret;
242 #elif defined(HAVE_STRUCT_STAT_ST_UMTIME)
243 struct timespec ret;
244 ret.tv_sec = pst->st_atime;
245 ret.tv_nsec = pst->st_uatime * 1000;
246 return ret;
247 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
248 return pst->st_atimespec;
249 #else
250 #error CONFIGURE_ERROR_IN_DETECTING_TIMESPEC_IN_STAT
251 #endif
252 #endif
255 static struct timespec get_mtimespec(const struct stat *pst)
257 #if !defined(HAVE_STAT_HIRES_TIMESTAMPS)
258 struct timespec ret;
260 /* Old system - no ns timestamp. */
261 ret.tv_sec = pst->st_mtime;
262 ret.tv_nsec = 0;
263 return ret;
264 #else
265 #if defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
266 struct timespec ret;
267 ret.tv_sec = pst->st_mtim.tv_sec;
268 ret.tv_nsec = pst->st_mtim.tv_nsec;
269 return ret;
270 #elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
271 struct timespec ret;
272 ret.tv_sec = pst->st_mtime;
273 ret.tv_nsec = pst->st_mtimensec;
274 return ret;
275 #elif defined(HAVE_STRUCT_STAT_ST_MTIME_N)
276 struct timespec ret;
277 ret.tv_sec = pst->st_mtime;
278 ret.tv_nsec = pst->st_mtime_n;
279 return ret;
280 #elif defined(HAVE_STRUCT_STAT_ST_UMTIME)
281 struct timespec ret;
282 ret.tv_sec = pst->st_mtime;
283 ret.tv_nsec = pst->st_umtime * 1000;
284 return ret;
285 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
286 return pst->st_mtimespec;
287 #else
288 #error CONFIGURE_ERROR_IN_DETECTING_TIMESPEC_IN_STAT
289 #endif
290 #endif
293 static struct timespec get_ctimespec(const struct stat *pst)
295 #if !defined(HAVE_STAT_HIRES_TIMESTAMPS)
296 struct timespec ret;
298 /* Old system - no ns timestamp. */
299 ret.tv_sec = pst->st_ctime;
300 ret.tv_nsec = 0;
301 return ret;
302 #else
303 #if defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
304 struct timespec ret;
305 ret.tv_sec = pst->st_ctim.tv_sec;
306 ret.tv_nsec = pst->st_ctim.tv_nsec;
307 return ret;
308 #elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
309 struct timespec ret;
310 ret.tv_sec = pst->st_ctime;
311 ret.tv_nsec = pst->st_ctimensec;
312 return ret;
313 #elif defined(HAVE_STRUCT_STAT_ST_MTIME_N)
314 struct timespec ret;
315 ret.tv_sec = pst->st_ctime;
316 ret.tv_nsec = pst->st_ctime_n;
317 return ret;
318 #elif defined(HAVE_STRUCT_STAT_ST_UMTIME)
319 struct timespec ret;
320 ret.tv_sec = pst->st_ctime;
321 ret.tv_nsec = pst->st_uctime * 1000;
322 return ret;
323 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
324 return pst->st_ctimespec;
325 #else
326 #error CONFIGURE_ERROR_IN_DETECTING_TIMESPEC_IN_STAT
327 #endif
328 #endif
331 /****************************************************************************
332 Return the best approximation to a 'create time' under UNIX from a stat
333 structure.
334 ****************************************************************************/
336 static struct timespec calc_create_time_stat(const struct stat *st)
338 struct timespec ret, ret1;
339 struct timespec c_time = get_ctimespec(st);
340 struct timespec m_time = get_mtimespec(st);
341 struct timespec a_time = get_atimespec(st);
343 ret = timespec_compare(&c_time, &m_time) < 0 ? c_time : m_time;
344 ret1 = timespec_compare(&ret, &a_time) < 0 ? ret : a_time;
346 if(!null_timespec(ret1)) {
347 return ret1;
351 * One of ctime, mtime or atime was zero (probably atime).
352 * Just return MIN(ctime, mtime).
354 return ret;
357 /****************************************************************************
358 Return the best approximation to a 'create time' under UNIX from a stat_ex
359 structure.
360 ****************************************************************************/
362 static struct timespec calc_create_time_stat_ex(const struct stat_ex *st)
364 struct timespec ret, ret1;
365 struct timespec c_time = st->st_ex_ctime;
366 struct timespec m_time = st->st_ex_mtime;
367 struct timespec a_time = st->st_ex_atime;
369 ret = timespec_compare(&c_time, &m_time) < 0 ? c_time : m_time;
370 ret1 = timespec_compare(&ret, &a_time) < 0 ? ret : a_time;
372 if(!null_timespec(ret1)) {
373 return ret1;
377 * One of ctime, mtime or atime was zero (probably atime).
378 * Just return MIN(ctime, mtime).
380 return ret;
383 /****************************************************************************
384 Return the 'create time' from a stat struct if it exists (birthtime) or else
385 use the best approximation.
386 ****************************************************************************/
388 static void make_create_timespec(const struct stat *pst, struct stat_ex *dst,
389 bool fake_dir_create_times)
391 if (S_ISDIR(pst->st_mode) && fake_dir_create_times) {
392 dst->st_ex_btime.tv_sec = 315493200L; /* 1/1/1980 */
393 dst->st_ex_btime.tv_nsec = 0;
396 dst->st_ex_calculated_birthtime = false;
398 #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC)
399 dst->st_ex_btime = pst->st_birthtimespec;
400 #elif defined(HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC)
401 dst->st_ex_btime.tv_sec = pst->st_birthtime;
402 dst->st_ex_btime.tv_nsec = pst->st_birthtimenspec;
403 #elif defined(HAVE_STRUCT_STAT_ST_BIRTHTIME)
404 dst->st_ex_btime.tv_sec = pst->st_birthtime;
405 dst->st_ex_btime.tv_nsec = 0;
406 #else
407 dst->st_ex_btime = calc_create_time_stat(pst);
408 dst->st_ex_calculated_birthtime = true;
409 #endif
411 /* Deal with systems that don't initialize birthtime correctly.
412 * Pointed out by SATOH Fumiyasu <fumiyas@osstech.jp>.
414 if (null_timespec(dst->st_ex_btime)) {
415 dst->st_ex_btime = calc_create_time_stat(pst);
416 dst->st_ex_calculated_birthtime = true;
420 /****************************************************************************
421 If we update a timestamp in a stat_ex struct we may have to recalculate
422 the birthtime. For now only implement this for write time, but we may
423 also need to do it for atime and ctime. JRA.
424 ****************************************************************************/
426 void update_stat_ex_mtime(struct stat_ex *dst,
427 struct timespec write_ts)
429 dst->st_ex_mtime = write_ts;
431 /* We may have to recalculate btime. */
432 if (dst->st_ex_calculated_birthtime) {
433 dst->st_ex_btime = calc_create_time_stat_ex(dst);
437 void update_stat_ex_create_time(struct stat_ex *dst,
438 struct timespec create_time)
440 dst->st_ex_btime = create_time;
441 dst->st_ex_calculated_birthtime = false;
444 void init_stat_ex_from_stat (struct stat_ex *dst,
445 const struct stat *src,
446 bool fake_dir_create_times)
448 dst->st_ex_dev = src->st_dev;
449 dst->st_ex_ino = src->st_ino;
450 dst->st_ex_mode = src->st_mode;
451 dst->st_ex_nlink = src->st_nlink;
452 dst->st_ex_uid = src->st_uid;
453 dst->st_ex_gid = src->st_gid;
454 dst->st_ex_rdev = src->st_rdev;
455 dst->st_ex_size = src->st_size;
456 dst->st_ex_atime = get_atimespec(src);
457 dst->st_ex_mtime = get_mtimespec(src);
458 dst->st_ex_ctime = get_ctimespec(src);
459 make_create_timespec(src, dst, fake_dir_create_times);
460 #ifdef HAVE_STAT_ST_BLKSIZE
461 dst->st_ex_blksize = src->st_blksize;
462 #else
463 dst->st_ex_blksize = STAT_ST_BLOCKSIZE;
464 #endif
466 #ifdef HAVE_STAT_ST_BLOCKS
467 dst->st_ex_blocks = src->st_blocks;
468 #else
469 dst->st_ex_blocks = src->st_size / dst->st_ex_blksize + 1;
470 #endif
472 #ifdef HAVE_STAT_ST_FLAGS
473 dst->st_ex_flags = src->st_flags;
474 #else
475 dst->st_ex_flags = 0;
476 #endif
479 /*******************************************************************
480 A stat() wrapper.
481 ********************************************************************/
483 int sys_stat(const char *fname, SMB_STRUCT_STAT *sbuf,
484 bool fake_dir_create_times)
486 int ret;
487 struct stat statbuf;
488 ret = stat(fname, &statbuf);
489 if (ret == 0) {
490 /* we always want directories to appear zero size */
491 if (S_ISDIR(statbuf.st_mode)) {
492 statbuf.st_size = 0;
494 init_stat_ex_from_stat(sbuf, &statbuf, fake_dir_create_times);
496 return ret;
499 /*******************************************************************
500 An fstat() wrapper.
501 ********************************************************************/
503 int sys_fstat(int fd, SMB_STRUCT_STAT *sbuf, bool fake_dir_create_times)
505 int ret;
506 struct stat statbuf;
507 ret = fstat(fd, &statbuf);
508 if (ret == 0) {
509 /* we always want directories to appear zero size */
510 if (S_ISDIR(statbuf.st_mode)) {
511 statbuf.st_size = 0;
513 init_stat_ex_from_stat(sbuf, &statbuf, fake_dir_create_times);
515 return ret;
518 /*******************************************************************
519 An lstat() wrapper.
520 ********************************************************************/
522 int sys_lstat(const char *fname,SMB_STRUCT_STAT *sbuf,
523 bool fake_dir_create_times)
525 int ret;
526 struct stat statbuf;
527 ret = lstat(fname, &statbuf);
528 if (ret == 0) {
529 /* we always want directories to appear zero size */
530 if (S_ISDIR(statbuf.st_mode)) {
531 statbuf.st_size = 0;
533 init_stat_ex_from_stat(sbuf, &statbuf, fake_dir_create_times);
535 return ret;
538 /*******************************************************************
539 An posix_fallocate() wrapper.
540 ********************************************************************/
541 int sys_posix_fallocate(int fd, off_t offset, off_t len)
543 #if defined(HAVE_POSIX_FALLOCATE) && !defined(HAVE_BROKEN_POSIX_FALLOCATE)
544 return posix_fallocate(fd, offset, len);
545 #elif defined(F_RESVSP64)
546 /* this handles XFS on IRIX */
547 struct flock64 fl;
548 off_t new_len = offset + len;
549 int ret;
550 struct stat64 sbuf;
552 /* unlikely to get a too large file on a 64bit system but ... */
553 if (new_len < 0)
554 return EFBIG;
556 fl.l_whence = SEEK_SET;
557 fl.l_start = offset;
558 fl.l_len = len;
560 ret=fcntl(fd, F_RESVSP64, &fl);
562 if (ret != 0)
563 return errno;
565 /* Make sure the file gets enlarged after we allocated space: */
566 fstat64(fd, &sbuf);
567 if (new_len > sbuf.st_size)
568 ftruncate64(fd, new_len);
569 return 0;
570 #else
571 return ENOSYS;
572 #endif
575 /*******************************************************************
576 An fallocate() function that matches the semantics of the Linux one.
577 ********************************************************************/
579 #ifdef HAVE_LINUX_FALLOC_H
580 #include <linux/falloc.h>
581 #endif
583 int sys_fallocate(int fd, enum vfs_fallocate_mode mode, off_t offset, off_t len)
585 #if defined(HAVE_LINUX_FALLOCATE64) || defined(HAVE_LINUX_FALLOCATE)
586 int lmode;
587 switch (mode) {
588 case VFS_FALLOCATE_EXTEND_SIZE:
589 lmode = 0;
590 break;
591 case VFS_FALLOCATE_KEEP_SIZE:
592 lmode = FALLOC_FL_KEEP_SIZE;
593 break;
594 default:
595 errno = EINVAL;
596 return -1;
598 #if defined(HAVE_LINUX_FALLOCATE)
599 return fallocate(fd, lmode, offset, len);
600 #endif
601 #else
602 /* TODO - plumb in fallocate from other filesysetms like VXFS etc. JRA. */
603 errno = ENOSYS;
604 return -1;
605 #endif
608 #if HAVE_KERNEL_SHARE_MODES
609 #ifndef LOCK_MAND
610 #define LOCK_MAND 32 /* This is a mandatory flock */
611 #define LOCK_READ 64 /* ... Which allows concurrent read operations */
612 #define LOCK_WRITE 128 /* ... Which allows concurrent write operations */
613 #define LOCK_RW 192 /* ... Which allows concurrent read & write ops */
614 #endif
615 #endif
617 /*******************************************************************
618 A flock() wrapper that will perform the kernel flock.
619 ********************************************************************/
621 void kernel_flock(int fd, uint32 share_mode, uint32 access_mask)
623 #if HAVE_KERNEL_SHARE_MODES
624 int kernel_mode = 0;
625 if (share_mode == FILE_SHARE_WRITE) {
626 kernel_mode = LOCK_MAND|LOCK_WRITE;
627 } else if (share_mode == FILE_SHARE_READ) {
628 kernel_mode = LOCK_MAND|LOCK_READ;
629 } else if (share_mode == FILE_SHARE_NONE) {
630 kernel_mode = LOCK_MAND;
632 if (kernel_mode) {
633 flock(fd, kernel_mode);
635 #endif
641 /*******************************************************************
642 An fdopendir wrapper.
643 ********************************************************************/
645 DIR *sys_fdopendir(int fd)
647 #if defined(HAVE_FDOPENDIR)
648 return fdopendir(fd);
649 #else
650 errno = ENOSYS;
651 return NULL;
652 #endif
655 /*******************************************************************
656 An mknod() wrapper.
657 ********************************************************************/
659 int sys_mknod(const char *path, mode_t mode, SMB_DEV_T dev)
661 #if defined(HAVE_MKNOD)
662 return mknod(path, mode, dev);
663 #else
664 /* No mknod system call. */
665 errno = ENOSYS;
666 return -1;
667 #endif
670 /*******************************************************************
671 The wait() calls vary between systems
672 ********************************************************************/
674 int sys_waitpid(pid_t pid,int *status,int options)
676 #ifdef HAVE_WAITPID
677 return waitpid(pid,status,options);
678 #else /* HAVE_WAITPID */
679 return wait4(pid, status, options, NULL);
680 #endif /* HAVE_WAITPID */
683 /*******************************************************************
684 System wrapper for getwd. Always returns MALLOC'ed memory, or NULL
685 on error (malloc fail usually).
686 ********************************************************************/
688 char *sys_getwd(void)
690 #ifdef GETCWD_TAKES_NULL
691 return getcwd(NULL, 0);
692 #elif HAVE_GETCWD
693 char *wd = NULL, *s = NULL;
694 size_t allocated = PATH_MAX;
696 while (1) {
697 s = SMB_REALLOC_ARRAY(s, char, allocated);
698 if (s == NULL) {
699 return NULL;
701 wd = getcwd(s, allocated);
702 if (wd) {
703 break;
705 if (errno != ERANGE) {
706 SAFE_FREE(s);
707 break;
709 allocated *= 2;
710 if (allocated < PATH_MAX) {
711 SAFE_FREE(s);
712 break;
715 return wd;
716 #else
717 char *s = SMB_MALLOC_ARRAY(char, PATH_MAX);
718 if (s == NULL) {
719 return NULL;
721 return getwd(s);
722 #endif
725 #if defined(HAVE_POSIX_CAPABILITIES)
727 /**************************************************************************
728 Try and abstract process capabilities (for systems that have them).
729 ****************************************************************************/
731 /* Set the POSIX capabilities needed for the given purpose into the effective
732 * capability set of the current process. Make sure they are always removed
733 * from the inheritable set, because there is no circumstance in which our
734 * children should inherit our elevated privileges.
736 static bool set_process_capability(enum smbd_capability capability,
737 bool enable)
739 cap_value_t cap_vals[2] = {0};
740 int num_cap_vals = 0;
742 cap_t cap;
744 #if defined(HAVE_PRCTL) && defined(PR_GET_KEEPCAPS) && defined(PR_SET_KEEPCAPS)
745 /* On Linux, make sure that any capabilities we grab are sticky
746 * across UID changes. We expect that this would allow us to keep both
747 * the effective and permitted capability sets, but as of circa 2.6.16,
748 * only the permitted set is kept. It is a bug (which we work around)
749 * that the effective set is lost, but we still require the effective
750 * set to be kept.
752 if (!prctl(PR_GET_KEEPCAPS)) {
753 prctl(PR_SET_KEEPCAPS, 1);
755 #endif
757 cap = cap_get_proc();
758 if (cap == NULL) {
759 DEBUG(0,("set_process_capability: cap_get_proc failed: %s\n",
760 strerror(errno)));
761 return False;
764 switch (capability) {
765 case KERNEL_OPLOCK_CAPABILITY:
766 #ifdef CAP_NETWORK_MGT
767 /* IRIX has CAP_NETWORK_MGT for oplocks. */
768 cap_vals[num_cap_vals++] = CAP_NETWORK_MGT;
769 #endif
770 break;
771 case DMAPI_ACCESS_CAPABILITY:
772 #ifdef CAP_DEVICE_MGT
773 /* IRIX has CAP_DEVICE_MGT for DMAPI access. */
774 cap_vals[num_cap_vals++] = CAP_DEVICE_MGT;
775 #elif CAP_MKNOD
776 /* Linux has CAP_MKNOD for DMAPI access. */
777 cap_vals[num_cap_vals++] = CAP_MKNOD;
778 #endif
779 break;
780 case LEASE_CAPABILITY:
781 #ifdef CAP_LEASE
782 cap_vals[num_cap_vals++] = CAP_LEASE;
783 #endif
784 break;
787 SMB_ASSERT(num_cap_vals <= ARRAY_SIZE(cap_vals));
789 if (num_cap_vals == 0) {
790 cap_free(cap);
791 return True;
794 cap_set_flag(cap, CAP_EFFECTIVE, num_cap_vals, cap_vals,
795 enable ? CAP_SET : CAP_CLEAR);
797 /* We never want to pass capabilities down to our children, so make
798 * sure they are not inherited.
800 cap_set_flag(cap, CAP_INHERITABLE, num_cap_vals, cap_vals, CAP_CLEAR);
802 if (cap_set_proc(cap) == -1) {
803 DEBUG(0, ("set_process_capability: cap_set_proc failed: %s\n",
804 strerror(errno)));
805 cap_free(cap);
806 return False;
809 cap_free(cap);
810 return True;
813 #endif /* HAVE_POSIX_CAPABILITIES */
815 /****************************************************************************
816 Gain the oplock capability from the kernel if possible.
817 ****************************************************************************/
819 void set_effective_capability(enum smbd_capability capability)
821 #if defined(HAVE_POSIX_CAPABILITIES)
822 set_process_capability(capability, True);
823 #endif /* HAVE_POSIX_CAPABILITIES */
826 void drop_effective_capability(enum smbd_capability capability)
828 #if defined(HAVE_POSIX_CAPABILITIES)
829 set_process_capability(capability, False);
830 #endif /* HAVE_POSIX_CAPABILITIES */
833 /**************************************************************************
834 Wrapper for random().
835 ****************************************************************************/
837 long sys_random(void)
839 #if defined(HAVE_RANDOM)
840 return (long)random();
841 #elif defined(HAVE_RAND)
842 return (long)rand();
843 #else
844 DEBUG(0,("Error - no random function available !\n"));
845 exit(1);
846 #endif
849 /**************************************************************************
850 Wrapper for srandom().
851 ****************************************************************************/
853 void sys_srandom(unsigned int seed)
855 #if defined(HAVE_SRANDOM)
856 srandom(seed);
857 #elif defined(HAVE_SRAND)
858 srand(seed);
859 #else
860 DEBUG(0,("Error - no srandom function available !\n"));
861 exit(1);
862 #endif
865 #ifndef NGROUPS_MAX
866 #define NGROUPS_MAX 32 /* Guess... */
867 #endif
869 /**************************************************************************
870 Returns equivalent to NGROUPS_MAX - using sysconf if needed.
871 ****************************************************************************/
873 int groups_max(void)
875 #if defined(SYSCONF_SC_NGROUPS_MAX)
876 int ret = sysconf(_SC_NGROUPS_MAX);
877 return (ret == -1) ? NGROUPS_MAX : ret;
878 #else
879 return NGROUPS_MAX;
880 #endif
883 /**************************************************************************
884 Wrap setgroups and getgroups for systems that declare getgroups() as
885 returning an array of gid_t, but actuall return an array of int.
886 ****************************************************************************/
888 #if defined(HAVE_BROKEN_GETGROUPS)
890 #ifdef HAVE_BROKEN_GETGROUPS
891 #define GID_T int
892 #else
893 #define GID_T gid_t
894 #endif
896 static int sys_broken_getgroups(int setlen, gid_t *gidset)
898 GID_T gid;
899 GID_T *group_list;
900 int i, ngroups;
902 if(setlen == 0) {
903 return getgroups(setlen, &gid);
907 * Broken case. We need to allocate a
908 * GID_T array of size setlen.
911 if(setlen < 0) {
912 errno = EINVAL;
913 return -1;
916 if (setlen == 0)
917 setlen = groups_max();
919 if((group_list = SMB_MALLOC_ARRAY(GID_T, setlen)) == NULL) {
920 DEBUG(0,("sys_getgroups: Malloc fail.\n"));
921 return -1;
924 if((ngroups = getgroups(setlen, group_list)) < 0) {
925 int saved_errno = errno;
926 SAFE_FREE(group_list);
927 errno = saved_errno;
928 return -1;
931 for(i = 0; i < ngroups; i++)
932 gidset[i] = (gid_t)group_list[i];
934 SAFE_FREE(group_list);
935 return ngroups;
938 static int sys_broken_setgroups(int setlen, gid_t *gidset)
940 GID_T *group_list;
941 int i ;
943 if (setlen == 0)
944 return 0 ;
946 if (setlen < 0 || setlen > groups_max()) {
947 errno = EINVAL;
948 return -1;
952 * Broken case. We need to allocate a
953 * GID_T array of size setlen.
956 if((group_list = SMB_MALLOC_ARRAY(GID_T, setlen)) == NULL) {
957 DEBUG(0,("sys_setgroups: Malloc fail.\n"));
958 return -1;
961 for(i = 0; i < setlen; i++)
962 group_list[i] = (GID_T) gidset[i];
964 if(samba_setgroups(setlen, group_list) != 0) {
965 int saved_errno = errno;
966 SAFE_FREE(group_list);
967 errno = saved_errno;
968 return -1;
971 SAFE_FREE(group_list);
972 return 0 ;
975 #endif /* HAVE_BROKEN_GETGROUPS */
977 /* This is a list of systems that require the first GID passed to setgroups(2)
978 * to be the effective GID. If your system is one of these, add it here.
980 #if defined (FREEBSD) || defined (DARWINOS)
981 #define USE_BSD_SETGROUPS
982 #endif
984 #if defined(USE_BSD_SETGROUPS)
985 /* Depending on the particular BSD implementation, the first GID that is
986 * passed to setgroups(2) will either be ignored or will set the credential's
987 * effective GID. In either case, the right thing to do is to guarantee that
988 * gidset[0] is the effective GID.
990 static int sys_bsd_setgroups(gid_t primary_gid, int setlen, const gid_t *gidset)
992 gid_t *new_gidset = NULL;
993 int max;
994 int ret;
996 /* setgroups(2) will fail with EINVAL if we pass too many groups. */
997 max = groups_max();
999 /* No group list, just make sure we are setting the efective GID. */
1000 if (setlen == 0) {
1001 return samba_setgroups(1, &primary_gid);
1004 /* If the primary gid is not the first array element, grow the array
1005 * and insert it at the front.
1007 if (gidset[0] != primary_gid) {
1008 new_gidset = SMB_MALLOC_ARRAY(gid_t, setlen + 1);
1009 if (new_gidset == NULL) {
1010 return -1;
1013 memcpy(new_gidset + 1, gidset, (setlen * sizeof(gid_t)));
1014 new_gidset[0] = primary_gid;
1015 setlen++;
1018 if (setlen > max) {
1019 DEBUG(3, ("forced to truncate group list from %d to %d\n",
1020 setlen, max));
1021 setlen = max;
1024 #if defined(HAVE_BROKEN_GETGROUPS)
1025 ret = sys_broken_setgroups(setlen, new_gidset ? new_gidset : gidset);
1026 #else
1027 ret = samba_setgroups(setlen, new_gidset ? new_gidset : gidset);
1028 #endif
1030 if (new_gidset) {
1031 int errsav = errno;
1032 SAFE_FREE(new_gidset);
1033 errno = errsav;
1036 return ret;
1039 #endif /* USE_BSD_SETGROUPS */
1041 /**************************************************************************
1042 Wrapper for getgroups. Deals with broken (int) case.
1043 ****************************************************************************/
1045 int sys_getgroups(int setlen, gid_t *gidset)
1047 #if defined(HAVE_BROKEN_GETGROUPS)
1048 return sys_broken_getgroups(setlen, gidset);
1049 #else
1050 return getgroups(setlen, gidset);
1051 #endif
1054 /**************************************************************************
1055 Wrapper for setgroups. Deals with broken (int) case and BSD case.
1056 ****************************************************************************/
1058 int sys_setgroups(gid_t UNUSED(primary_gid), int setlen, gid_t *gidset)
1060 #if !defined(HAVE_SETGROUPS)
1061 errno = ENOSYS;
1062 return -1;
1063 #endif /* HAVE_SETGROUPS */
1065 #if defined(USE_BSD_SETGROUPS)
1066 return sys_bsd_setgroups(primary_gid, setlen, gidset);
1067 #elif defined(HAVE_BROKEN_GETGROUPS)
1068 return sys_broken_setgroups(setlen, gidset);
1069 #else
1070 return samba_setgroups(setlen, gidset);
1071 #endif
1074 /**************************************************************************
1075 Extract a command into an arg list.
1076 ****************************************************************************/
1078 static char **extract_args(TALLOC_CTX *mem_ctx, const char *command)
1080 char *trunc_cmd;
1081 char *saveptr;
1082 char *ptr;
1083 int argcl;
1084 char **argl = NULL;
1085 int i;
1087 if (!(trunc_cmd = talloc_strdup(mem_ctx, command))) {
1088 DEBUG(0, ("talloc failed\n"));
1089 goto nomem;
1092 if(!(ptr = strtok_r(trunc_cmd, " \t", &saveptr))) {
1093 TALLOC_FREE(trunc_cmd);
1094 errno = EINVAL;
1095 return NULL;
1099 * Count the args.
1102 for( argcl = 1; ptr; ptr = strtok_r(NULL, " \t", &saveptr))
1103 argcl++;
1105 TALLOC_FREE(trunc_cmd);
1107 if (!(argl = talloc_array(mem_ctx, char *, argcl + 1))) {
1108 goto nomem;
1112 * Now do the extraction.
1115 if (!(trunc_cmd = talloc_strdup(mem_ctx, command))) {
1116 goto nomem;
1119 ptr = strtok_r(trunc_cmd, " \t", &saveptr);
1120 i = 0;
1122 if (!(argl[i++] = talloc_strdup(argl, ptr))) {
1123 goto nomem;
1126 while((ptr = strtok_r(NULL, " \t", &saveptr)) != NULL) {
1128 if (!(argl[i++] = talloc_strdup(argl, ptr))) {
1129 goto nomem;
1133 argl[i++] = NULL;
1134 TALLOC_FREE(trunc_cmd);
1135 return argl;
1137 nomem:
1138 DEBUG(0, ("talloc failed\n"));
1139 TALLOC_FREE(trunc_cmd);
1140 TALLOC_FREE(argl);
1141 errno = ENOMEM;
1142 return NULL;
1145 /**************************************************************************
1146 Wrapper for popen. Safer as it doesn't search a path.
1147 Modified from the glibc sources.
1148 modified by tridge to return a file descriptor. We must kick our FILE* habit
1149 ****************************************************************************/
1151 typedef struct _popen_list
1153 int fd;
1154 pid_t child_pid;
1155 struct _popen_list *next;
1156 } popen_list;
1158 static popen_list *popen_chain;
1160 int sys_popen(const char *command)
1162 int parent_end, child_end;
1163 int pipe_fds[2];
1164 popen_list *entry = NULL;
1165 char **argl = NULL;
1166 int ret;
1168 if (!*command) {
1169 errno = EINVAL;
1170 return -1;
1173 ret = pipe(pipe_fds);
1174 if (ret < 0) {
1175 DEBUG(0, ("sys_popen: error opening pipe: %s\n",
1176 strerror(errno)));
1177 return -1;
1180 parent_end = pipe_fds[0];
1181 child_end = pipe_fds[1];
1183 entry = SMB_MALLOC_P(popen_list);
1184 if (entry == NULL) {
1185 DEBUG(0, ("sys_popen: malloc failed\n"));
1186 goto err_exit;
1189 ZERO_STRUCTP(entry);
1192 * Extract the command and args into a NULL terminated array.
1195 argl = extract_args(NULL, command);
1196 if (argl == NULL) {
1197 DEBUG(0, ("sys_popen: extract_args() failed: %s\n", strerror(errno)));
1198 goto err_exit;
1201 entry->child_pid = fork();
1203 if (entry->child_pid == -1) {
1204 DEBUG(0, ("sys_popen: fork failed: %s\n", strerror(errno)));
1205 goto err_exit;
1208 if (entry->child_pid == 0) {
1211 * Child !
1214 int child_std_end = STDOUT_FILENO;
1215 popen_list *p;
1217 close(parent_end);
1218 if (child_end != child_std_end) {
1219 dup2 (child_end, child_std_end);
1220 close (child_end);
1224 * POSIX.2: "popen() shall ensure that any streams from previous
1225 * popen() calls that remain open in the parent process are closed
1226 * in the new child process."
1229 for (p = popen_chain; p; p = p->next)
1230 close(p->fd);
1232 ret = execv(argl[0], argl);
1233 if (ret == -1) {
1234 DEBUG(0, ("sys_popen: ERROR executing command "
1235 "'%s': %s\n", command, strerror(errno)));
1237 _exit (127);
1241 * Parent.
1244 close (child_end);
1245 TALLOC_FREE(argl);
1247 /* Link into popen_chain. */
1248 entry->next = popen_chain;
1249 popen_chain = entry;
1250 entry->fd = parent_end;
1252 return entry->fd;
1254 err_exit:
1256 SAFE_FREE(entry);
1257 TALLOC_FREE(argl);
1258 close(pipe_fds[0]);
1259 close(pipe_fds[1]);
1260 return -1;
1263 /**************************************************************************
1264 Wrapper for pclose. Modified from the glibc sources.
1265 ****************************************************************************/
1267 int sys_pclose(int fd)
1269 int wstatus;
1270 popen_list **ptr = &popen_chain;
1271 popen_list *entry = NULL;
1272 pid_t wait_pid;
1273 int status = -1;
1275 /* Unlink from popen_chain. */
1276 for ( ; *ptr != NULL; ptr = &(*ptr)->next) {
1277 if ((*ptr)->fd == fd) {
1278 entry = *ptr;
1279 *ptr = (*ptr)->next;
1280 status = 0;
1281 break;
1285 if (status < 0 || close(entry->fd) < 0)
1286 return -1;
1289 * As Samba is catching and eating child process
1290 * exits we don't really care about the child exit
1291 * code, a -1 with errno = ECHILD will do fine for us.
1294 do {
1295 wait_pid = sys_waitpid (entry->child_pid, &wstatus, 0);
1296 } while (wait_pid == -1 && errno == EINTR);
1298 SAFE_FREE(entry);
1300 if (wait_pid == -1)
1301 return -1;
1302 return wstatus;
1305 /**************************************************************************
1306 Wrapper for Admin Logs.
1307 ****************************************************************************/
1309 void sys_adminlog(int priority, const char *format_str, ...)
1311 va_list ap;
1312 int ret;
1313 char *msgbuf = NULL;
1315 va_start( ap, format_str );
1316 ret = vasprintf( &msgbuf, format_str, ap );
1317 va_end( ap );
1319 if (ret == -1)
1320 return;
1322 #if defined(HAVE_SYSLOG)
1323 syslog( priority, "%s", msgbuf );
1324 #else
1325 DEBUG(0,("%s", msgbuf ));
1326 #endif
1327 SAFE_FREE(msgbuf);
1330 /****************************************************************************
1331 Return the major devicenumber for UNIX extensions.
1332 ****************************************************************************/
1334 uint32 unix_dev_major(SMB_DEV_T dev)
1336 #if defined(HAVE_DEVICE_MAJOR_FN)
1337 return (uint32)major(dev);
1338 #else
1339 return (uint32)(dev >> 8);
1340 #endif
1343 /****************************************************************************
1344 Return the minor devicenumber for UNIX extensions.
1345 ****************************************************************************/
1347 uint32 unix_dev_minor(SMB_DEV_T dev)
1349 #if defined(HAVE_DEVICE_MINOR_FN)
1350 return (uint32)minor(dev);
1351 #else
1352 return (uint32)(dev & 0xff);
1353 #endif
1356 #if 0
1357 /*******************************************************************
1358 Return the number of CPUs.
1359 ********************************************************************/
1361 int sys_get_number_of_cores(void)
1363 int ret = -1;
1365 #if defined(HAVE_SYSCONF)
1366 #if defined(_SC_NPROCESSORS_ONLN)
1367 ret = (int)sysconf(_SC_NPROCESSORS_ONLN);
1368 #endif
1369 #if defined(_SC_NPROCESSORS_CONF)
1370 if (ret < 1) {
1371 ret = (int)sysconf(_SC_NPROCESSORS_CONF);
1373 #endif
1374 #elif defined(HAVE_SYSCTL) && defined(CTL_HW)
1375 int name[2];
1376 unsigned int len = sizeof(ret);
1378 name[0] = CTL_HW;
1379 #if defined(HW_AVAILCPU)
1380 name[1] = HW_AVAILCPU;
1382 if (sysctl(name, 2, &ret, &len, NULL, 0) == -1) {
1383 ret = -1;
1385 #endif
1386 #if defined(HW_NCPU)
1387 if(ret < 1) {
1388 name[0] = CTL_HW;
1389 name[1] = HW_NCPU;
1390 if (sysctl(nm, 2, &count, &len, NULL, 0) == -1) {
1391 ret = -1;
1394 #endif
1395 #endif
1396 if (ret < 1) {
1397 ret = 1;
1399 return ret;
1401 #endif