initial kerberos/ADS/SPNEGO support in libsmb and smbclient. To
[sfrench/samba-autobuild/.git] / source / lib / util_file.c
1 /*
2  * Unix SMB/Netbios implementation. Version 1.9. SMB parameters and setup
3  * Copyright (C) Andrew Tridgell 1992-1998 Modified by Jeremy Allison 1995.
4  * 
5  * This program is free software; you can redistribute it and/or modify it under
6  * the terms of the GNU General Public License as published by the Free
7  * Software Foundation; either version 2 of the License, or (at your option)
8  * any later version.
9  * 
10  * This program is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  * 
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc., 675
17  * Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include "includes.h"
21
22 static int gotalarm;
23
24 /***************************************************************
25  Signal function to tell us we timed out.
26 ****************************************************************/
27
28 static void gotalarm_sig(void)
29 {
30   gotalarm = 1;
31 }
32
33 /***************************************************************
34  Lock or unlock a fd for a known lock type. Abandon after waitsecs 
35  seconds.
36 ****************************************************************/
37
38 BOOL do_file_lock(int fd, int waitsecs, int type)
39 {
40   SMB_STRUCT_FLOCK lock;
41   int             ret;
42
43   gotalarm = 0;
44   CatchSignal(SIGALRM, SIGNAL_CAST gotalarm_sig);
45
46   lock.l_type = type;
47   lock.l_whence = SEEK_SET;
48   lock.l_start = 0;
49   lock.l_len = 1;
50   lock.l_pid = 0;
51
52   alarm(waitsecs);
53   ret = fcntl(fd, SMB_F_SETLKW, &lock);
54   alarm(0);
55   CatchSignal(SIGALRM, SIGNAL_CAST SIG_DFL);
56
57   if (gotalarm) {
58     DEBUG(0, ("do_file_lock: failed to %s file.\n",
59                 type == F_UNLCK ? "unlock" : "lock"));
60     return False;
61   }
62
63   return (ret == 0);
64 }
65
66
67 /***************************************************************
68  Lock an fd. Abandon after waitsecs seconds.
69 ****************************************************************/
70
71 BOOL file_lock(int fd, int type, int secs, int *plock_depth)
72 {
73   if (fd < 0)
74     return False;
75
76   (*plock_depth)++;
77
78   if ((*plock_depth) == 0)
79   {
80     if (!do_file_lock(fd, secs, type)) {
81       DEBUG(10,("file_lock: locking file failed, error = %s.\n",
82                  strerror(errno)));
83       return False;
84     }
85   }
86
87   return True;
88 }
89
90 /***************************************************************
91  Unlock an fd. Abandon after waitsecs seconds.
92 ****************************************************************/
93
94 BOOL file_unlock(int fd, int *plock_depth)
95 {
96   BOOL ret=True;
97
98   if(*plock_depth == 1)
99     ret = do_file_lock(fd, 5, F_UNLCK);
100
101   (*plock_depth)--;
102
103   if(!ret)
104     DEBUG(10,("file_unlock: unlocking file failed, error = %s.\n",
105                  strerror(errno)));
106   return ret;
107 }
108
109 /***************************************************************
110  locks a file for enumeration / modification.
111  update to be set = True if modification is required.
112 ****************************************************************/
113
114 void *startfilepwent(char *pfile, char *s_readbuf, int bufsize,
115                                 int *file_lock_depth, BOOL update)
116 {
117   FILE *fp = NULL;
118
119   if (!*pfile)
120  {
121     DEBUG(0, ("startfilepwent: No file set\n"));
122     return (NULL);
123   }
124   DEBUG(10, ("startfilepwent: opening file %s\n", pfile));
125
126   fp = sys_fopen(pfile, update ? "r+b" : "rb");
127
128   if (fp == NULL) {
129     DEBUG(0, ("startfilepwent: unable to open file %s\n", pfile));
130     return NULL;
131   }
132
133   /* Set a buffer to do more efficient reads */
134   setvbuf(fp, s_readbuf, _IOFBF, bufsize);
135
136   if (!file_lock(fileno(fp), (update ? F_WRLCK : F_RDLCK), 5, file_lock_depth))
137   {
138     DEBUG(0, ("startfilepwent: unable to lock file %s\n", pfile));
139     fclose(fp);
140     return NULL;
141   }
142
143   /* Make sure it is only rw by the owner */
144   chmod(pfile, 0600);
145
146   /* We have a lock on the file. */
147   return (void *)fp;
148 }
149
150 /***************************************************************
151  End enumeration of the file.
152 ****************************************************************/
153 void endfilepwent(void *vp, int *file_lock_depth)
154 {
155   FILE *fp = (FILE *)vp;
156
157   file_unlock(fileno(fp), file_lock_depth);
158   fclose(fp);
159   DEBUG(7, ("endfilepwent: closed file.\n"));
160 }
161
162 /*************************************************************************
163  Return the current position in the file list as an SMB_BIG_UINT.
164  This must be treated as an opaque token.
165 *************************************************************************/
166 SMB_BIG_UINT getfilepwpos(void *vp)
167 {
168   return (SMB_BIG_UINT)sys_ftell((FILE *)vp);
169 }
170
171 /*************************************************************************
172  Set the current position in the file list from an SMB_BIG_UINT.
173  This must be treated as an opaque token.
174 *************************************************************************/
175 BOOL setfilepwpos(void *vp, SMB_BIG_UINT tok)
176 {
177   return !sys_fseek((FILE *)vp, (SMB_OFF_T)tok, SEEK_SET);
178 }
179
180 /*************************************************************************
181  gets a line out of a file.
182  line is of format "xxxx:xxxxxx:xxxxx:".
183  lines with "#" at the front are ignored.
184 *************************************************************************/
185 int getfileline(void *vp, char *linebuf, int linebuf_size)
186 {
187         /* Static buffers we will return. */
188         FILE *fp = (FILE *)vp;
189         unsigned char   c;
190         unsigned char  *p;
191         size_t            linebuf_len;
192
193         if (fp == NULL)
194         {
195                 DEBUG(0,("getfileline: Bad file pointer.\n"));
196                 return -1;
197         }
198
199         /*
200          * Scan the file, a line at a time.
201          */
202         while (!feof(fp))
203         {
204                 linebuf[0] = '\0';
205
206                 fgets(linebuf, linebuf_size, fp);
207                 if (ferror(fp))
208                 {
209                         return -1;
210                 }
211
212                 /*
213                  * Check if the string is terminated with a newline - if not
214                  * then we must keep reading and discard until we get one.
215                  */
216
217                 linebuf_len = strlen(linebuf);
218                 if (linebuf_len == 0)
219                 {
220                         linebuf[0] = '\0';
221                         return 0;
222                 }
223
224                 if (linebuf[linebuf_len - 1] != '\n')
225                 {
226                         c = '\0';
227                         while (!ferror(fp) && !feof(fp))
228                         {
229                                 c = fgetc(fp);
230                                 if (c == '\n')
231                                 {
232                                         break;
233                                 }
234                         }
235                 }
236                 else
237                 {
238                         linebuf[linebuf_len - 1] = '\0';
239                 }
240
241 #ifdef DEBUG_PASSWORD
242                 DEBUG(100, ("getfileline: got line |%s|\n", linebuf));
243 #endif
244                 if ((linebuf[0] == 0) && feof(fp))
245                 {
246                         DEBUG(4, ("getfileline: end of file reached\n"));
247                         return 0;
248                 }
249
250                 if (linebuf[0] == '#' || linebuf[0] == '\0')
251                 {
252                         DEBUG(6, ("getfileline: skipping comment or blank line\n"));
253                         continue;
254                 }
255
256                 p = (unsigned char *) strchr_m(linebuf, ':');
257                 if (p == NULL)
258                 {
259                         DEBUG(0, ("getfileline: malformed line entry (no :)\n"));
260                         continue;
261                 }
262                 return linebuf_len;
263         }
264         return -1;
265 }
266
267
268 /****************************************************************************
269 read a line from a file with possible \ continuation chars. 
270 Blanks at the start or end of a line are stripped.
271 The string will be allocated if s2 is NULL
272 ****************************************************************************/
273 char *fgets_slash(char *s2,int maxlen,XFILE *f)
274 {
275   char *s=s2;
276   int len = 0;
277   int c;
278   BOOL start_of_line = True;
279
280   if (x_feof(f))
281     return(NULL);
282
283   if (maxlen <2) return(NULL);
284
285   if (!s2)
286     {
287       maxlen = MIN(maxlen,8);
288       s = (char *)malloc(maxlen);
289     }
290
291   if (!s) return(NULL);
292
293   *s = 0;
294
295   while (len < maxlen-1)
296     {
297       c = x_getc(f);
298       switch (c)
299         {
300         case '\r':
301           break;
302         case '\n':
303           while (len > 0 && s[len-1] == ' ')
304             {
305               s[--len] = 0;
306             }
307           if (len > 0 && s[len-1] == '\\')
308             {
309               s[--len] = 0;
310               start_of_line = True;
311               break;
312             }
313           return(s);
314         case EOF:
315           if (len <= 0 && !s2) 
316             SAFE_FREE(s);
317           return(len>0?s:NULL);
318         case ' ':
319           if (start_of_line)
320             break;
321         default:
322           start_of_line = False;
323           s[len++] = c;
324           s[len] = 0;
325         }
326       if (!s2 && len > maxlen-3)
327         {
328           char *t;
329           
330           maxlen *= 2;
331           t = (char *)Realloc(s,maxlen);
332           if (!t) {
333             DEBUG(0,("fgets_slash: failed to expand buffer!\n"));
334             SAFE_FREE(s);
335             return(NULL);
336           } else s = t;
337         }
338     }
339   return(s);
340 }
341
342
343 /****************************************************************************
344 load from a pipe into memory
345 ****************************************************************************/
346 char *file_pload(char *syscmd, size_t *size)
347 {
348         int fd, n;
349         char *p, *tp;
350         pstring buf;
351         size_t total;
352         
353         fd = sys_popen(syscmd);
354         if (fd == -1) return NULL;
355
356         p = NULL;
357         total = 0;
358
359         while ((n = read(fd, buf, sizeof(buf))) > 0) {
360                 tp = Realloc(p, total + n + 1);
361                 if (!tp) {
362                         DEBUG(0,("file_pload: failed to exand buffer!\n"));
363                         close(fd);
364                         SAFE_FREE(p);
365                         return NULL;
366                 } else p = tp;
367                 memcpy(p+total, buf, n);
368                 total += n;
369         }
370         if (p) p[total] = 0;
371
372         sys_pclose(fd);
373
374         if (size) *size = total;
375
376         return p;
377 }
378
379 /****************************************************************************
380 load a file into memory from a fd.
381 ****************************************************************************/ 
382
383 char *fd_load(int fd, size_t *size)
384 {
385         SMB_STRUCT_STAT sbuf;
386         char *p;
387
388         if (sys_fstat(fd, &sbuf) != 0) return NULL;
389
390         p = (char *)malloc(sbuf.st_size+1);
391         if (!p) return NULL;
392
393         if (read(fd, p, sbuf.st_size) != sbuf.st_size) {
394                 SAFE_FREE(p);
395                 return NULL;
396         }
397         p[sbuf.st_size] = 0;
398
399         if (size) *size = sbuf.st_size;
400
401         return p;
402 }
403
404 /****************************************************************************
405 load a file into memory
406 ****************************************************************************/
407 char *file_load(const char *fname, size_t *size)
408 {
409         int fd;
410         char *p;
411
412         if (!fname || !*fname) return NULL;
413         
414         fd = open(fname,O_RDONLY);
415         if (fd == -1) return NULL;
416
417         p = fd_load(fd, size);
418
419         close(fd);
420
421         return p;
422 }
423
424
425 /*******************************************************************
426 mmap (if possible) or read a file
427 ********************************************************************/
428 void *map_file(char *fname, size_t size)
429 {
430         size_t s2 = 0;
431         void *p = NULL;
432 #ifdef HAVE_MMAP
433         int fd;
434         fd = open(fname, O_RDONLY, 0);
435         if (fd == -1) {
436                 DEBUG(1,("Failed to load %s - %s\n", fname, strerror(errno)));
437                 return NULL;
438         }
439         p = mmap(NULL, size, PROT_READ, MAP_SHARED|MAP_FILE, fd, 0);
440         close(fd);
441         if (p == MAP_FAILED) {
442                 DEBUG(1,("Failed to mmap %s - %s\n", fname, strerror(errno)));
443                 return NULL;
444         }
445 #endif
446         if (!p) {
447                 p = file_load(fname, &s2);
448                 if (!p || s2 != size) {
449                         DEBUG(1,("incorrect size for %s - got %d expected %d\n",
450                                  fname, s2, size));
451                         if (p) free(p);
452                         return NULL;
453                 }
454         }
455
456         return p;
457 }
458
459
460 /****************************************************************************
461 parse a buffer into lines
462 ****************************************************************************/
463 static char **file_lines_parse(char *p, size_t size, int *numlines)
464 {
465         int i;
466         char *s, **ret;
467
468         if (!p) return NULL;
469
470         for (s = p, i=0; s < p+size; s++) {
471                 if (s[0] == '\n') i++;
472         }
473
474         ret = (char **)malloc(sizeof(ret[0])*(i+2));
475         if (!ret) {
476                 SAFE_FREE(p);
477                 return NULL;
478         }       
479         memset(ret, 0, sizeof(ret[0])*(i+2));
480         if (numlines) *numlines = i;
481
482         ret[0] = p;
483         for (s = p, i=0; s < p+size; s++) {
484                 if (s[0] == '\n') {
485                         s[0] = 0;
486                         i++;
487                         ret[i] = s+1;
488                 }
489                 if (s[0] == '\r') s[0] = 0;
490         }
491
492         return ret;
493 }
494
495
496 /****************************************************************************
497 load a file into memory and return an array of pointers to lines in the file
498 must be freed with file_lines_free(). 
499 ****************************************************************************/
500 char **file_lines_load(const char *fname, int *numlines)
501 {
502         char *p;
503         size_t size;
504
505         p = file_load(fname, &size);
506         if (!p) return NULL;
507
508         return file_lines_parse(p, size, numlines);
509 }
510
511 /****************************************************************************
512 load a fd into memory and return an array of pointers to lines in the file
513 must be freed with file_lines_free(). If convert is true calls unix_to_dos on
514 the list.
515 ****************************************************************************/
516 char **fd_lines_load(int fd, int *numlines)
517 {
518         char *p;
519         size_t size;
520
521         p = fd_load(fd, &size);
522         if (!p) return NULL;
523
524         return file_lines_parse(p, size, numlines);
525 }
526
527
528 /****************************************************************************
529 load a pipe into memory and return an array of pointers to lines in the data
530 must be freed with file_lines_free(). 
531 ****************************************************************************/
532 char **file_lines_pload(char *syscmd, int *numlines)
533 {
534         char *p;
535         size_t size;
536
537         p = file_pload(syscmd, &size);
538         if (!p) return NULL;
539
540         return file_lines_parse(p, size, numlines);
541 }
542
543 /****************************************************************************
544 free lines loaded with file_lines_load
545 ****************************************************************************/
546 void file_lines_free(char **lines)
547 {
548         if (!lines) return;
549         SAFE_FREE(lines[0]);
550         SAFE_FREE(lines);
551 }
552
553
554 /****************************************************************************
555 take a lislist of lines and modify them to produce a list where \ continues
556 a line
557 ****************************************************************************/
558 void file_lines_slashcont(char **lines)
559 {
560         int i, j;
561
562         for (i=0; lines[i];) {
563                 int len = strlen(lines[i]);
564                 if (lines[i][len-1] == '\\') {
565                         lines[i][len-1] = ' ';
566                         if (lines[i+1]) {
567                                 char *p = &lines[i][len];
568                                 while (p < lines[i+1]) *p++ = ' ';
569                                 for (j = i+1; lines[j]; j++) lines[j] = lines[j+1];
570                         }
571                 } else {
572                         i++;
573                 }
574         }
575 }
576
577 /*
578   save a lump of data into a file. Mostly used for debugging 
579 */
580 BOOL file_save(const char *fname, void *packet, size_t length)
581 {
582         int fd;
583         fd = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0644);
584         if (fd == -1) {
585                 return False;
586         }
587         if (write(fd, packet, length) != length) {
588                 return False;
589         }
590         close(fd);
591         return True;
592 }