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