1b4a82cb033765f284265e673c44f99b4f6a4931
[abartlet/samba.git/.git] / source4 / lib / replace / replace.c
1 /* 
2    Unix SMB/CIFS implementation.
3    replacement routines for broken systems
4    Copyright (C) Andrew Tridgell 1992-1998
5
6      ** NOTE! The following LGPL license applies to the replace
7      ** library. This does NOT imply that all of Samba is released
8      ** under the LGPL
9    
10    This library is free software; you can redistribute it and/or
11    modify it under the terms of the GNU Lesser General Public
12    License as published by the Free Software Foundation; either
13    version 3 of the License, or (at your option) any later version.
14
15    This library is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    Lesser General Public License for more details.
19
20    You should have received a copy of the GNU Lesser General Public
21    License along with this library; if not, write to the Free Software
22    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23 */
24
25 #include "replace.h"
26
27 #include "system/filesys.h"
28 #include "system/time.h"
29 #include "system/passwd.h"
30 #include "system/syslog.h"
31 #include "system/network.h"
32 #include "system/locale.h"
33 #include "system/wait.h"
34
35 void replace_dummy(void);
36 void replace_dummy(void) {}
37
38 #ifndef HAVE_FTRUNCATE
39  /*******************************************************************
40 ftruncate for operating systems that don't have it
41 ********************************************************************/
42 int rep_ftruncate(int f, off_t l)
43 {
44 #ifdef HAVE_CHSIZE
45       return chsize(f,l);
46 #elif defined(F_FREESP)
47       struct  flock   fl;
48
49       fl.l_whence = 0;
50       fl.l_len = 0;
51       fl.l_start = l;
52       fl.l_type = F_WRLCK;
53       return fcntl(f, F_FREESP, &fl);
54 #else
55 #error "you must have a ftruncate function"
56 #endif
57 }
58 #endif /* HAVE_FTRUNCATE */
59
60
61 #ifndef HAVE_STRLCPY
62 /* like strncpy but does not 0 fill the buffer and always null 
63    terminates. bufsize is the size of the destination buffer */
64 size_t rep_strlcpy(char *d, const char *s, size_t bufsize)
65 {
66         size_t len = strlen(s);
67         size_t ret = len;
68         if (bufsize <= 0) return 0;
69         if (len >= bufsize) len = bufsize-1;
70         memcpy(d, s, len);
71         d[len] = 0;
72         return ret;
73 }
74 #endif
75
76 #ifndef HAVE_STRLCAT
77 /* like strncat but does not 0 fill the buffer and always null 
78    terminates. bufsize is the length of the buffer, which should
79    be one more than the maximum resulting string length */
80 size_t rep_strlcat(char *d, const char *s, size_t bufsize)
81 {
82         size_t len1 = strlen(d);
83         size_t len2 = strlen(s);
84         size_t ret = len1 + len2;
85
86         if (len1+len2 >= bufsize) {
87                 len2 = bufsize - (len1+1);
88         }
89         if (len2 > 0) {
90                 memcpy(d+len1, s, len2);
91                 d[len1+len2] = 0;
92         }
93         return ret;
94 }
95 #endif
96
97 #ifndef HAVE_MKTIME
98 /*******************************************************************
99 a mktime() replacement for those who don't have it - contributed by 
100 C.A. Lademann <cal@zls.com>
101 Corrections by richard.kettlewell@kewill.com
102 ********************************************************************/
103
104 #define  MINUTE  60
105 #define  HOUR    60*MINUTE
106 #define  DAY             24*HOUR
107 #define  YEAR    365*DAY
108 time_t rep_mktime(struct tm *t)
109 {
110   struct tm       *u;
111   time_t  epoch = 0;
112   int n;
113   int             mon [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
114   y, m, i;
115
116   if(t->tm_year < 70)
117     return((time_t)-1);
118
119   n = t->tm_year + 1900 - 1;
120   epoch = (t->tm_year - 70) * YEAR + 
121     ((n / 4 - n / 100 + n / 400) - (1969 / 4 - 1969 / 100 + 1969 / 400)) * DAY;
122
123   y = t->tm_year + 1900;
124   m = 0;
125
126   for(i = 0; i < t->tm_mon; i++) {
127     epoch += mon [m] * DAY;
128     if(m == 1 && y % 4 == 0 && (y % 100 != 0 || y % 400 == 0))
129       epoch += DAY;
130     
131     if(++m > 11) {
132       m = 0;
133       y++;
134     }
135   }
136
137   epoch += (t->tm_mday - 1) * DAY;
138   epoch += t->tm_hour * HOUR + t->tm_min * MINUTE + t->tm_sec;
139   
140   if((u = localtime(&epoch)) != NULL) {
141     t->tm_sec = u->tm_sec;
142     t->tm_min = u->tm_min;
143     t->tm_hour = u->tm_hour;
144     t->tm_mday = u->tm_mday;
145     t->tm_mon = u->tm_mon;
146     t->tm_year = u->tm_year;
147     t->tm_wday = u->tm_wday;
148     t->tm_yday = u->tm_yday;
149     t->tm_isdst = u->tm_isdst;
150   }
151
152   return(epoch);
153 }
154 #endif /* !HAVE_MKTIME */
155
156
157 #ifndef HAVE_INITGROUPS
158 /****************************************************************************
159  some systems don't have an initgroups call 
160 ****************************************************************************/
161 int rep_initgroups(char *name, gid_t id)
162 {
163 #ifndef HAVE_SETGROUPS
164         /* yikes! no SETGROUPS or INITGROUPS? how can this work? */
165         errno = ENOSYS;
166         return -1;
167 #else /* HAVE_SETGROUPS */
168
169 #include <grp.h>
170
171         gid_t *grouplst = NULL;
172         int max_gr = 32;
173         int ret;
174         int    i,j;
175         struct group *g;
176         char   *gr;
177         
178         if((grouplst = malloc(sizeof(gid_t) * max_gr)) == NULL) {
179                 errno = ENOMEM;
180                 return -1;
181         }
182
183         grouplst[0] = id;
184         i = 1;
185         while (i < max_gr && ((g = (struct group *)getgrent()) != (struct group *)NULL)) {
186                 if (g->gr_gid == id)
187                         continue;
188                 j = 0;
189                 gr = g->gr_mem[0];
190                 while (gr && (*gr != (char)NULL)) {
191                         if (strcmp(name,gr) == 0) {
192                                 grouplst[i] = g->gr_gid;
193                                 i++;
194                                 gr = (char *)NULL;
195                                 break;
196                         }
197                         gr = g->gr_mem[++j];
198                 }
199         }
200         endgrent();
201         ret = setgroups(i, grouplst);
202         free(grouplst);
203         return ret;
204 #endif /* HAVE_SETGROUPS */
205 }
206 #endif /* HAVE_INITGROUPS */
207
208
209 #if (defined(SecureWare) && defined(SCO))
210 /* This is needed due to needing the nap() function but we don't want
211    to include the Xenix libraries since that will break other things...
212    BTW: system call # 0x0c28 is the same as calling nap() */
213 long nap(long milliseconds) {
214          return syscall(0x0c28, milliseconds);
215  }
216 #endif
217
218
219 #ifndef HAVE_MEMMOVE
220 /*******************************************************************
221 safely copies memory, ensuring no overlap problems.
222 this is only used if the machine does not have it's own memmove().
223 this is not the fastest algorithm in town, but it will do for our
224 needs.
225 ********************************************************************/
226 void *rep_memmove(void *dest,const void *src,int size)
227 {
228         unsigned long d,s;
229         int i;
230         if (dest==src || !size) return(dest);
231
232         d = (unsigned long)dest;
233         s = (unsigned long)src;
234
235         if ((d >= (s+size)) || (s >= (d+size))) {
236                 /* no overlap */
237                 memcpy(dest,src,size);
238                 return(dest);
239         }
240
241         if (d < s) {
242                 /* we can forward copy */
243                 if (s-d >= sizeof(int) && 
244                     !(s%sizeof(int)) && 
245                     !(d%sizeof(int)) && 
246                     !(size%sizeof(int))) {
247                         /* do it all as words */
248                         int *idest = (int *)dest;
249                         int *isrc = (int *)src;
250                         size /= sizeof(int);
251                         for (i=0;i<size;i++) idest[i] = isrc[i];
252                 } else {
253                         /* simplest */
254                         char *cdest = (char *)dest;
255                         char *csrc = (char *)src;
256                         for (i=0;i<size;i++) cdest[i] = csrc[i];
257                 }
258         } else {
259                 /* must backward copy */
260                 if (d-s >= sizeof(int) && 
261                     !(s%sizeof(int)) && 
262                     !(d%sizeof(int)) && 
263                     !(size%sizeof(int))) {
264                         /* do it all as words */
265                         int *idest = (int *)dest;
266                         int *isrc = (int *)src;
267                         size /= sizeof(int);
268                         for (i=size-1;i>=0;i--) idest[i] = isrc[i];
269                 } else {
270                         /* simplest */
271                         char *cdest = (char *)dest;
272                         char *csrc = (char *)src;
273                         for (i=size-1;i>=0;i--) cdest[i] = csrc[i];
274                 }      
275         }
276         return(dest);
277 }
278 #endif /* HAVE_MEMMOVE */
279
280 #ifndef HAVE_STRDUP
281 /****************************************************************************
282 duplicate a string
283 ****************************************************************************/
284 char *rep_strdup(const char *s)
285 {
286         size_t len;
287         char *ret;
288
289         if (!s) return(NULL);
290
291         len = strlen(s)+1;
292         ret = (char *)malloc(len);
293         if (!ret) return(NULL);
294         memcpy(ret,s,len);
295         return(ret);
296 }
297 #endif /* HAVE_STRDUP */
298
299 #ifndef WITH_PTHREADS
300 /* REWRITE: not thread safe */
301 #ifdef REPLACE_INET_NTOA
302 char *rep_inet_ntoa(struct in_addr ip)
303 {
304         uint8_t *p = (uint8_t *)&ip.s_addr;
305         static char buf[18];
306         slprintf(buf, 17, "%d.%d.%d.%d", 
307                  (int)p[0], (int)p[1], (int)p[2], (int)p[3]);
308         return buf;
309 }
310 #endif /* REPLACE_INET_NTOA */
311 #endif
312
313 #ifndef HAVE_SETLINEBUF
314 void rep_setlinebuf(FILE *stream)
315 {
316         setvbuf(stream, (char *)NULL, _IOLBF, 0);
317 }
318 #endif /* HAVE_SETLINEBUF */
319
320 #ifndef HAVE_VSYSLOG
321 #ifdef HAVE_SYSLOG
322 void rep_vsyslog (int facility_priority, const char *format, va_list arglist)
323 {
324         char *msg = NULL;
325         vasprintf(&msg, format, arglist);
326         if (!msg)
327                 return;
328         syslog(facility_priority, "%s", msg);
329         free(msg);
330 }
331 #endif /* HAVE_SYSLOG */
332 #endif /* HAVE_VSYSLOG */
333
334 #ifndef HAVE_STRNLEN
335 /**
336  Some platforms don't have strnlen
337 **/
338  size_t rep_strnlen(const char *s, size_t max)
339 {
340         size_t len;
341   
342         for (len = 0; len < max; len++) {
343                 if (s[len] == '\0') {
344                         break;
345                 }
346         }
347         return len;  
348 }
349 #endif
350   
351 #ifndef HAVE_STRNDUP
352 /**
353  Some platforms don't have strndup.
354 **/
355 char *rep_strndup(const char *s, size_t n)
356 {
357         char *ret;
358         
359         n = strnlen(s, n);
360         ret = malloc(n+1);
361         if (!ret)
362                 return NULL;
363         memcpy(ret, s, n);
364         ret[n] = 0;
365
366         return ret;
367 }
368 #endif
369
370 #ifndef HAVE_WAITPID
371 int rep_waitpid(pid_t pid,int *status,int options)
372 {
373   return wait4(pid, status, options, NULL);
374 }
375 #endif
376
377 #ifndef HAVE_SETEUID
378 int rep_seteuid(uid_t euid)
379 {
380 #ifdef HAVE_SETRESUID
381         return setresuid(-1, euid, -1);
382 #else
383 #  error "You need a seteuid function"
384 #endif
385 }
386 #endif
387
388 #ifndef HAVE_SETEGID
389 int rep_setegid(gid_t egid)
390 {
391 #ifdef HAVE_SETRESGID
392         return setresgid(-1, egid, -1);
393 #else
394 #  error "You need a setegid function"
395 #endif
396 }
397 #endif
398
399 /*******************************************************************
400 os/2 also doesn't have chroot
401 ********************************************************************/
402 #ifndef HAVE_CHROOT
403 int rep_chroot(const char *dname)
404 {
405         errno = ENOSYS;
406         return -1;
407 }
408 #endif
409
410 /*****************************************************************
411  Possibly replace mkstemp if it is broken.
412 *****************************************************************/  
413
414 #ifndef HAVE_SECURE_MKSTEMP
415 int rep_mkstemp(char *template)
416 {
417         /* have a reasonable go at emulating it. Hope that
418            the system mktemp() isn't completly hopeless */
419         char *p = mktemp(template);
420         if (!p)
421                 return -1;
422         return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
423 }
424 #endif
425
426 #ifndef HAVE_MKDTEMP
427 char *rep_mkdtemp(char *template)
428 {
429         char *dname;
430         
431         if ((dname = mktemp(template))) {
432                 if (mkdir(dname, 0700) >= 0) {
433                         return dname;
434                 }
435         }
436
437         return NULL;
438 }
439 #endif
440
441 /*****************************************************************
442  Watch out: this is not thread safe.
443 *****************************************************************/
444
445 #ifndef HAVE_PREAD
446 ssize_t rep_pread(int __fd, void *__buf, size_t __nbytes, off_t __offset)
447 {
448         if (lseek(__fd, __offset, SEEK_SET) != __offset) {
449                 return -1;
450         }
451         return read(__fd, __buf, __nbytes);
452 }
453 #endif
454
455 /*****************************************************************
456  Watch out: this is not thread safe.
457 *****************************************************************/
458
459 #ifndef HAVE_PWRITE
460 ssize_t rep_pwrite(int __fd, const void *__buf, size_t __nbytes, off_t __offset)
461 {
462         if (lseek(__fd, __offset, SEEK_SET) != __offset) {
463                 return -1;
464         }
465         return write(__fd, __buf, __nbytes);
466 }
467 #endif
468
469 #ifndef HAVE_STRCASESTR
470 char *rep_strcasestr(const char *haystack, const char *needle)
471 {
472         const char *s;
473         size_t nlen = strlen(needle);
474         for (s=haystack;*s;s++) {
475                 if (toupper(*needle) == toupper(*s) &&
476                     strncasecmp(s, needle, nlen) == 0) {
477                         return (char *)((intptr_t)s);
478                 }
479         }
480         return NULL;
481 }
482 #endif
483
484 #ifndef HAVE_STRTOK_R
485 /* based on GLIBC version, copyright Free Software Foundation */
486 char *rep_strtok_r(char *s, const char *delim, char **save_ptr)
487 {
488         char *token;
489
490         if (s == NULL) s = *save_ptr;
491
492         s += strspn(s, delim);
493         if (*s == '\0') {
494                 *save_ptr = s;
495                 return NULL;
496         }
497
498         token = s;
499         s = strpbrk(token, delim);
500         if (s == NULL) {
501                 *save_ptr = token + strlen(token);
502         } else {
503                 *s = '\0';
504                 *save_ptr = s + 1;
505         }
506
507         return token;
508 }
509 #endif
510
511 #ifndef HAVE_STRTOLL
512 long long int rep_strtoll(const char *str, char **endptr, int base)
513 {
514 #ifdef HAVE_STRTOQ
515         return strtoq(str, endptr, base);
516 #elif defined(HAVE___STRTOLL) 
517         return __strtoll(str, endptr, base);
518 #elif SIZEOF_LONG == SIZEOF_LONG_LONG
519         return (long long int) strtol(str, endptr, base);
520 #else
521 # error "You need a strtoll function"
522 #endif
523 }
524 #endif
525
526
527 #ifndef HAVE_STRTOULL
528 unsigned long long int rep_strtoull(const char *str, char **endptr, int base)
529 {
530 #ifdef HAVE_STRTOUQ
531         return strtouq(str, endptr, base);
532 #elif defined(HAVE___STRTOULL) 
533         return __strtoull(str, endptr, base);
534 #elif SIZEOF_LONG == SIZEOF_LONG_LONG
535         return (unsigned long long int) strtoul(str, endptr, base);
536 #else
537 # error "You need a strtoull function"
538 #endif
539 }
540 #endif
541
542 #ifndef HAVE_SETENV
543 int rep_setenv(const char *name, const char *value, int overwrite) 
544 {
545         char *p;
546         size_t l1, l2;
547         int ret;
548
549         if (!overwrite && getenv(name)) {
550                 return 0;
551         }
552
553         l1 = strlen(name);
554         l2 = strlen(value);
555
556         p = malloc(l1+l2+2);
557         if (p == NULL) {
558                 return -1;
559         }
560         memcpy(p, name, l1);
561         p[l1] = '=';
562         memcpy(p+l1+1, value, l2);
563         p[l1+l2+1] = 0;
564
565         ret = putenv(p);
566         if (ret != 0) {
567                 free(p);
568         }
569
570         return ret;
571 }
572 #endif
573
574 #ifndef HAVE_UNSETENV
575 int rep_unsetenv(const char *name)
576 {
577         extern char **environ;
578         size_t len = strlen(name);
579         size_t i, count;
580
581         if (environ == NULL || getenv(name) == NULL) {
582                 return 0;
583         }
584
585         for (i=0;environ[i];i++) /* noop */ ;
586
587         count=i;
588         
589         for (i=0;i<count;) {
590                 if (strncmp(environ[i], name, len) == 0 && environ[i][len] == '=') {
591                         /* note: we do _not_ free the old variable here. It is unsafe to 
592                            do so, as the pointer may not have come from malloc */
593                         memmove(&environ[i], &environ[i+1], (count-i)*sizeof(char *));
594                         count--;
595                 } else {
596                         i++;
597                 }
598         }
599
600         return 0;
601 }
602 #endif
603
604 #ifndef HAVE_SOCKETPAIR
605 int rep_socketpair(int d, int type, int protocol, int sv[2])
606 {
607         if (d != AF_UNIX) {
608                 errno = EAFNOSUPPORT;
609                 return -1;
610         }
611
612         if (protocol != 0) {
613                 errno = EPROTONOSUPPORT;
614                 return -1;
615         }
616
617         if (type != SOCK_STREAM) {
618                 errno = EOPNOTSUPP;
619                 return -1;
620         }
621
622         return pipe(sv);
623 }
624 #endif