s3/vfs: change fallocate mode flags from enum->uint32_t
[samba.git] / source3 / lib / system.c
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
8
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.
13
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.
18
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/>.
21 */
22
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"
29
30 #ifdef HAVE_SYS_SYSCTL_H
31 #include <sys/sysctl.h>
32 #endif
33
34 #ifdef HAVE_SYS_PRCTL_H
35 #include <sys/prctl.h>
36 #endif
37
38 /*
39    The idea is that this file will eventually have wrappers around all
40    important system calls in samba. The aims are:
41
42    - to enable easier porting by putting OS dependent stuff in here
43
44    - to allow for hooks into other "pseudo-filesystems"
45
46    - to allow easier integration of things like the japanese extensions
47
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.
51 */
52
53 /*******************************************************************
54 A send wrapper that will deal with EINTR or EAGAIN or EWOULDBLOCK.
55 ********************************************************************/
56
57 ssize_t sys_send(int s, const void *msg, size_t len, int flags)
58 {
59         ssize_t ret;
60
61         do {
62                 ret = send(s, msg, len, flags);
63         } while (ret == -1 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK));
64
65         return ret;
66 }
67
68 /*******************************************************************
69 A recvfrom wrapper that will deal with EINTR.
70 NB. As used with non-blocking sockets, return on EAGAIN/EWOULDBLOCK
71 ********************************************************************/
72
73 ssize_t sys_recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen)
74 {
75         ssize_t ret;
76
77         do {
78                 ret = recvfrom(s, buf, len, flags, from, fromlen);
79         } while (ret == -1 && (errno == EINTR));
80         return ret;
81 }
82
83 /*******************************************************************
84 A fcntl wrapper that will deal with EINTR.
85 ********************************************************************/
86
87 int sys_fcntl_ptr(int fd, int cmd, void *arg)
88 {
89         int ret;
90
91         do {
92                 ret = fcntl(fd, cmd, arg);
93         } while (ret == -1 && errno == EINTR);
94         return ret;
95 }
96
97 /*******************************************************************
98 A fcntl wrapper that will deal with EINTR.
99 ********************************************************************/
100
101 int sys_fcntl_long(int fd, int cmd, long arg)
102 {
103         int ret;
104
105         do {
106                 ret = fcntl(fd, cmd, arg);
107         } while (ret == -1 && errno == EINTR);
108         return ret;
109 }
110
111 /****************************************************************************
112  Get/Set all the possible time fields from a stat struct as a timespec.
113 ****************************************************************************/
114
115 static struct timespec get_atimespec(const struct stat *pst)
116 {
117 #if !defined(HAVE_STAT_HIRES_TIMESTAMPS)
118         struct timespec ret;
119
120         /* Old system - no ns timestamp. */
121         ret.tv_sec = pst->st_atime;
122         ret.tv_nsec = 0;
123         return ret;
124 #else
125 #if defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
126         struct timespec ret;
127         ret.tv_sec = pst->st_atim.tv_sec;
128         ret.tv_nsec = pst->st_atim.tv_nsec;
129         return ret;
130 #elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
131         struct timespec ret;
132         ret.tv_sec = pst->st_atime;
133         ret.tv_nsec = pst->st_atimensec;
134         return ret;
135 #elif defined(HAVE_STRUCT_STAT_ST_MTIME_N)
136         struct timespec ret;
137         ret.tv_sec = pst->st_atime;
138         ret.tv_nsec = pst->st_atime_n;
139         return ret;
140 #elif defined(HAVE_STRUCT_STAT_ST_UMTIME)
141         struct timespec ret;
142         ret.tv_sec = pst->st_atime;
143         ret.tv_nsec = pst->st_uatime * 1000;
144         return ret;
145 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
146         return pst->st_atimespec;
147 #else
148 #error  CONFIGURE_ERROR_IN_DETECTING_TIMESPEC_IN_STAT
149 #endif
150 #endif
151 }
152
153 static struct timespec get_mtimespec(const struct stat *pst)
154 {
155 #if !defined(HAVE_STAT_HIRES_TIMESTAMPS)
156         struct timespec ret;
157
158         /* Old system - no ns timestamp. */
159         ret.tv_sec = pst->st_mtime;
160         ret.tv_nsec = 0;
161         return ret;
162 #else
163 #if defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
164         struct timespec ret;
165         ret.tv_sec = pst->st_mtim.tv_sec;
166         ret.tv_nsec = pst->st_mtim.tv_nsec;
167         return ret;
168 #elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
169         struct timespec ret;
170         ret.tv_sec = pst->st_mtime;
171         ret.tv_nsec = pst->st_mtimensec;
172         return ret;
173 #elif defined(HAVE_STRUCT_STAT_ST_MTIME_N)
174         struct timespec ret;
175         ret.tv_sec = pst->st_mtime;
176         ret.tv_nsec = pst->st_mtime_n;
177         return ret;
178 #elif defined(HAVE_STRUCT_STAT_ST_UMTIME)
179         struct timespec ret;
180         ret.tv_sec = pst->st_mtime;
181         ret.tv_nsec = pst->st_umtime * 1000;
182         return ret;
183 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
184         return pst->st_mtimespec;
185 #else
186 #error  CONFIGURE_ERROR_IN_DETECTING_TIMESPEC_IN_STAT
187 #endif
188 #endif
189 }
190
191 static struct timespec get_ctimespec(const struct stat *pst)
192 {
193 #if !defined(HAVE_STAT_HIRES_TIMESTAMPS)
194         struct timespec ret;
195
196         /* Old system - no ns timestamp. */
197         ret.tv_sec = pst->st_ctime;
198         ret.tv_nsec = 0;
199         return ret;
200 #else
201 #if defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
202         struct timespec ret;
203         ret.tv_sec = pst->st_ctim.tv_sec;
204         ret.tv_nsec = pst->st_ctim.tv_nsec;
205         return ret;
206 #elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
207         struct timespec ret;
208         ret.tv_sec = pst->st_ctime;
209         ret.tv_nsec = pst->st_ctimensec;
210         return ret;
211 #elif defined(HAVE_STRUCT_STAT_ST_MTIME_N)
212         struct timespec ret;
213         ret.tv_sec = pst->st_ctime;
214         ret.tv_nsec = pst->st_ctime_n;
215         return ret;
216 #elif defined(HAVE_STRUCT_STAT_ST_UMTIME)
217         struct timespec ret;
218         ret.tv_sec = pst->st_ctime;
219         ret.tv_nsec = pst->st_uctime * 1000;
220         return ret;
221 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
222         return pst->st_ctimespec;
223 #else
224 #error  CONFIGURE_ERROR_IN_DETECTING_TIMESPEC_IN_STAT
225 #endif
226 #endif
227 }
228
229 /****************************************************************************
230  Return the best approximation to a 'create time' under UNIX from a stat
231  structure.
232 ****************************************************************************/
233
234 static struct timespec calc_create_time_stat(const struct stat *st)
235 {
236         struct timespec ret, ret1;
237         struct timespec c_time = get_ctimespec(st);
238         struct timespec m_time = get_mtimespec(st);
239         struct timespec a_time = get_atimespec(st);
240
241         ret = timespec_compare(&c_time, &m_time) < 0 ? c_time : m_time;
242         ret1 = timespec_compare(&ret, &a_time) < 0 ? ret : a_time;
243
244         if(!null_timespec(ret1)) {
245                 return ret1;
246         }
247
248         /*
249          * One of ctime, mtime or atime was zero (probably atime).
250          * Just return MIN(ctime, mtime).
251          */
252         return ret;
253 }
254
255 /****************************************************************************
256  Return the best approximation to a 'create time' under UNIX from a stat_ex
257  structure.
258 ****************************************************************************/
259
260 static struct timespec calc_create_time_stat_ex(const struct stat_ex *st)
261 {
262         struct timespec ret, ret1;
263         struct timespec c_time = st->st_ex_ctime;
264         struct timespec m_time = st->st_ex_mtime;
265         struct timespec a_time = st->st_ex_atime;
266
267         ret = timespec_compare(&c_time, &m_time) < 0 ? c_time : m_time;
268         ret1 = timespec_compare(&ret, &a_time) < 0 ? ret : a_time;
269
270         if(!null_timespec(ret1)) {
271                 return ret1;
272         }
273
274         /*
275          * One of ctime, mtime or atime was zero (probably atime).
276          * Just return MIN(ctime, mtime).
277          */
278         return ret;
279 }
280
281 /****************************************************************************
282  Return the 'create time' from a stat struct if it exists (birthtime) or else
283  use the best approximation.
284 ****************************************************************************/
285
286 static void make_create_timespec(const struct stat *pst, struct stat_ex *dst,
287                                  bool fake_dir_create_times)
288 {
289         if (S_ISDIR(pst->st_mode) && fake_dir_create_times) {
290                 dst->st_ex_btime.tv_sec = 315493200L;          /* 1/1/1980 */
291                 dst->st_ex_btime.tv_nsec = 0;
292         }
293
294         dst->st_ex_calculated_birthtime = false;
295
296 #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC)
297         dst->st_ex_btime = pst->st_birthtimespec;
298 #elif defined(HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC)
299         dst->st_ex_btime.tv_sec = pst->st_birthtime;
300         dst->st_ex_btime.tv_nsec = pst->st_birthtimenspec;
301 #elif defined(HAVE_STRUCT_STAT_ST_BIRTHTIME)
302         dst->st_ex_btime.tv_sec = pst->st_birthtime;
303         dst->st_ex_btime.tv_nsec = 0;
304 #else
305         dst->st_ex_btime = calc_create_time_stat(pst);
306         dst->st_ex_calculated_birthtime = true;
307 #endif
308
309         /* Deal with systems that don't initialize birthtime correctly.
310          * Pointed out by SATOH Fumiyasu <fumiyas@osstech.jp>.
311          */
312         if (null_timespec(dst->st_ex_btime)) {
313                 dst->st_ex_btime = calc_create_time_stat(pst);
314                 dst->st_ex_calculated_birthtime = true;
315         }
316 }
317
318 /****************************************************************************
319  If we update a timestamp in a stat_ex struct we may have to recalculate
320  the birthtime. For now only implement this for write time, but we may
321  also need to do it for atime and ctime. JRA.
322 ****************************************************************************/
323
324 void update_stat_ex_mtime(struct stat_ex *dst,
325                                 struct timespec write_ts)
326 {
327         dst->st_ex_mtime = write_ts;
328
329         /* We may have to recalculate btime. */
330         if (dst->st_ex_calculated_birthtime) {
331                 dst->st_ex_btime = calc_create_time_stat_ex(dst);
332         }
333 }
334
335 void update_stat_ex_create_time(struct stat_ex *dst,
336                                 struct timespec create_time)
337 {
338         dst->st_ex_btime = create_time;
339         dst->st_ex_calculated_birthtime = false;
340 }
341
342 void init_stat_ex_from_stat (struct stat_ex *dst,
343                             const struct stat *src,
344                             bool fake_dir_create_times)
345 {
346         dst->st_ex_dev = src->st_dev;
347         dst->st_ex_ino = src->st_ino;
348         dst->st_ex_mode = src->st_mode;
349         dst->st_ex_nlink = src->st_nlink;
350         dst->st_ex_uid = src->st_uid;
351         dst->st_ex_gid = src->st_gid;
352         dst->st_ex_rdev = src->st_rdev;
353         dst->st_ex_size = src->st_size;
354         dst->st_ex_atime = get_atimespec(src);
355         dst->st_ex_mtime = get_mtimespec(src);
356         dst->st_ex_ctime = get_ctimespec(src);
357         make_create_timespec(src, dst, fake_dir_create_times);
358 #ifdef HAVE_STAT_ST_BLKSIZE
359         dst->st_ex_blksize = src->st_blksize;
360 #else
361         dst->st_ex_blksize = STAT_ST_BLOCKSIZE;
362 #endif
363
364 #ifdef HAVE_STAT_ST_BLOCKS
365         dst->st_ex_blocks = src->st_blocks;
366 #else
367         dst->st_ex_blocks = src->st_size / dst->st_ex_blksize + 1;
368 #endif
369
370 #ifdef HAVE_STAT_ST_FLAGS
371         dst->st_ex_flags = src->st_flags;
372 #else
373         dst->st_ex_flags = 0;
374 #endif
375 }
376
377 /*******************************************************************
378 A stat() wrapper.
379 ********************************************************************/
380
381 int sys_stat(const char *fname, SMB_STRUCT_STAT *sbuf,
382              bool fake_dir_create_times)
383 {
384         int ret;
385         struct stat statbuf;
386         ret = stat(fname, &statbuf);
387         if (ret == 0) {
388                 /* we always want directories to appear zero size */
389                 if (S_ISDIR(statbuf.st_mode)) {
390                         statbuf.st_size = 0;
391                 }
392                 init_stat_ex_from_stat(sbuf, &statbuf, fake_dir_create_times);
393         }
394         return ret;
395 }
396
397 /*******************************************************************
398  An fstat() wrapper.
399 ********************************************************************/
400
401 int sys_fstat(int fd, SMB_STRUCT_STAT *sbuf, bool fake_dir_create_times)
402 {
403         int ret;
404         struct stat statbuf;
405         ret = fstat(fd, &statbuf);
406         if (ret == 0) {
407                 /* we always want directories to appear zero size */
408                 if (S_ISDIR(statbuf.st_mode)) {
409                         statbuf.st_size = 0;
410                 }
411                 init_stat_ex_from_stat(sbuf, &statbuf, fake_dir_create_times);
412         }
413         return ret;
414 }
415
416 /*******************************************************************
417  An lstat() wrapper.
418 ********************************************************************/
419
420 int sys_lstat(const char *fname,SMB_STRUCT_STAT *sbuf,
421               bool fake_dir_create_times)
422 {
423         int ret;
424         struct stat statbuf;
425         ret = lstat(fname, &statbuf);
426         if (ret == 0) {
427                 /* we always want directories to appear zero size */
428                 if (S_ISDIR(statbuf.st_mode)) {
429                         statbuf.st_size = 0;
430                 }
431                 init_stat_ex_from_stat(sbuf, &statbuf, fake_dir_create_times);
432         }
433         return ret;
434 }
435
436 /*******************************************************************
437  An posix_fallocate() wrapper.
438 ********************************************************************/
439 int sys_posix_fallocate(int fd, off_t offset, off_t len)
440 {
441 #if defined(HAVE_POSIX_FALLOCATE) && !defined(HAVE_BROKEN_POSIX_FALLOCATE)
442         return posix_fallocate(fd, offset, len);
443 #elif defined(F_RESVSP64)
444         /* this handles XFS on IRIX */
445         struct flock64 fl;
446         off_t new_len = offset + len;
447         int ret;
448         struct stat64 sbuf;
449
450         /* unlikely to get a too large file on a 64bit system but ... */
451         if (new_len < 0)
452                 return EFBIG;
453
454         fl.l_whence = SEEK_SET;
455         fl.l_start = offset;
456         fl.l_len = len;
457
458         ret=fcntl(fd, F_RESVSP64, &fl);
459
460         if (ret != 0)
461                 return errno;
462
463         /* Make sure the file gets enlarged after we allocated space: */
464         fstat64(fd, &sbuf);
465         if (new_len > sbuf.st_size)
466                 ftruncate64(fd, new_len);
467         return 0;
468 #else
469         return ENOSYS;
470 #endif
471 }
472
473 /*******************************************************************
474  An fallocate() function that matches the semantics of the Linux one.
475 ********************************************************************/
476
477 #ifdef HAVE_LINUX_FALLOC_H
478 #include <linux/falloc.h>
479 #endif
480
481 int sys_fallocate(int fd, uint32_t mode, off_t offset, off_t len)
482 {
483 #if defined(HAVE_LINUX_FALLOCATE)
484         int lmode = 0;
485
486         if (mode & VFS_FALLOCATE_FL_KEEP_SIZE) {
487                 lmode |= FALLOC_FL_KEEP_SIZE;
488                 mode &= ~VFS_FALLOCATE_FL_KEEP_SIZE;
489         }
490
491         if (mode != 0) {
492                 DEBUG(2, ("unmapped fallocate flags: %lx\n",
493                       (unsigned long)mode));
494                 errno = EINVAL;
495                 return -1;
496         }
497         return fallocate(fd, lmode, offset, len);
498 #else
499         /* TODO - plumb in fallocate from other filesysetms like VXFS etc. JRA. */
500         errno = ENOSYS;
501         return -1;
502 #endif
503 }
504
505 #if HAVE_KERNEL_SHARE_MODES
506 #ifndef LOCK_MAND
507 #define LOCK_MAND       32      /* This is a mandatory flock */
508 #define LOCK_READ       64      /* ... Which allows concurrent read operations */
509 #define LOCK_WRITE      128     /* ... Which allows concurrent write operations */
510 #define LOCK_RW         192     /* ... Which allows concurrent read & write ops */
511 #endif
512 #endif
513
514 /*******************************************************************
515  A flock() wrapper that will perform the kernel flock.
516 ********************************************************************/
517
518 void kernel_flock(int fd, uint32 share_mode, uint32 access_mask)
519 {
520 #if HAVE_KERNEL_SHARE_MODES
521         int kernel_mode = 0;
522         if (share_mode == FILE_SHARE_WRITE) {
523                 kernel_mode = LOCK_MAND|LOCK_WRITE;
524         } else if (share_mode == FILE_SHARE_READ) {
525                 kernel_mode = LOCK_MAND|LOCK_READ;
526         } else if (share_mode == FILE_SHARE_NONE) {
527                 kernel_mode = LOCK_MAND;
528         }
529         if (kernel_mode) {
530                 flock(fd, kernel_mode);
531         }
532 #endif
533         ;
534 }
535
536
537
538 /*******************************************************************
539  An fdopendir wrapper.
540 ********************************************************************/
541
542 DIR *sys_fdopendir(int fd)
543 {
544 #if defined(HAVE_FDOPENDIR)
545         return fdopendir(fd);
546 #else
547         errno = ENOSYS;
548         return NULL;
549 #endif
550 }
551
552 /*******************************************************************
553  An mknod() wrapper.
554 ********************************************************************/
555
556 int sys_mknod(const char *path, mode_t mode, SMB_DEV_T dev)
557 {
558 #if defined(HAVE_MKNOD)
559         return mknod(path, mode, dev);
560 #else
561         /* No mknod system call. */
562         errno = ENOSYS;
563         return -1;
564 #endif
565 }
566
567 /*******************************************************************
568 The wait() calls vary between systems
569 ********************************************************************/
570
571 int sys_waitpid(pid_t pid,int *status,int options)
572 {
573 #ifdef HAVE_WAITPID
574         return waitpid(pid,status,options);
575 #else /* HAVE_WAITPID */
576         return wait4(pid, status, options, NULL);
577 #endif /* HAVE_WAITPID */
578 }
579
580 /*******************************************************************
581  System wrapper for getwd. Always returns MALLOC'ed memory, or NULL
582  on error (malloc fail usually).
583 ********************************************************************/
584
585 char *sys_getwd(void)
586 {
587 #ifdef GETCWD_TAKES_NULL
588         return getcwd(NULL, 0);
589 #elif HAVE_GETCWD
590         char *wd = NULL, *s = NULL;
591         size_t allocated = PATH_MAX;
592
593         while (1) {
594                 s = SMB_REALLOC_ARRAY(s, char, allocated);
595                 if (s == NULL) {
596                         return NULL;
597                 }
598                 wd = getcwd(s, allocated);
599                 if (wd) {
600                         break;
601                 }
602                 if (errno != ERANGE) {
603                         SAFE_FREE(s);
604                         break;
605                 }
606                 allocated *= 2;
607                 if (allocated < PATH_MAX) {
608                         SAFE_FREE(s);
609                         break;
610                 }
611         }
612         return wd;
613 #else
614         char *s = SMB_MALLOC_ARRAY(char, PATH_MAX);
615         if (s == NULL) {
616                 return NULL;
617         }
618         return getwd(s);
619 #endif
620 }
621
622 #if defined(HAVE_POSIX_CAPABILITIES)
623
624 /**************************************************************************
625  Try and abstract process capabilities (for systems that have them).
626 ****************************************************************************/
627
628 /* Set the POSIX capabilities needed for the given purpose into the effective
629  * capability set of the current process. Make sure they are always removed
630  * from the inheritable set, because there is no circumstance in which our
631  * children should inherit our elevated privileges.
632  */
633 static bool set_process_capability(enum smbd_capability capability,
634                                    bool enable)
635 {
636         cap_value_t cap_vals[2] = {0};
637         int num_cap_vals = 0;
638
639         cap_t cap;
640
641 #if defined(HAVE_PRCTL) && defined(PR_GET_KEEPCAPS) && defined(PR_SET_KEEPCAPS)
642         /* On Linux, make sure that any capabilities we grab are sticky
643          * across UID changes. We expect that this would allow us to keep both
644          * the effective and permitted capability sets, but as of circa 2.6.16,
645          * only the permitted set is kept. It is a bug (which we work around)
646          * that the effective set is lost, but we still require the effective
647          * set to be kept.
648          */
649         if (!prctl(PR_GET_KEEPCAPS)) {
650                 prctl(PR_SET_KEEPCAPS, 1);
651         }
652 #endif
653
654         cap = cap_get_proc();
655         if (cap == NULL) {
656                 DEBUG(0,("set_process_capability: cap_get_proc failed: %s\n",
657                         strerror(errno)));
658                 return False;
659         }
660
661         switch (capability) {
662                 case KERNEL_OPLOCK_CAPABILITY:
663 #ifdef CAP_NETWORK_MGT
664                         /* IRIX has CAP_NETWORK_MGT for oplocks. */
665                         cap_vals[num_cap_vals++] = CAP_NETWORK_MGT;
666 #endif
667                         break;
668                 case DMAPI_ACCESS_CAPABILITY:
669 #ifdef CAP_DEVICE_MGT
670                         /* IRIX has CAP_DEVICE_MGT for DMAPI access. */
671                         cap_vals[num_cap_vals++] = CAP_DEVICE_MGT;
672 #elif CAP_MKNOD
673                         /* Linux has CAP_MKNOD for DMAPI access. */
674                         cap_vals[num_cap_vals++] = CAP_MKNOD;
675 #endif
676                         break;
677                 case LEASE_CAPABILITY:
678 #ifdef CAP_LEASE
679                         cap_vals[num_cap_vals++] = CAP_LEASE;
680 #endif
681                         break;
682                 case DAC_OVERRIDE_CAPABILITY:
683 #ifdef CAP_DAC_OVERRIDE
684                         cap_vals[num_cap_vals++] = CAP_DAC_OVERRIDE;
685 #endif
686         }
687
688         SMB_ASSERT(num_cap_vals <= ARRAY_SIZE(cap_vals));
689
690         if (num_cap_vals == 0) {
691                 cap_free(cap);
692                 return True;
693         }
694
695         cap_set_flag(cap, CAP_EFFECTIVE, num_cap_vals, cap_vals,
696                 enable ? CAP_SET : CAP_CLEAR);
697
698         /* We never want to pass capabilities down to our children, so make
699          * sure they are not inherited.
700          */
701         cap_set_flag(cap, CAP_INHERITABLE, num_cap_vals, cap_vals, CAP_CLEAR);
702
703         if (cap_set_proc(cap) == -1) {
704                 DEBUG(0, ("set_process_capability: cap_set_proc failed: %s\n",
705                         strerror(errno)));
706                 cap_free(cap);
707                 return False;
708         }
709
710         cap_free(cap);
711         return True;
712 }
713
714 #endif /* HAVE_POSIX_CAPABILITIES */
715
716 /****************************************************************************
717  Gain the oplock capability from the kernel if possible.
718 ****************************************************************************/
719
720 void set_effective_capability(enum smbd_capability capability)
721 {
722 #if defined(HAVE_POSIX_CAPABILITIES)
723         set_process_capability(capability, True);
724 #endif /* HAVE_POSIX_CAPABILITIES */
725 }
726
727 void drop_effective_capability(enum smbd_capability capability)
728 {
729 #if defined(HAVE_POSIX_CAPABILITIES)
730         set_process_capability(capability, False);
731 #endif /* HAVE_POSIX_CAPABILITIES */
732 }
733
734 /**************************************************************************
735  Wrapper for random().
736 ****************************************************************************/
737
738 long sys_random(void)
739 {
740 #if defined(HAVE_RANDOM)
741         return (long)random();
742 #elif defined(HAVE_RAND)
743         return (long)rand();
744 #else
745         DEBUG(0,("Error - no random function available !\n"));
746         exit(1);
747 #endif
748 }
749
750 /**************************************************************************
751  Wrapper for srandom().
752 ****************************************************************************/
753
754 void sys_srandom(unsigned int seed)
755 {
756 #if defined(HAVE_SRANDOM)
757         srandom(seed);
758 #elif defined(HAVE_SRAND)
759         srand(seed);
760 #else
761         DEBUG(0,("Error - no srandom function available !\n"));
762         exit(1);
763 #endif
764 }
765
766 #ifndef NGROUPS_MAX
767 #define NGROUPS_MAX 32 /* Guess... */
768 #endif
769
770 /**************************************************************************
771  Returns equivalent to NGROUPS_MAX - using sysconf if needed.
772 ****************************************************************************/
773
774 int groups_max(void)
775 {
776 #if defined(SYSCONF_SC_NGROUPS_MAX)
777         int ret = sysconf(_SC_NGROUPS_MAX);
778         return (ret == -1) ? NGROUPS_MAX : ret;
779 #else
780         return NGROUPS_MAX;
781 #endif
782 }
783
784 /**************************************************************************
785  Wrap setgroups and getgroups for systems that declare getgroups() as
786  returning an array of gid_t, but actuall return an array of int.
787 ****************************************************************************/
788
789 #if defined(HAVE_BROKEN_GETGROUPS)
790
791 #ifdef HAVE_BROKEN_GETGROUPS
792 #define GID_T int
793 #else
794 #define GID_T gid_t
795 #endif
796
797 static int sys_broken_getgroups(int setlen, gid_t *gidset)
798 {
799         GID_T gid;
800         GID_T *group_list;
801         int i, ngroups;
802
803         if(setlen == 0) {
804                 return getgroups(setlen, &gid);
805         }
806
807         /*
808          * Broken case. We need to allocate a
809          * GID_T array of size setlen.
810          */
811
812         if(setlen < 0) {
813                 errno = EINVAL; 
814                 return -1;
815         } 
816
817         if (setlen == 0)
818                 setlen = groups_max();
819
820         if((group_list = SMB_MALLOC_ARRAY(GID_T, setlen)) == NULL) {
821                 DEBUG(0,("sys_getgroups: Malloc fail.\n"));
822                 return -1;
823         }
824
825         if((ngroups = getgroups(setlen, group_list)) < 0) {
826                 int saved_errno = errno;
827                 SAFE_FREE(group_list);
828                 errno = saved_errno;
829                 return -1;
830         }
831
832         for(i = 0; i < ngroups; i++)
833                 gidset[i] = (gid_t)group_list[i];
834
835         SAFE_FREE(group_list);
836         return ngroups;
837 }
838
839 static int sys_broken_setgroups(int setlen, gid_t *gidset)
840 {
841         GID_T *group_list;
842         int i ; 
843
844         if (setlen == 0)
845                 return 0 ;
846
847         if (setlen < 0 || setlen > groups_max()) {
848                 errno = EINVAL; 
849                 return -1;   
850         }
851
852         /*
853          * Broken case. We need to allocate a
854          * GID_T array of size setlen.
855          */
856
857         if((group_list = SMB_MALLOC_ARRAY(GID_T, setlen)) == NULL) {
858                 DEBUG(0,("sys_setgroups: Malloc fail.\n"));
859                 return -1;    
860         }
861
862         for(i = 0; i < setlen; i++) 
863                 group_list[i] = (GID_T) gidset[i]; 
864
865         if(samba_setgroups(setlen, group_list) != 0) {
866                 int saved_errno = errno;
867                 SAFE_FREE(group_list);
868                 errno = saved_errno;
869                 return -1;
870         }
871
872         SAFE_FREE(group_list);
873         return 0 ;
874 }
875
876 #endif /* HAVE_BROKEN_GETGROUPS */
877
878 /* This is a list of systems that require the first GID passed to setgroups(2)
879  * to be the effective GID. If your system is one of these, add it here.
880  */
881 #if defined (FREEBSD) || defined (DARWINOS)
882 #define USE_BSD_SETGROUPS
883 #endif
884
885 #if defined(USE_BSD_SETGROUPS)
886 /* Depending on the particular BSD implementation, the first GID that is
887  * passed to setgroups(2) will either be ignored or will set the credential's
888  * effective GID. In either case, the right thing to do is to guarantee that
889  * gidset[0] is the effective GID.
890  */
891 static int sys_bsd_setgroups(gid_t primary_gid, int setlen, const gid_t *gidset)
892 {
893         gid_t *new_gidset = NULL;
894         int max;
895         int ret;
896
897         /* setgroups(2) will fail with EINVAL if we pass too many groups. */
898         max = groups_max();
899
900         /* No group list, just make sure we are setting the efective GID. */
901         if (setlen == 0) {
902                 return samba_setgroups(1, &primary_gid);
903         }
904
905         /* If the primary gid is not the first array element, grow the array
906          * and insert it at the front.
907          */
908         if (gidset[0] != primary_gid) {
909                 new_gidset = SMB_MALLOC_ARRAY(gid_t, setlen + 1);
910                 if (new_gidset == NULL) {
911                         return -1;
912                 }
913
914                 memcpy(new_gidset + 1, gidset, (setlen * sizeof(gid_t)));
915                 new_gidset[0] = primary_gid;
916                 setlen++;
917         }
918
919         if (setlen > max) {
920                 DEBUG(3, ("forced to truncate group list from %d to %d\n",
921                         setlen, max));
922                 setlen = max;
923         }
924
925 #if defined(HAVE_BROKEN_GETGROUPS)
926         ret = sys_broken_setgroups(setlen, new_gidset ? new_gidset : gidset);
927 #else
928         ret = samba_setgroups(setlen, new_gidset ? new_gidset : gidset);
929 #endif
930
931         if (new_gidset) {
932                 int errsav = errno;
933                 SAFE_FREE(new_gidset);
934                 errno = errsav;
935         }
936
937         return ret;
938 }
939
940 #endif /* USE_BSD_SETGROUPS */
941
942 /**************************************************************************
943  Wrapper for getgroups. Deals with broken (int) case.
944 ****************************************************************************/
945
946 int sys_getgroups(int setlen, gid_t *gidset)
947 {
948 #if defined(HAVE_BROKEN_GETGROUPS)
949         return sys_broken_getgroups(setlen, gidset);
950 #else
951         return getgroups(setlen, gidset);
952 #endif
953 }
954
955 /**************************************************************************
956  Wrapper for setgroups. Deals with broken (int) case and BSD case.
957 ****************************************************************************/
958
959 int sys_setgroups(gid_t UNUSED(primary_gid), int setlen, gid_t *gidset)
960 {
961 #if !defined(HAVE_SETGROUPS)
962         errno = ENOSYS;
963         return -1;
964 #endif /* HAVE_SETGROUPS */
965
966 #if defined(USE_BSD_SETGROUPS)
967         return sys_bsd_setgroups(primary_gid, setlen, gidset);
968 #elif defined(HAVE_BROKEN_GETGROUPS)
969         return sys_broken_setgroups(setlen, gidset);
970 #else
971         return samba_setgroups(setlen, gidset);
972 #endif
973 }
974
975 /**************************************************************************
976  Extract a command into an arg list.
977 ****************************************************************************/
978
979 static char **extract_args(TALLOC_CTX *mem_ctx, const char *command)
980 {
981         char *trunc_cmd;
982         char *saveptr;
983         char *ptr;
984         int argcl;
985         char **argl = NULL;
986         int i;
987
988         if (!(trunc_cmd = talloc_strdup(mem_ctx, command))) {
989                 DEBUG(0, ("talloc failed\n"));
990                 goto nomem;
991         }
992
993         if(!(ptr = strtok_r(trunc_cmd, " \t", &saveptr))) {
994                 TALLOC_FREE(trunc_cmd);
995                 errno = EINVAL;
996                 return NULL;
997         }
998
999         /*
1000          * Count the args.
1001          */
1002
1003         for( argcl = 1; ptr; ptr = strtok_r(NULL, " \t", &saveptr))
1004                 argcl++;
1005
1006         TALLOC_FREE(trunc_cmd);
1007
1008         if (!(argl = talloc_array(mem_ctx, char *, argcl + 1))) {
1009                 goto nomem;
1010         }
1011
1012         /*
1013          * Now do the extraction.
1014          */
1015
1016         if (!(trunc_cmd = talloc_strdup(mem_ctx, command))) {
1017                 goto nomem;
1018         }
1019
1020         ptr = strtok_r(trunc_cmd, " \t", &saveptr);
1021         i = 0;
1022
1023         if (!(argl[i++] = talloc_strdup(argl, ptr))) {
1024                 goto nomem;
1025         }
1026
1027         while((ptr = strtok_r(NULL, " \t", &saveptr)) != NULL) {
1028
1029                 if (!(argl[i++] = talloc_strdup(argl, ptr))) {
1030                         goto nomem;
1031                 }
1032         }
1033
1034         argl[i++] = NULL;
1035         TALLOC_FREE(trunc_cmd);
1036         return argl;
1037
1038  nomem:
1039         DEBUG(0, ("talloc failed\n"));
1040         TALLOC_FREE(trunc_cmd);
1041         TALLOC_FREE(argl);
1042         errno = ENOMEM;
1043         return NULL;
1044 }
1045
1046 /**************************************************************************
1047  Wrapper for popen. Safer as it doesn't search a path.
1048  Modified from the glibc sources.
1049  modified by tridge to return a file descriptor. We must kick our FILE* habit
1050 ****************************************************************************/
1051
1052 typedef struct _popen_list
1053 {
1054         int fd;
1055         pid_t child_pid;
1056         struct _popen_list *next;
1057 } popen_list;
1058
1059 static popen_list *popen_chain;
1060
1061 int sys_popen(const char *command)
1062 {
1063         int parent_end, child_end;
1064         int pipe_fds[2];
1065         popen_list *entry = NULL;
1066         char **argl = NULL;
1067         int ret;
1068
1069         if (!*command) {
1070                 errno = EINVAL;
1071                 return -1;
1072         }
1073
1074         ret = pipe(pipe_fds);
1075         if (ret < 0) {
1076                 DEBUG(0, ("sys_popen: error opening pipe: %s\n",
1077                           strerror(errno)));
1078                 return -1;
1079         }
1080
1081         parent_end = pipe_fds[0];
1082         child_end = pipe_fds[1];
1083
1084         entry = SMB_MALLOC_P(popen_list);
1085         if (entry == NULL) {
1086                 DEBUG(0, ("sys_popen: malloc failed\n"));
1087                 goto err_exit;
1088         }
1089
1090         ZERO_STRUCTP(entry);
1091
1092         /*
1093          * Extract the command and args into a NULL terminated array.
1094          */
1095
1096         argl = extract_args(NULL, command);
1097         if (argl == NULL) {
1098                 DEBUG(0, ("sys_popen: extract_args() failed: %s\n", strerror(errno)));
1099                 goto err_exit;
1100         }
1101
1102         entry->child_pid = fork();
1103
1104         if (entry->child_pid == -1) {
1105                 DEBUG(0, ("sys_popen: fork failed: %s\n", strerror(errno)));
1106                 goto err_exit;
1107         }
1108
1109         if (entry->child_pid == 0) {
1110
1111                 /*
1112                  * Child !
1113                  */
1114
1115                 int child_std_end = STDOUT_FILENO;
1116                 popen_list *p;
1117
1118                 close(parent_end);
1119                 if (child_end != child_std_end) {
1120                         dup2 (child_end, child_std_end);
1121                         close (child_end);
1122                 }
1123
1124                 /*
1125                  * POSIX.2:  "popen() shall ensure that any streams from previous
1126                  * popen() calls that remain open in the parent process are closed
1127                  * in the new child process."
1128                  */
1129
1130                 for (p = popen_chain; p; p = p->next)
1131                         close(p->fd);
1132
1133                 ret = execv(argl[0], argl);
1134                 if (ret == -1) {
1135                         DEBUG(0, ("sys_popen: ERROR executing command "
1136                                   "'%s': %s\n", command, strerror(errno)));
1137                 }
1138                 _exit (127);
1139         }
1140
1141         /*
1142          * Parent.
1143          */
1144
1145         close (child_end);
1146         TALLOC_FREE(argl);
1147
1148         /* Link into popen_chain. */
1149         entry->next = popen_chain;
1150         popen_chain = entry;
1151         entry->fd = parent_end;
1152
1153         return entry->fd;
1154
1155 err_exit:
1156
1157         SAFE_FREE(entry);
1158         TALLOC_FREE(argl);
1159         close(pipe_fds[0]);
1160         close(pipe_fds[1]);
1161         return -1;
1162 }
1163
1164 /**************************************************************************
1165  Wrapper for pclose. Modified from the glibc sources.
1166 ****************************************************************************/
1167
1168 int sys_pclose(int fd)
1169 {
1170         int wstatus;
1171         popen_list **ptr = &popen_chain;
1172         popen_list *entry = NULL;
1173         pid_t wait_pid;
1174         int status = -1;
1175
1176         /* Unlink from popen_chain. */
1177         for ( ; *ptr != NULL; ptr = &(*ptr)->next) {
1178                 if ((*ptr)->fd == fd) {
1179                         entry = *ptr;
1180                         *ptr = (*ptr)->next;
1181                         status = 0;
1182                         break;
1183                 }
1184         }
1185
1186         if (status < 0 || close(entry->fd) < 0)
1187                 return -1;
1188
1189         /*
1190          * As Samba is catching and eating child process
1191          * exits we don't really care about the child exit
1192          * code, a -1 with errno = ECHILD will do fine for us.
1193          */
1194
1195         do {
1196                 wait_pid = sys_waitpid (entry->child_pid, &wstatus, 0);
1197         } while (wait_pid == -1 && errno == EINTR);
1198
1199         SAFE_FREE(entry);
1200
1201         if (wait_pid == -1)
1202                 return -1;
1203         return wstatus;
1204 }
1205
1206 /****************************************************************************
1207  Return the major devicenumber for UNIX extensions.
1208 ****************************************************************************/
1209
1210 uint32 unix_dev_major(SMB_DEV_T dev)
1211 {
1212 #if defined(HAVE_DEVICE_MAJOR_FN)
1213         return (uint32)major(dev);
1214 #else
1215         return (uint32)(dev >> 8);
1216 #endif
1217 }
1218
1219 /****************************************************************************
1220  Return the minor devicenumber for UNIX extensions.
1221 ****************************************************************************/
1222
1223 uint32 unix_dev_minor(SMB_DEV_T dev)
1224 {
1225 #if defined(HAVE_DEVICE_MINOR_FN)
1226         return (uint32)minor(dev);
1227 #else
1228         return (uint32)(dev & 0xff);
1229 #endif
1230 }
1231
1232 #if 0
1233 /*******************************************************************
1234  Return the number of CPUs.
1235 ********************************************************************/
1236
1237 int sys_get_number_of_cores(void)
1238 {
1239         int ret = -1;
1240
1241 #if defined(HAVE_SYSCONF)
1242 #if defined(_SC_NPROCESSORS_ONLN)
1243         ret = (int)sysconf(_SC_NPROCESSORS_ONLN);
1244 #endif
1245 #if defined(_SC_NPROCESSORS_CONF)
1246         if (ret < 1) {
1247                 ret = (int)sysconf(_SC_NPROCESSORS_CONF);
1248         }
1249 #endif
1250 #elif defined(HAVE_SYSCTL) && defined(CTL_HW)
1251         int name[2];
1252         unsigned int len = sizeof(ret);
1253
1254         name[0] = CTL_HW;
1255 #if defined(HW_AVAILCPU)
1256         name[1] = HW_AVAILCPU;
1257
1258         if (sysctl(name, 2, &ret, &len, NULL, 0) == -1) {
1259                 ret = -1;
1260         }
1261 #endif
1262 #if defined(HW_NCPU)
1263         if(ret < 1) {
1264                 name[0] = CTL_HW;
1265                 name[1] = HW_NCPU;
1266                 if (sysctl(nm, 2, &count, &len, NULL, 0) == -1) {
1267                         ret = -1;
1268                 }
1269         }
1270 #endif
1271 #endif
1272         if (ret < 1) {
1273                 ret = 1;
1274         }
1275         return ret;
1276 }
1277 #endif