-dead option elimination
[oweals/gnunet.git] / src / util / disk.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001--2012 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file util/disk.c
23  * @brief disk IO convenience methods
24  * @author Christian Grothoff
25  * @author Nils Durner
26  */
27
28 #include "platform.h"
29 #include "gnunet_common.h"
30 #include "gnunet_directories.h"
31 #include "gnunet_disk_lib.h"
32 #include "gnunet_scheduler_lib.h"
33 #include "gnunet_strings_lib.h"
34 #include "gnunet_crypto_lib.h"
35 #include "disk.h"
36
37 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
38
39 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
40
41 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
42
43 /**
44  * Block size for IO for copying files.
45  */
46 #define COPY_BLK_SIZE 65536
47
48
49
50 #if defined(LINUX) || defined(CYGWIN) || defined(GNU)
51 #include <sys/vfs.h>
52 #else
53 #if defined(SOMEBSD) || defined(DARWIN)
54 #include <sys/param.h>
55 #include <sys/mount.h>
56 #else
57 #ifdef SOLARIS
58 #include <sys/types.h>
59 #include <sys/statvfs.h>
60 #else
61 #ifdef MINGW
62 #ifndef PIPE_BUF
63 #define PIPE_BUF        512
64 ULONG PipeSerialNumber;
65 #endif
66 #define         _IFMT           0170000 /* type of file */
67 #define         _IFLNK          0120000 /* symbolic link */
68 #define  S_ISLNK(m)     (((m)&_IFMT) == _IFLNK)
69 #else
70 #error PORT-ME: need to port statfs (how much space is left on the drive?)
71 #endif
72 #endif
73 #endif
74 #endif
75
76 #if !defined(SOMEBSD) && !defined(DARWIN) && !defined(WINDOWS)
77 #include <wordexp.h>
78 #endif
79 #if LINUX
80 #include <sys/statvfs.h>
81 #endif
82
83
84 /**
85  * Handle used to manage a pipe.
86  */
87 struct GNUNET_DISK_PipeHandle
88 {
89   /**
90    * File descriptors for the pipe.
91    * One or both of them could be NULL.
92    */
93   struct GNUNET_DISK_FileHandle *fd[2];
94 };
95
96
97 /**
98  * Closure for the recursion to determine the file size
99  * of a directory.
100  */
101 struct GetFileSizeData
102 {
103   /**
104    * Set to the total file size.
105    */
106   uint64_t total;
107
108   /**
109    * GNUNET_YES if symbolic links should be included.
110    */
111   int include_sym_links;
112
113   /**
114    * GNUNET_YES if mode is file-only (return total == -1 for directories).
115    */
116   int single_file_mode;
117 };
118
119
120 #ifndef MINGW
121 /**
122  * Translate GNUnet-internal permission bitmap to UNIX file
123  * access permission bitmap.
124  *
125  * @param perm file permissions, GNUnet style
126  * @return file permissions, UNIX style
127  */
128 static int
129 translate_unix_perms (enum GNUNET_DISK_AccessPermissions perm)
130 {
131   int mode;
132
133   mode = 0;
134   if (perm & GNUNET_DISK_PERM_USER_READ)
135     mode |= S_IRUSR;
136   if (perm & GNUNET_DISK_PERM_USER_WRITE)
137     mode |= S_IWUSR;
138   if (perm & GNUNET_DISK_PERM_USER_EXEC)
139     mode |= S_IXUSR;
140   if (perm & GNUNET_DISK_PERM_GROUP_READ)
141     mode |= S_IRGRP;
142   if (perm & GNUNET_DISK_PERM_GROUP_WRITE)
143     mode |= S_IWGRP;
144   if (perm & GNUNET_DISK_PERM_GROUP_EXEC)
145     mode |= S_IXGRP;
146   if (perm & GNUNET_DISK_PERM_OTHER_READ)
147     mode |= S_IROTH;
148   if (perm & GNUNET_DISK_PERM_OTHER_WRITE)
149     mode |= S_IWOTH;
150   if (perm & GNUNET_DISK_PERM_OTHER_EXEC)
151     mode |= S_IXOTH;
152
153   return mode;
154 }
155 #endif
156
157
158 /**
159  * Iterate over all files in the given directory and
160  * accumulate their size.
161  *
162  * @param cls closure of type "struct GetFileSizeData"
163  * @param fn current filename we are looking at
164  * @return GNUNET_SYSERR on serious errors, otherwise GNUNET_OK
165  */
166 static int
167 getSizeRec (void *cls, const char *fn)
168 {
169   struct GetFileSizeData *gfsd = cls;
170
171 #ifdef HAVE_STAT64
172   struct stat64 buf;
173 #else
174   struct stat buf;
175 #endif
176
177 #ifdef HAVE_STAT64
178   if (0 != STAT64 (fn, &buf))
179   {
180     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_DEBUG, "stat64", fn);
181     return GNUNET_SYSERR;
182   }
183 #else
184   if (0 != STAT (fn, &buf))
185   {
186     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_DEBUG, "stat", fn);
187     return GNUNET_SYSERR;
188   }
189 #endif
190   if ((S_ISDIR (buf.st_mode)) && (gfsd->single_file_mode == GNUNET_YES))
191   {
192     errno = EISDIR;
193     return GNUNET_SYSERR;
194   }
195   if ((!S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES))
196     gfsd->total += buf.st_size;
197   if ((S_ISDIR (buf.st_mode)) && (0 == ACCESS (fn, X_OK)) &&
198       ((!S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES)))
199   {
200     if (GNUNET_SYSERR == GNUNET_DISK_directory_scan (fn, &getSizeRec, gfsd))
201       return GNUNET_SYSERR;
202   }
203   return GNUNET_OK;
204 }
205
206
207 /**
208  * Checks whether a handle is invalid
209  *
210  * @param h handle to check
211  * @return GNUNET_YES if invalid, GNUNET_NO if valid
212  */
213 int
214 GNUNET_DISK_handle_invalid (const struct GNUNET_DISK_FileHandle *h)
215 {
216 #ifdef MINGW
217   return ((!h) || (h->h == INVALID_HANDLE_VALUE)) ? GNUNET_YES : GNUNET_NO;
218 #else
219   return ((!h) || (h->fd == -1)) ? GNUNET_YES : GNUNET_NO;
220 #endif
221 }
222
223 /**
224  * Get the size of an open file.
225  *
226  * @param fh open file handle
227  * @param size where to write size of the file
228  * @return GNUNET_OK on success, GNUNET_SYSERR on error
229  */
230 int
231 GNUNET_DISK_file_handle_size (struct GNUNET_DISK_FileHandle *fh,
232                               OFF_T *size)
233 {
234 #if WINDOWS
235   BOOL b;
236   LARGE_INTEGER li;
237   b = GetFileSizeEx (fh->h, &li);
238   if (!b)
239   {
240     SetErrnoFromWinError (GetLastError ());
241     return GNUNET_SYSERR;
242   }
243   *size = (OFF_T) li.QuadPart;
244 #else
245   struct stat sbuf;
246
247   if (0 != FSTAT (fh->fd, &sbuf))
248     return GNUNET_SYSERR;
249   *size = sbuf.st_size;
250 #endif
251   return GNUNET_OK;
252 }
253
254
255 /**
256  * Move the read/write pointer in a file
257  *
258  * @param h handle of an open file
259  * @param offset position to move to
260  * @param whence specification to which position the offset parameter relates to
261  * @return the new position on success, GNUNET_SYSERR otherwise
262  */
263 OFF_T
264 GNUNET_DISK_file_seek (const struct GNUNET_DISK_FileHandle * h, OFF_T offset,
265                        enum GNUNET_DISK_Seek whence)
266 {
267   if (h == NULL)
268   {
269     errno = EINVAL;
270     return GNUNET_SYSERR;
271   }
272
273 #ifdef MINGW
274   LARGE_INTEGER li;
275   LARGE_INTEGER new_pos;
276   BOOL b;
277
278   static DWORD t[] = { FILE_BEGIN, FILE_CURRENT, FILE_END };
279   li.QuadPart = offset;
280
281   b = SetFilePointerEx (h->h, li, &new_pos, t[whence]);
282   if (b == 0)
283   {
284     SetErrnoFromWinError (GetLastError ());
285     return GNUNET_SYSERR;
286   }
287   return (OFF_T) new_pos.QuadPart;
288 #else
289   static int t[] = { SEEK_SET, SEEK_CUR, SEEK_END };
290
291   return lseek (h->fd, offset, t[whence]);
292 #endif
293 }
294
295
296 /**
297  * Get the size of the file (or directory) of the given file (in
298  * bytes).
299  *
300  * @param filename name of the file or directory
301  * @param size set to the size of the file (or,
302  *             in the case of directories, the sum
303  *             of all sizes of files in the directory)
304  * @param includeSymLinks should symbolic links be
305  *        included?
306  * @param singleFileMode GNUNET_YES to only get size of one file
307  *        and return GNUNET_SYSERR for directories.
308  * @return GNUNET_SYSERR on error, GNUNET_OK on success
309  */
310 int
311 GNUNET_DISK_file_size (const char *filename, uint64_t * size,
312                        int includeSymLinks, int singleFileMode)
313 {
314   struct GetFileSizeData gfsd;
315   int ret;
316
317   GNUNET_assert (size != NULL);
318   gfsd.total = 0;
319   gfsd.include_sym_links = includeSymLinks;
320   gfsd.single_file_mode = singleFileMode;
321   ret = getSizeRec (&gfsd, filename);
322   *size = gfsd.total;
323   return ret;
324 }
325
326
327 /**
328  * Obtain some unique identifiers for the given file
329  * that can be used to identify it in the local system.
330  * This function is used between GNUnet processes to
331  * quickly check if two files with the same absolute path
332  * are actually identical.  The two processes represent
333  * the same peer but may communicate over the network
334  * (and the file may be on an NFS volume).  This function
335  * may not be supported on all operating systems.
336  *
337  * @param filename name of the file
338  * @param dev set to the device ID
339  * @param ino set to the inode ID
340  * @return GNUNET_OK on success
341  */
342 int
343 GNUNET_DISK_file_get_identifiers (const char *filename, uint64_t * dev,
344                                   uint64_t * ino)
345 {
346 #if LINUX
347   struct stat sbuf;
348   struct statvfs fbuf;
349
350   if ((0 == stat (filename, &sbuf)) && (0 == statvfs (filename, &fbuf)))
351   {
352     *dev = (uint64_t) fbuf.f_fsid;
353     *ino = (uint64_t) sbuf.st_ino;
354     return GNUNET_OK;
355   }
356 #elif SOMEBSD
357   struct stat sbuf;
358   struct statfs fbuf;
359
360   if ((0 == stat (filename, &sbuf)) && (0 == statfs (filename, &fbuf)))
361   {
362     *dev = ((uint64_t) fbuf.f_fsid.val[0]) << 32 ||
363         ((uint64_t) fbuf.f_fsid.val[1]);
364     *ino = (uint64_t) sbuf.st_ino;
365     return GNUNET_OK;
366   }
367 #elif WINDOWS
368   // FIXME NILS: test this
369   struct GNUNET_DISK_FileHandle *fh;
370   BY_HANDLE_FILE_INFORMATION info;
371   int succ;
372
373   fh = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ, 0);
374   if (fh == NULL)
375     return GNUNET_SYSERR;
376   succ = GetFileInformationByHandle (fh->h, &info);
377   GNUNET_DISK_file_close (fh);
378   if (succ)
379   {
380     *dev = info.dwVolumeSerialNumber;
381     *ino = ((((uint64_t) info.nFileIndexHigh) << (sizeof (DWORD) * 8)) | info.nFileIndexLow);
382     return GNUNET_OK;
383   }
384   else
385     return GNUNET_SYSERR;
386
387 #endif
388   return GNUNET_SYSERR;
389 }
390
391
392 /**
393  * Create the name for a temporary file or directory from a template.
394  *
395  * @param t template (without XXXXX or "/tmp/")
396  * @return name ready for passing to 'mktemp' or 'mkdtemp', NULL on error
397  */
398 static char *
399 mktemp_name (const char *t)
400 {
401   const char *tmpdir;
402   char *tmpl;
403   char *fn;
404
405   if ((t[0] != '/') && (t[0] != '\\')
406 #if WINDOWS
407       && !(isalpha ((int) t[0]) && (t[0] != '\0') && (t[1] == ':'))
408 #endif
409       )
410   {
411     /* FIXME: This uses system codepage on W32, not UTF-8 */
412     tmpdir = getenv ("TMPDIR");
413     if (NULL == tmpdir)
414       tmpdir = getenv ("TMP");
415     if (NULL == tmpdir)
416       tmpdir = getenv ("TEMP");  
417     if (NULL == tmpdir)
418       tmpdir = "/tmp";
419     GNUNET_asprintf (&tmpl, "%s/%s%s", tmpdir, t, "XXXXXX");
420   }
421   else
422   {
423     GNUNET_asprintf (&tmpl, "%s%s", t, "XXXXXX");
424   }
425 #ifdef MINGW
426   fn = (char *) GNUNET_malloc (MAX_PATH + 1);
427   if (ERROR_SUCCESS != plibc_conv_to_win_path (tmpl, fn))
428   {
429     GNUNET_free (fn);
430     GNUNET_free (tmpl);
431     return NULL;
432   }
433   GNUNET_free (tmpl);
434 #else
435   fn = tmpl;
436 #endif
437   return fn;
438 }
439
440
441 #if WINDOWS
442 static char *
443 mkdtemp (char *fn)
444 {
445   char *random_fn;
446   char *tfn;
447
448   while (1)
449   {
450     tfn = GNUNET_strdup (fn);
451     random_fn = _mktemp (tfn);
452     if (NULL == random_fn)
453     {
454       GNUNET_free (tfn);
455       return NULL;
456     }
457     /* FIXME: assume fn to be UTF-8-encoded and do the right thing */
458     if (0 == CreateDirectoryA (tfn, NULL))
459     {
460       DWORD error = GetLastError ();
461       GNUNET_free (tfn);
462       if (ERROR_ALREADY_EXISTS == error)
463         continue;
464       return NULL;
465     }
466     break;
467   }
468   strcpy (fn, tfn);
469   return fn;
470 }
471 #endif
472
473 /**
474  * Create an (empty) temporary directory on disk.  If the given name is not
475  * an absolute path, the current 'TMPDIR' will be prepended.  In any case,
476  * 6 random characters will be appended to the name to create a unique
477  * filename.
478  *
479  * @param t component to use for the name;
480  *        does NOT contain "XXXXXX" or "/tmp/".
481  * @return NULL on error, otherwise name of fresh
482  *         file on disk in directory for temporary files
483  */
484 char *
485 GNUNET_DISK_mkdtemp (const char *t)
486 {
487   char *fn;
488
489   fn = mktemp_name (t);
490   if (fn != mkdtemp (fn))
491   {
492     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "mkstemp", fn);
493     GNUNET_free (fn);
494     return NULL;
495   }
496   return fn;
497 }
498
499
500 /**
501  * Move a file out of the way (create a backup) by
502  * renaming it to "orig.NUM~" where NUM is the smallest
503  * number that is not used yet.
504  *
505  * @param fil name of the file to back up
506  */
507 void
508 GNUNET_DISK_file_backup (const char *fil)
509 {
510   size_t slen;
511   char *target;
512   unsigned int num;
513
514   slen = strlen (fil) + 20;
515   target = GNUNET_malloc (slen);
516   num = 0;
517   do
518   {
519     GNUNET_snprintf (target, slen,
520                      "%s.%u~",
521                      fil,
522                      num++);
523   } while (0 == access (target, F_OK));
524   if (0 != rename (fil, target))
525     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
526                               "rename",
527                               fil);
528   GNUNET_free (target);  
529 }
530
531
532 /**
533  * Create an (empty) temporary file on disk.  If the given name is not
534  * an absolute path, the current 'TMPDIR' will be prepended.  In any case,
535  * 6 random characters will be appended to the name to create a unique
536  * filename.
537  *
538  * @param t component to use for the name;
539  *        does NOT contain "XXXXXX" or "/tmp/".
540  * @return NULL on error, otherwise name of fresh
541  *         file on disk in directory for temporary files
542  */
543 char *
544 GNUNET_DISK_mktemp (const char *t)
545 {
546   int fd;
547   char *fn;
548
549   fn = mktemp_name (t);
550   if (-1 == (fd = mkstemp (fn)))
551   {
552     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "mkstemp", fn);
553     GNUNET_free (fn);
554     return NULL;
555   }
556   if (0 != CLOSE (fd))
557     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "close", fn);
558   return fn;
559 }
560
561
562 /**
563  * Get the number of blocks that are left on the partition that
564  * contains the given file (for normal users).
565  *
566  * @param part a file on the partition to check
567  * @return -1 on errors, otherwise the number of free blocks
568  */
569 long
570 GNUNET_DISK_get_blocks_available (const char *part)
571 {
572 #ifdef SOLARIS
573   struct statvfs buf;
574
575   if (0 != statvfs (part, &buf))
576   {
577     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
578     return -1;
579   }
580   return buf.f_bavail;
581 #elif MINGW
582   DWORD dwDummy;
583   DWORD dwBlocks;
584   wchar_t szDrive[4];
585   wchar_t wpath[MAX_PATH + 1];
586   char *path;
587
588   path = GNUNET_STRINGS_filename_expand (part);
589   if (path == NULL)
590     return -1;
591   /* "part" was in UTF-8, and so is "path" */
592   if (ERROR_SUCCESS != plibc_conv_to_win_pathwconv(path, wpath))
593   {
594     GNUNET_free (path);
595     return -1;
596   }
597   GNUNET_free (path);
598   wcsncpy (szDrive, wpath, 3);
599   szDrive[3] = 0;
600   if (!GetDiskFreeSpaceW (szDrive, &dwDummy, &dwDummy, &dwBlocks, &dwDummy))
601   {
602     LOG (GNUNET_ERROR_TYPE_WARNING, _("`%s' failed for drive `%S': %u\n"),
603          "GetDiskFreeSpace", szDrive, GetLastError ());
604
605     return -1;
606   }
607   return dwBlocks;
608 #else
609   struct statfs s;
610
611   if (0 != statfs (part, &s))
612   {
613     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
614     return -1;
615   }
616   return s.f_bavail;
617 #endif
618 }
619
620
621 /**
622  * Test if "fil" is a directory and listable. Optionally, also check if the
623  * directory is readable.  Will not print an error message if the directory does
624  * not exist.  Will log errors if GNUNET_SYSERR is returned (i.e., a file exists
625  * with the same name).
626  *
627  * @param fil filename to test
628  * @param is_readable GNUNET_YES to additionally check if "fil" is readable;
629  *          GNUNET_NO to disable this check
630  * @return GNUNET_YES if yes, GNUNET_NO if not; GNUNET_SYSERR if it
631  *           does not exist or stat'ed
632  */
633 int
634 GNUNET_DISK_directory_test (const char *fil, int is_readable)
635 {
636   struct stat filestat;
637   int ret;
638
639   ret = STAT (fil, &filestat);
640   if (ret != 0)
641   {
642     if (errno != ENOENT)
643       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", fil);
644     return GNUNET_SYSERR;
645   }
646   if (!S_ISDIR (filestat.st_mode))
647   {
648     LOG (GNUNET_ERROR_TYPE_WARNING,
649          "A file already exits with the same name %s\n", fil);
650     return GNUNET_NO;
651   }
652   if (GNUNET_YES == is_readable)
653     ret = ACCESS (fil, R_OK | X_OK);
654   else
655     ret = ACCESS (fil, X_OK);
656   if (ret < 0)
657   {
658     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", fil);
659     return GNUNET_NO;
660   }
661   return GNUNET_YES;
662 }
663
664
665 /**
666  * Check that fil corresponds to a filename
667  * (of a file that exists and that is not a directory).
668  *
669  * @param fil filename to check
670  * @return GNUNET_YES if yes, GNUNET_NO if not a file, GNUNET_SYSERR if something
671  * else (will print an error message in that case, too).
672  */
673 int
674 GNUNET_DISK_file_test (const char *fil)
675 {
676   struct stat filestat;
677   int ret;
678   char *rdir;
679
680   rdir = GNUNET_STRINGS_filename_expand (fil);
681   if (rdir == NULL)
682     return GNUNET_SYSERR;
683
684   ret = STAT (rdir, &filestat);
685   if (ret != 0)
686   {
687     if (errno != ENOENT)
688     {
689       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", rdir);
690       GNUNET_free (rdir);
691       return GNUNET_SYSERR;
692     }
693     GNUNET_free (rdir);
694     return GNUNET_NO;
695   }
696   if (!S_ISREG (filestat.st_mode))
697   {
698     GNUNET_free (rdir);
699     return GNUNET_NO;
700   }
701   if (ACCESS (rdir, F_OK) < 0)
702   {
703     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", rdir);
704     GNUNET_free (rdir);
705     return GNUNET_SYSERR;
706   }
707   GNUNET_free (rdir);
708   return GNUNET_YES;
709 }
710
711
712 /**
713  * Implementation of "mkdir -p"
714  * @param dir the directory to create
715  * @returns GNUNET_OK on success, GNUNET_SYSERR on failure
716  */
717 int
718 GNUNET_DISK_directory_create (const char *dir)
719 {
720   char *rdir;
721   unsigned int len;
722   unsigned int pos;
723   unsigned int pos2;
724   int ret = GNUNET_OK;
725
726   rdir = GNUNET_STRINGS_filename_expand (dir);
727   if (rdir == NULL)
728     return GNUNET_SYSERR;
729
730   len = strlen (rdir);
731 #ifndef MINGW
732   pos = 1;                      /* skip heading '/' */
733 #else
734   /* Local or Network path? */
735   if (strncmp (rdir, "\\\\", 2) == 0)
736   {
737     pos = 2;
738     while (rdir[pos])
739     {
740       if (rdir[pos] == '\\')
741       {
742         pos++;
743         break;
744       }
745       pos++;
746     }
747   }
748   else
749   {
750     pos = 3;                    /* strlen("C:\\") */
751   }
752 #endif
753   /* Check which low level directories already exist */
754   pos2 = len;
755   rdir[len] = DIR_SEPARATOR;
756   while (pos <= pos2)
757   {
758     if (DIR_SEPARATOR == rdir[pos2])
759     {
760       rdir[pos2] = '\0';
761       ret = GNUNET_DISK_directory_test (rdir, GNUNET_NO);
762       if (GNUNET_NO == ret)
763       {
764         GNUNET_free (rdir);
765         return GNUNET_SYSERR;
766       }
767       rdir[pos2] = DIR_SEPARATOR;
768       if (GNUNET_YES == ret)
769       {
770         pos2++;
771         break;
772       }
773     }
774     pos2--;
775   }
776   rdir[len] = '\0';
777   if (pos < pos2)
778     pos = pos2;
779   /* Start creating directories */
780   while (pos <= len)
781   {
782     if ((rdir[pos] == DIR_SEPARATOR) || (pos == len))
783     {
784       rdir[pos] = '\0';
785       ret = GNUNET_DISK_directory_test (rdir, GNUNET_NO);
786       if (GNUNET_NO == ret)
787       {
788         GNUNET_free (rdir);
789         return GNUNET_SYSERR;
790       }
791       if (GNUNET_SYSERR == ret)
792       {
793 #ifndef MINGW
794         ret = mkdir (rdir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);        /* 755 */
795 #else
796         wchar_t wrdir[MAX_PATH + 1];
797         if (ERROR_SUCCESS == plibc_conv_to_win_pathwconv(rdir, wrdir))
798           ret = !CreateDirectoryW (wrdir, NULL);
799         else
800           ret = 1;
801 #endif
802         if ((ret != 0) && (errno != EEXIST))
803         {
804           LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "mkdir", rdir);
805           GNUNET_free (rdir);
806           return GNUNET_SYSERR;
807         }
808       }
809       rdir[pos] = DIR_SEPARATOR;
810     }
811     pos++;
812   }
813   GNUNET_free (rdir);
814   return GNUNET_OK;
815 }
816
817
818 /**
819  * Create the directory structure for storing
820  * a file.
821  *
822  * @param filename name of a file in the directory
823  * @returns GNUNET_OK on success,
824  *          GNUNET_SYSERR on failure,
825  *          GNUNET_NO if the directory
826  *          exists but is not writeable for us
827  */
828 int
829 GNUNET_DISK_directory_create_for_file (const char *filename)
830 {
831   char *rdir;
832   int len;
833   int ret;
834
835   rdir = GNUNET_STRINGS_filename_expand (filename);
836   if (rdir == NULL)
837     return GNUNET_SYSERR;
838   len = strlen (rdir);
839   while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
840     len--;
841   rdir[len] = '\0';
842   ret = GNUNET_DISK_directory_create (rdir);
843   if ((ret == GNUNET_OK) && (0 != ACCESS (rdir, W_OK)))
844     ret = GNUNET_NO;
845   GNUNET_free (rdir);
846   return ret;
847 }
848
849
850 /**
851  * Read the contents of a binary file into a buffer.
852  * @param h handle to an open file
853  * @param result the buffer to write the result to
854  * @param len the maximum number of bytes to read
855  * @return the number of bytes read on success, GNUNET_SYSERR on failure
856  */
857 ssize_t
858 GNUNET_DISK_file_read (const struct GNUNET_DISK_FileHandle * h, void *result,
859                        size_t len)
860 {
861   if (h == NULL)
862   {
863     errno = EINVAL;
864     return GNUNET_SYSERR;
865   }
866
867 #ifdef MINGW
868   DWORD bytesRead;
869
870   if (h->type != GNUNET_DISK_HANLDE_TYPE_PIPE)
871   {
872     if (!ReadFile (h->h, result, len, &bytesRead, NULL))
873     {
874       SetErrnoFromWinError (GetLastError ());
875       return GNUNET_SYSERR;
876     }
877   }
878   else
879   {
880     if (!ReadFile (h->h, result, len, &bytesRead, h->oOverlapRead))
881     {
882       if (GetLastError () != ERROR_IO_PENDING)
883       {
884         LOG (GNUNET_ERROR_TYPE_DEBUG, "Error reading from pipe: %u\n", GetLastError ());
885         SetErrnoFromWinError (GetLastError ());
886         return GNUNET_SYSERR;
887       }
888       LOG (GNUNET_ERROR_TYPE_DEBUG, "Will get overlapped result\n");
889       GetOverlappedResult (h->h, h->oOverlapRead, &bytesRead, TRUE);
890     }
891     LOG (GNUNET_ERROR_TYPE_DEBUG, "Read %u bytes from pipe\n", bytesRead);
892   }
893   return bytesRead;
894 #else
895   return read (h->fd, result, len);
896 #endif
897 }
898
899
900 /**
901  * Read the contents of a binary file into a buffer.
902  * Guarantees not to block (returns GNUNET_SYSERR and sets errno to EAGAIN
903  * when no data can be read).
904  *
905  * @param h handle to an open file
906  * @param result the buffer to write the result to
907  * @param len the maximum number of bytes to read
908  * @return the number of bytes read on success, GNUNET_SYSERR on failure
909  */
910 ssize_t
911 GNUNET_DISK_file_read_non_blocking (const struct GNUNET_DISK_FileHandle * h,
912                                     void *result, 
913                                     size_t len)
914 {
915   if (h == NULL)
916   {
917     errno = EINVAL;
918     return GNUNET_SYSERR;
919   }
920
921 #ifdef MINGW
922   DWORD bytesRead;
923
924   if (h->type != GNUNET_DISK_HANLDE_TYPE_PIPE)
925   {
926     if (!ReadFile (h->h, result, len, &bytesRead, NULL))
927     {
928       SetErrnoFromWinError (GetLastError ());
929       return GNUNET_SYSERR;
930     }
931   }
932   else
933   {
934     if (!ReadFile (h->h, result, len, &bytesRead, h->oOverlapRead))
935     {
936       if (GetLastError () != ERROR_IO_PENDING)
937       {
938         LOG (GNUNET_ERROR_TYPE_DEBUG, "Error reading from pipe: %u\n", GetLastError ());
939         SetErrnoFromWinError (GetLastError ());
940         return GNUNET_SYSERR;
941       }
942       else
943       {
944         LOG (GNUNET_ERROR_TYPE_DEBUG,
945             "ReadFile() queued a read, cancelling\n");
946         CancelIo (h->h);
947         errno = EAGAIN;
948         return GNUNET_SYSERR;
949       }
950     }
951     LOG (GNUNET_ERROR_TYPE_DEBUG, "Read %u bytes\n", bytesRead);
952   }
953   return bytesRead;
954 #else
955   int flags;
956   ssize_t ret;
957
958   /* set to non-blocking, read, then set back */
959   flags = fcntl (h->fd, F_GETFL);
960   if (0 == (flags & O_NONBLOCK))
961     (void) fcntl (h->fd, F_SETFL, flags | O_NONBLOCK);
962   ret = read (h->fd, result, len);
963   if (0 == (flags & O_NONBLOCK))
964     {
965       int eno = errno;
966       (void) fcntl (h->fd, F_SETFL, flags);
967       errno = eno;
968     }
969   return ret;
970 #endif
971 }
972
973
974 /**
975  * Read the contents of a binary file into a buffer.
976  *
977  * @param fn file name
978  * @param result the buffer to write the result to
979  * @param len the maximum number of bytes to read
980  * @return number of bytes read, GNUNET_SYSERR on failure
981  */
982 ssize_t
983 GNUNET_DISK_fn_read (const char *fn, void *result, size_t len)
984 {
985   struct GNUNET_DISK_FileHandle *fh;
986   ssize_t ret;
987
988   fh = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_READ, GNUNET_DISK_PERM_NONE);
989   if (!fh)
990     return GNUNET_SYSERR;
991   ret = GNUNET_DISK_file_read (fh, result, len);
992   GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
993
994   return ret;
995 }
996
997
998 /**
999  * Write a buffer to a file.
1000  * @param h handle to open file
1001  * @param buffer the data to write
1002  * @param n number of bytes to write
1003  * @return number of bytes written on success, GNUNET_SYSERR on error
1004  */
1005 ssize_t
1006 GNUNET_DISK_file_write (const struct GNUNET_DISK_FileHandle * h,
1007                         const void *buffer, size_t n)
1008 {
1009   if (h == NULL)
1010   {
1011     errno = EINVAL;
1012     return GNUNET_SYSERR;
1013   }
1014
1015 #ifdef MINGW
1016   DWORD bytesWritten;
1017
1018   if (h->type != GNUNET_DISK_HANLDE_TYPE_PIPE)
1019   {
1020     if (!WriteFile (h->h, buffer, n, &bytesWritten, NULL))
1021     {
1022       SetErrnoFromWinError (GetLastError ());
1023       return GNUNET_SYSERR;
1024     }
1025   }
1026   else
1027   {
1028     LOG (GNUNET_ERROR_TYPE_DEBUG, "It is a pipe trying to write %u bytes\n", n);
1029     if (!WriteFile (h->h, buffer, n, &bytesWritten, h->oOverlapWrite))
1030     {
1031       if (GetLastError () != ERROR_IO_PENDING)
1032       {
1033         SetErrnoFromWinError (GetLastError ());
1034         LOG (GNUNET_ERROR_TYPE_DEBUG, "Error writing to pipe: %u\n",
1035             GetLastError ());
1036         return GNUNET_SYSERR;
1037       }
1038       LOG (GNUNET_ERROR_TYPE_DEBUG, "Will get overlapped result\n");
1039       if (!GetOverlappedResult (h->h, h->oOverlapWrite, &bytesWritten, TRUE))
1040       {
1041         SetErrnoFromWinError (GetLastError ());
1042         LOG (GNUNET_ERROR_TYPE_DEBUG,
1043             "Error getting overlapped result while writing to pipe: %u\n",
1044             GetLastError ());
1045         return GNUNET_SYSERR;
1046       }
1047     }
1048     else
1049     {
1050       DWORD ovr;
1051       if (!GetOverlappedResult (h->h, h->oOverlapWrite, &ovr, TRUE))
1052       {
1053         LOG (GNUNET_ERROR_TYPE_DEBUG,
1054             "Error getting control overlapped result while writing to pipe: %u\n",
1055             GetLastError ());
1056       }
1057       else
1058       {
1059         LOG (GNUNET_ERROR_TYPE_DEBUG,
1060             "Wrote %u bytes (ovr says %u), picking the greatest\n",
1061             bytesWritten, ovr);
1062       }
1063     }
1064     if (bytesWritten == 0)
1065     {
1066       if (n > 0)
1067       {
1068         LOG (GNUNET_ERROR_TYPE_DEBUG, "Wrote %u bytes, returning -1 with EAGAIN\n", bytesWritten);
1069         errno = EAGAIN;
1070         return GNUNET_SYSERR;
1071       }
1072     }
1073     LOG (GNUNET_ERROR_TYPE_DEBUG, "Wrote %u bytes\n", bytesWritten);
1074   }
1075   return bytesWritten;
1076 #else
1077   return write (h->fd, buffer, n);
1078 #endif
1079 }
1080
1081
1082 /**
1083  * Write a buffer to a file, blocking, if necessary.
1084  * @param h handle to open file
1085  * @param buffer the data to write
1086  * @param n number of bytes to write
1087  * @return number of bytes written on success, GNUNET_SYSERR on error
1088  */
1089 ssize_t
1090 GNUNET_DISK_file_write_blocking (const struct GNUNET_DISK_FileHandle * h,
1091     const void *buffer, size_t n)
1092 {
1093   if (h == NULL)
1094   {
1095     errno = EINVAL;
1096     return GNUNET_SYSERR;
1097   }
1098
1099 #ifdef MINGW
1100   DWORD bytesWritten;
1101   /* We do a non-overlapped write, which is as blocking as it gets */
1102   LOG (GNUNET_ERROR_TYPE_DEBUG, "Writing %u bytes\n", n);
1103   if (!WriteFile (h->h, buffer, n, &bytesWritten, NULL))
1104   {
1105     SetErrnoFromWinError (GetLastError ());
1106     LOG (GNUNET_ERROR_TYPE_DEBUG, "Error writing to pipe: %u\n",
1107         GetLastError ());
1108     return GNUNET_SYSERR;
1109   }
1110   if (bytesWritten == 0 && n > 0)
1111   {
1112     LOG (GNUNET_ERROR_TYPE_DEBUG, "Waiting for pipe to clean\n");
1113     WaitForSingleObject (h->h, INFINITE);
1114     if (!WriteFile (h->h, buffer, n, &bytesWritten, NULL))
1115     {
1116       SetErrnoFromWinError (GetLastError ());
1117       LOG (GNUNET_ERROR_TYPE_DEBUG, "Error writing to pipe: %u\n",
1118           GetLastError ());
1119       return GNUNET_SYSERR;
1120     }
1121   }
1122   LOG (GNUNET_ERROR_TYPE_DEBUG, "Wrote %u bytes\n", bytesWritten);
1123   return bytesWritten;
1124 #else
1125   int flags;
1126   ssize_t ret;
1127
1128   /* set to blocking, write, then set back */
1129   flags = fcntl (h->fd, F_GETFL);
1130   if (0 != (flags & O_NONBLOCK))
1131     (void) fcntl (h->fd, F_SETFL, flags - O_NONBLOCK);
1132   ret = write (h->fd, buffer, n);
1133   if (0 == (flags & O_NONBLOCK))
1134     (void) fcntl (h->fd, F_SETFL, flags);
1135   return ret;
1136 #endif
1137 }
1138
1139
1140 /**
1141  * Write a buffer to a file.  If the file is longer than the
1142  * number of bytes that will be written, it will be truncated.
1143  *
1144  * @param fn file name
1145  * @param buffer the data to write
1146  * @param n number of bytes to write
1147  * @param mode file permissions
1148  * @return number of bytes written on success, GNUNET_SYSERR on error
1149  */
1150 ssize_t
1151 GNUNET_DISK_fn_write (const char *fn, const void *buffer, size_t n,
1152                       enum GNUNET_DISK_AccessPermissions mode)
1153 {
1154   struct GNUNET_DISK_FileHandle *fh;
1155   ssize_t ret;
1156
1157   fh = GNUNET_DISK_file_open (fn,
1158                               GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE
1159                               | GNUNET_DISK_OPEN_CREATE, mode);
1160   if (!fh)
1161     return GNUNET_SYSERR;
1162   ret = GNUNET_DISK_file_write (fh, buffer, n);
1163   GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
1164   return ret;
1165 }
1166
1167
1168 /**
1169  * Scan a directory for files.
1170  *
1171  * @param dirName the name of the directory
1172  * @param callback the method to call for each file,
1173  *        can be NULL, in that case, we only count
1174  * @param callback_cls closure for callback
1175  * @return the number of files found, GNUNET_SYSERR on error or
1176  *         ieration aborted by callback returning GNUNET_SYSERR
1177  */
1178 int
1179 GNUNET_DISK_directory_scan (const char *dirName,
1180                             GNUNET_FileNameCallback callback,
1181                             void *callback_cls)
1182 {
1183   DIR *dinfo;
1184   struct dirent *finfo;
1185   struct stat istat;
1186   int count = 0;
1187   char *name;
1188   char *dname;
1189   unsigned int name_len;
1190   unsigned int n_size;
1191
1192   GNUNET_assert (dirName != NULL);
1193   dname = GNUNET_STRINGS_filename_expand (dirName);
1194   if (dname == NULL)
1195     return GNUNET_SYSERR;
1196   while ((strlen (dname) > 0) && (dname[strlen (dname) - 1] == DIR_SEPARATOR))
1197     dname[strlen (dname) - 1] = '\0';
1198   if (0 != STAT (dname, &istat))
1199   {
1200     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", dname);
1201     GNUNET_free (dname);
1202     return GNUNET_SYSERR;
1203   }
1204   if (!S_ISDIR (istat.st_mode))
1205   {
1206     LOG (GNUNET_ERROR_TYPE_WARNING, _("Expected `%s' to be a directory!\n"),
1207          dirName);
1208     GNUNET_free (dname);
1209     return GNUNET_SYSERR;
1210   }
1211   errno = 0;
1212   dinfo = OPENDIR (dname);
1213   if ((errno == EACCES) || (dinfo == NULL))
1214   {
1215     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "opendir", dname);
1216     if (dinfo != NULL)
1217       CLOSEDIR (dinfo);
1218     GNUNET_free (dname);
1219     return GNUNET_SYSERR;
1220   }
1221   name_len = 256;
1222   n_size = strlen (dname) + name_len + 2;
1223   name = GNUNET_malloc (n_size);
1224   while ((finfo = READDIR (dinfo)) != NULL)
1225   {
1226     if ((0 == strcmp (finfo->d_name, ".")) ||
1227         (0 == strcmp (finfo->d_name, "..")))
1228       continue;
1229     if (callback != NULL)
1230     {
1231       if (name_len < strlen (finfo->d_name))
1232       {
1233         GNUNET_free (name);
1234         name_len = strlen (finfo->d_name);
1235         n_size = strlen (dname) + name_len + 2;
1236         name = GNUNET_malloc (n_size);
1237       }
1238       /* dname can end in "/" only if dname == "/";
1239        * if dname does not end in "/", we need to add
1240        * a "/" (otherwise, we must not!) */
1241       GNUNET_snprintf (name, n_size, "%s%s%s", dname,
1242                        (strcmp (dname, DIR_SEPARATOR_STR) ==
1243                         0) ? "" : DIR_SEPARATOR_STR, finfo->d_name);
1244       if (GNUNET_OK != callback (callback_cls, name))
1245       {
1246         CLOSEDIR (dinfo);
1247         GNUNET_free (name);
1248         GNUNET_free (dname);
1249         return GNUNET_SYSERR;
1250       }
1251     }
1252     count++;
1253   }
1254   CLOSEDIR (dinfo);
1255   GNUNET_free (name);
1256   GNUNET_free (dname);
1257   return count;
1258 }
1259
1260
1261 /**
1262  * Opaque handle used for iterating over a directory.
1263  */
1264 struct GNUNET_DISK_DirectoryIterator
1265 {
1266
1267   /**
1268    * Function to call on directory entries.
1269    */
1270   GNUNET_DISK_DirectoryIteratorCallback callback;
1271
1272   /**
1273    * Closure for callback.
1274    */
1275   void *callback_cls;
1276
1277   /**
1278    * Reference to directory.
1279    */
1280   DIR *directory;
1281
1282   /**
1283    * Directory name.
1284    */
1285   char *dirname;
1286
1287   /**
1288    * Next filename to process.
1289    */
1290   char *next_name;
1291
1292   /**
1293    * Our priority.
1294    */
1295   enum GNUNET_SCHEDULER_Priority priority;
1296
1297 };
1298
1299
1300 /**
1301  * Task used by the directory iterator.
1302  */
1303 static void
1304 directory_iterator_task (void *cls,
1305                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1306 {
1307   struct GNUNET_DISK_DirectoryIterator *iter = cls;
1308   char *name;
1309
1310   name = iter->next_name;
1311   GNUNET_assert (name != NULL);
1312   iter->next_name = NULL;
1313   iter->callback (iter->callback_cls, iter, name, iter->dirname);
1314   GNUNET_free (name);
1315 }
1316
1317
1318 /**
1319  * This function must be called during the DiskIteratorCallback
1320  * (exactly once) to schedule the task to process the next
1321  * filename in the directory (if there is one).
1322  *
1323  * @param iter opaque handle for the iterator
1324  * @param can set to GNUNET_YES to terminate the iteration early
1325  * @return GNUNET_YES if iteration will continue,
1326  *         GNUNET_NO if this was the last entry (and iteration is complete),
1327  *         GNUNET_SYSERR if abort was YES
1328  */
1329 int
1330 GNUNET_DISK_directory_iterator_next (struct GNUNET_DISK_DirectoryIterator *iter,
1331                                      int can)
1332 {
1333   struct dirent *finfo;
1334
1335   GNUNET_assert (iter->next_name == NULL);
1336   if (can == GNUNET_YES)
1337   {
1338     CLOSEDIR (iter->directory);
1339     GNUNET_free (iter->dirname);
1340     GNUNET_free (iter);
1341     return GNUNET_SYSERR;
1342   }
1343   while (NULL != (finfo = READDIR (iter->directory)))
1344   {
1345     if ((0 == strcmp (finfo->d_name, ".")) ||
1346         (0 == strcmp (finfo->d_name, "..")))
1347       continue;
1348     GNUNET_asprintf (&iter->next_name, "%s%s%s", iter->dirname,
1349                      DIR_SEPARATOR_STR, finfo->d_name);
1350     break;
1351   }
1352   if (finfo == NULL)
1353   {
1354     GNUNET_DISK_directory_iterator_next (iter, GNUNET_YES);
1355     return GNUNET_NO;
1356   }
1357   GNUNET_SCHEDULER_add_with_priority (iter->priority, &directory_iterator_task,
1358                                       iter);
1359   return GNUNET_YES;
1360 }
1361
1362
1363 /**
1364  * Scan a directory for files using the scheduler to run a task for
1365  * each entry.  The name of the directory must be expanded first (!).
1366  * If a scheduler does not need to be used, GNUNET_DISK_directory_scan
1367  * may provide a simpler API.
1368  *
1369  * @param prio priority to use
1370  * @param dirName the name of the directory
1371  * @param callback the method to call for each file
1372  * @param callback_cls closure for callback
1373  * @return GNUNET_YES if directory is not empty and 'callback'
1374  *         will be called later, GNUNET_NO otherwise, GNUNET_SYSERR on error.
1375  */
1376 int
1377 GNUNET_DISK_directory_iterator_start (enum GNUNET_SCHEDULER_Priority prio,
1378                                       const char *dirName,
1379                                       GNUNET_DISK_DirectoryIteratorCallback
1380                                       callback, void *callback_cls)
1381 {
1382   struct GNUNET_DISK_DirectoryIterator *di;
1383
1384   di = GNUNET_malloc (sizeof (struct GNUNET_DISK_DirectoryIterator));
1385   di->callback = callback;
1386   di->callback_cls = callback_cls;
1387   di->directory = OPENDIR (dirName);
1388   if (di->directory == NULL)
1389   {
1390     GNUNET_free (di);
1391     callback (callback_cls, NULL, NULL, NULL);
1392     return GNUNET_SYSERR;
1393   }
1394   di->dirname = GNUNET_strdup (dirName);
1395   di->priority = prio;
1396   return GNUNET_DISK_directory_iterator_next (di, GNUNET_NO);
1397 }
1398
1399
1400 /**
1401  * Function that removes the given directory by calling
1402  * "GNUNET_DISK_directory_remove".
1403  *
1404  * @param unused not used
1405  * @param fn directory to remove
1406  * @return GNUNET_OK
1407  */
1408 static int
1409 remove_helper (void *unused, const char *fn)
1410 {
1411   (void) GNUNET_DISK_directory_remove (fn);
1412   return GNUNET_OK;
1413 }
1414
1415
1416 /**
1417  * Remove all files in a directory (rm -rf). Call with
1418  * caution.
1419  *
1420  *
1421  * @param filename the file to remove
1422  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1423  */
1424 int
1425 GNUNET_DISK_directory_remove (const char *filename)
1426 {
1427   struct stat istat;
1428
1429   if (0 != LSTAT (filename, &istat))
1430     return GNUNET_NO;           /* file may not exist... */
1431   (void) CHMOD (filename, S_IWUSR | S_IRUSR | S_IXUSR);
1432   if (UNLINK (filename) == 0)
1433     return GNUNET_OK;
1434   if ((errno != EISDIR) &&
1435       /* EISDIR is not sufficient in all cases, e.g.
1436        * sticky /tmp directory may result in EPERM on BSD.
1437        * So we also explicitly check "isDirectory" */
1438       (GNUNET_YES != GNUNET_DISK_directory_test (filename, GNUNET_YES)))
1439   {
1440     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "rmdir", filename);
1441     return GNUNET_SYSERR;
1442   }
1443   if (GNUNET_SYSERR ==
1444       GNUNET_DISK_directory_scan (filename, &remove_helper, NULL))
1445     return GNUNET_SYSERR;
1446   if (0 != RMDIR (filename))
1447   {
1448     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "rmdir", filename);
1449     return GNUNET_SYSERR;
1450   }
1451   return GNUNET_OK;
1452 }
1453
1454
1455 /**
1456  * Copy a file.
1457  *
1458  * @param src file to copy
1459  * @param dst destination file name
1460  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1461  */
1462 int
1463 GNUNET_DISK_file_copy (const char *src, const char *dst)
1464 {
1465   char *buf;
1466   uint64_t pos;
1467   uint64_t size;
1468   size_t len;
1469   struct GNUNET_DISK_FileHandle *in;
1470   struct GNUNET_DISK_FileHandle *out;
1471
1472   if (GNUNET_OK != GNUNET_DISK_file_size (src, &size, GNUNET_YES, GNUNET_YES))
1473     return GNUNET_SYSERR;
1474   pos = 0;
1475   in = GNUNET_DISK_file_open (src, GNUNET_DISK_OPEN_READ,
1476                               GNUNET_DISK_PERM_NONE);
1477   if (!in)
1478     return GNUNET_SYSERR;
1479   out =
1480       GNUNET_DISK_file_open (dst,
1481                              GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE |
1482                              GNUNET_DISK_OPEN_FAILIFEXISTS,
1483                              GNUNET_DISK_PERM_USER_READ |
1484                              GNUNET_DISK_PERM_USER_WRITE |
1485                              GNUNET_DISK_PERM_GROUP_READ |
1486                              GNUNET_DISK_PERM_GROUP_WRITE);
1487   if (!out)
1488   {
1489     GNUNET_DISK_file_close (in);
1490     return GNUNET_SYSERR;
1491   }
1492   buf = GNUNET_malloc (COPY_BLK_SIZE);
1493   while (pos < size)
1494   {
1495     len = COPY_BLK_SIZE;
1496     if (len > size - pos)
1497       len = size - pos;
1498     if (len != GNUNET_DISK_file_read (in, buf, len))
1499       goto FAIL;
1500     if (len != GNUNET_DISK_file_write (out, buf, len))
1501       goto FAIL;
1502     pos += len;
1503   }
1504   GNUNET_free (buf);
1505   GNUNET_DISK_file_close (in);
1506   GNUNET_DISK_file_close (out);
1507   return GNUNET_OK;
1508 FAIL:
1509   GNUNET_free (buf);
1510   GNUNET_DISK_file_close (in);
1511   GNUNET_DISK_file_close (out);
1512   return GNUNET_SYSERR;
1513 }
1514
1515
1516 /**
1517  * @brief Removes special characters as ':' from a filename.
1518  * @param fn the filename to canonicalize
1519  */
1520 void
1521 GNUNET_DISK_filename_canonicalize (char *fn)
1522 {
1523   char *idx;
1524   char c;
1525
1526   idx = fn;
1527   while (*idx)
1528   {
1529     c = *idx;
1530
1531     if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' || c == '"' ||
1532         c == '<' || c == '>' || c == '|')
1533     {
1534       *idx = '_';
1535     }
1536
1537     idx++;
1538   }
1539 }
1540
1541
1542
1543 /**
1544  * @brief Change owner of a file
1545  *
1546  * @param filename name of file to change the owner of
1547  * @param user name of the new owner
1548  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1549  */
1550 int
1551 GNUNET_DISK_file_change_owner (const char *filename, const char *user)
1552 {
1553 #ifndef MINGW
1554   struct passwd *pws;
1555
1556   pws = getpwnam (user);
1557   if (pws == NULL)
1558   {
1559     LOG (GNUNET_ERROR_TYPE_ERROR,
1560          _("Cannot obtain information about user `%s': %s\n"), user,
1561          STRERROR (errno));
1562     return GNUNET_SYSERR;
1563   }
1564   if (0 != chown (filename, pws->pw_uid, pws->pw_gid))
1565     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "chown", filename);
1566 #endif
1567   return GNUNET_OK;
1568 }
1569
1570
1571 /**
1572  * Lock a part of a file
1573  * @param fh file handle
1574  * @param lockStart absolute position from where to lock
1575  * @param lockEnd absolute position until where to lock
1576  * @param excl GNUNET_YES for an exclusive lock
1577  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1578  */
1579 int
1580 GNUNET_DISK_file_lock (struct GNUNET_DISK_FileHandle *fh, OFF_T lockStart,
1581                        OFF_T lockEnd, int excl)
1582 {
1583   if (fh == NULL)
1584   {
1585     errno = EINVAL;
1586     return GNUNET_SYSERR;
1587   }
1588
1589 #ifndef MINGW
1590   struct flock fl;
1591
1592   memset (&fl, 0, sizeof (struct flock));
1593   fl.l_type = excl ? F_WRLCK : F_RDLCK;
1594   fl.l_whence = SEEK_SET;
1595   fl.l_start = lockStart;
1596   fl.l_len = lockEnd;
1597
1598   return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1599 #else
1600   OVERLAPPED o;
1601   OFF_T diff = lockEnd - lockStart;
1602   DWORD diff_low, diff_high;
1603   diff_low = (DWORD) (diff & 0xFFFFFFFF);
1604   diff_high = (DWORD) ((diff >> (sizeof (DWORD) * 8)) & 0xFFFFFFFF);
1605
1606   memset (&o, 0, sizeof (OVERLAPPED));
1607   o.Offset = (DWORD) (lockStart & 0xFFFFFFFF);;
1608   o.OffsetHigh = (DWORD) (((lockStart & ~0xFFFFFFFF) >> (sizeof (DWORD) * 8)) & 0xFFFFFFFF);
1609
1610   if (!LockFileEx
1611       (fh->h, (excl ? LOCKFILE_EXCLUSIVE_LOCK : 0) | LOCKFILE_FAIL_IMMEDIATELY,
1612        0, diff_low, diff_high, &o))
1613   {
1614     SetErrnoFromWinError (GetLastError ());
1615     return GNUNET_SYSERR;
1616   }
1617
1618   return GNUNET_OK;
1619 #endif
1620 }
1621
1622
1623 /**
1624  * Unlock a part of a file
1625  * @param fh file handle
1626  * @param unlockStart absolute position from where to unlock
1627  * @param unlockEnd absolute position until where to unlock
1628  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1629  */
1630 int
1631 GNUNET_DISK_file_unlock (struct GNUNET_DISK_FileHandle *fh, OFF_T unlockStart,
1632                          OFF_T unlockEnd)
1633 {
1634   if (fh == NULL)
1635   {
1636     errno = EINVAL;
1637     return GNUNET_SYSERR;
1638   }
1639
1640 #ifndef MINGW
1641   struct flock fl;
1642
1643   memset (&fl, 0, sizeof (struct flock));
1644   fl.l_type = F_UNLCK;
1645   fl.l_whence = SEEK_SET;
1646   fl.l_start = unlockStart;
1647   fl.l_len = unlockEnd;
1648
1649   return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1650 #else
1651   OVERLAPPED o;
1652   OFF_T diff = unlockEnd - unlockStart;
1653   DWORD diff_low, diff_high;
1654   diff_low = (DWORD) (diff & 0xFFFFFFFF);
1655   diff_high = (DWORD) ((diff >> (sizeof (DWORD) * 8)) & 0xFFFFFFFF);
1656
1657   memset (&o, 0, sizeof (OVERLAPPED));
1658   o.Offset = (DWORD) (unlockStart & 0xFFFFFFFF);;
1659   o.OffsetHigh = (DWORD) (((unlockStart & ~0xFFFFFFFF) >> (sizeof (DWORD) * 8)) & 0xFFFFFFFF);
1660
1661   if (!UnlockFileEx (fh->h, 0, diff_low, diff_high, &o))
1662   {
1663     SetErrnoFromWinError (GetLastError ());
1664     return GNUNET_SYSERR;
1665   }
1666
1667   return GNUNET_OK;
1668 #endif
1669 }
1670
1671
1672 /**
1673  * Open a file.  Note that the access permissions will only be
1674  * used if a new file is created and if the underlying operating
1675  * system supports the given permissions.
1676  *
1677  * @param fn file name to be opened
1678  * @param flags opening flags, a combination of GNUNET_DISK_OPEN_xxx bit flags
1679  * @param perm permissions for the newly created file, use
1680  *             GNUNET_DISK_PERM_USER_NONE if a file could not be created by this
1681  *             call (because of flags)
1682  * @return IO handle on success, NULL on error
1683  */
1684 struct GNUNET_DISK_FileHandle *
1685 GNUNET_DISK_file_open (const char *fn, enum GNUNET_DISK_OpenFlags flags,
1686                        enum GNUNET_DISK_AccessPermissions perm)
1687 {
1688   char *expfn;
1689   struct GNUNET_DISK_FileHandle *ret;
1690
1691 #ifdef MINGW
1692   DWORD access;
1693   DWORD disp;
1694   HANDLE h;
1695   wchar_t wexpfn[MAX_PATH + 1];
1696 #else
1697   int oflags;
1698   int mode;
1699   int fd;
1700 #endif
1701
1702   expfn = GNUNET_STRINGS_filename_expand (fn);
1703   if (NULL == expfn)
1704     return NULL;
1705 #ifndef MINGW
1706   mode = 0;
1707   if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1708     oflags = O_RDWR;            /* note: O_RDWR is NOT always O_RDONLY | O_WRONLY */
1709   else if (flags & GNUNET_DISK_OPEN_READ)
1710     oflags = O_RDONLY;
1711   else if (flags & GNUNET_DISK_OPEN_WRITE)
1712     oflags = O_WRONLY;
1713   else
1714   {
1715     GNUNET_break (0);
1716     GNUNET_free (expfn);
1717     return NULL;
1718   }
1719   if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1720     oflags |= (O_CREAT | O_EXCL);
1721   if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1722     oflags |= O_TRUNC;
1723   if (flags & GNUNET_DISK_OPEN_APPEND)
1724     oflags |= O_APPEND;
1725   if (flags & GNUNET_DISK_OPEN_CREATE)
1726   {
1727     (void) GNUNET_DISK_directory_create_for_file (expfn);
1728     oflags |= O_CREAT;
1729     mode = translate_unix_perms (perm);
1730   }
1731
1732   fd = open (expfn, oflags 
1733 #if O_CLOEXEC
1734              | O_CLOEXEC
1735 #endif
1736              | O_LARGEFILE, mode);
1737   if (fd == -1)
1738   {
1739     if (0 == (flags & GNUNET_DISK_OPEN_FAILIFEXISTS))
1740       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1741     else
1742       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_DEBUG, "open", expfn);
1743     GNUNET_free (expfn);
1744     return NULL;
1745   }
1746 #else
1747   access = 0;
1748   disp = OPEN_ALWAYS;
1749
1750   if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1751     access = FILE_READ_DATA | FILE_WRITE_DATA;
1752   else if (flags & GNUNET_DISK_OPEN_READ)
1753     access = FILE_READ_DATA;
1754   else if (flags & GNUNET_DISK_OPEN_WRITE)
1755     access = FILE_WRITE_DATA;
1756
1757   if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1758   {
1759     disp = CREATE_NEW;
1760   }
1761   else if (flags & GNUNET_DISK_OPEN_CREATE)
1762   {
1763     (void) GNUNET_DISK_directory_create_for_file (expfn);
1764     if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1765       disp = CREATE_ALWAYS;
1766     else
1767       disp = OPEN_ALWAYS;
1768   }
1769   else if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1770   {
1771     disp = TRUNCATE_EXISTING;
1772   }
1773   else
1774   {
1775     disp = OPEN_EXISTING;
1776   }
1777
1778   if (ERROR_SUCCESS == plibc_conv_to_win_pathwconv(expfn, wexpfn))
1779     h = CreateFileW (wexpfn, access,
1780                     FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1781                     disp, FILE_ATTRIBUTE_NORMAL, NULL);
1782   else
1783     h = INVALID_HANDLE_VALUE;
1784   if (h == INVALID_HANDLE_VALUE)
1785   {
1786     int err;
1787     SetErrnoFromWinError (GetLastError ());
1788     err = errno;
1789     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_INFO, "open", expfn);
1790     GNUNET_free (expfn);
1791     errno = err;
1792     return NULL;
1793   }
1794
1795   if (flags & GNUNET_DISK_OPEN_APPEND)
1796     if (SetFilePointer (h, 0, 0, FILE_END) == INVALID_SET_FILE_POINTER)
1797     {
1798       SetErrnoFromWinError (GetLastError ());
1799       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "SetFilePointer", expfn);
1800       CloseHandle (h);
1801       GNUNET_free (expfn);
1802       return NULL;
1803     }
1804 #endif
1805
1806   ret = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
1807 #ifdef MINGW
1808   ret->h = h;
1809   ret->type = GNUNET_DISK_HANLDE_TYPE_FILE;
1810 #else
1811   ret->fd = fd;
1812 #endif
1813   GNUNET_free (expfn);
1814   return ret;
1815 }
1816
1817
1818 /**
1819  * Close an open file
1820  * @param h file handle
1821  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1822  */
1823 int
1824 GNUNET_DISK_file_close (struct GNUNET_DISK_FileHandle *h)
1825 {
1826   int ret;
1827   if (h == NULL)
1828   {
1829     errno = EINVAL;
1830     return GNUNET_SYSERR;
1831   }
1832
1833   ret = GNUNET_OK;
1834
1835 #if MINGW
1836   if (!CloseHandle (h->h))
1837   {
1838     SetErrnoFromWinError (GetLastError ());
1839     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close");
1840     ret = GNUNET_SYSERR;
1841   }
1842   if (h->oOverlapRead)
1843   {
1844     if (!CloseHandle (h->oOverlapRead->hEvent))
1845     {
1846       SetErrnoFromWinError (GetLastError ());
1847       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close");
1848       ret = GNUNET_SYSERR;
1849     }
1850     GNUNET_free (h->oOverlapRead);
1851   }
1852   if (h->oOverlapWrite)
1853   {
1854     if (!CloseHandle (h->oOverlapWrite->hEvent))
1855     {
1856       SetErrnoFromWinError (GetLastError ());
1857       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close");
1858       ret = GNUNET_SYSERR;
1859     }
1860     GNUNET_free (h->oOverlapWrite);
1861   }
1862 #else
1863   if (close (h->fd) != 0)
1864   {
1865     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close");
1866     ret = GNUNET_SYSERR;
1867   }
1868 #endif
1869   GNUNET_free (h);
1870   return ret;
1871 }
1872
1873 #ifdef WINDOWS
1874 /**
1875  * Get a GNUnet file handle from a W32 handle.
1876  *
1877  * @param handle native handle
1878  * @return GNUnet file handle corresponding to the W32 handle
1879  */
1880 struct GNUNET_DISK_FileHandle *
1881 GNUNET_DISK_get_handle_from_w32_handle (HANDLE osfh)
1882 {
1883   struct GNUNET_DISK_FileHandle *fh;
1884
1885   DWORD dwret;
1886   enum GNUNET_FILE_Type ftype;
1887
1888   dwret = GetFileType (osfh);
1889   switch (dwret)
1890   {
1891   case FILE_TYPE_DISK:
1892     ftype = GNUNET_DISK_HANLDE_TYPE_FILE;
1893     break;
1894   case FILE_TYPE_PIPE:
1895     ftype = GNUNET_DISK_HANLDE_TYPE_PIPE;
1896     break;
1897   default:
1898     return NULL;
1899   }
1900
1901   fh = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
1902
1903   fh->h = osfh;
1904   fh->type = ftype;
1905   if (ftype == GNUNET_DISK_HANLDE_TYPE_PIPE)
1906   {
1907     /**
1908      * Note that we can't make it overlapped if it isn't already.
1909      * (ReOpenFile() is only available in 2003/Vista).
1910      * The process that opened this file in the first place (usually a parent
1911      * process, if this is stdin/stdout/stderr) must make it overlapped,
1912      * otherwise we're screwed, as selecting on non-overlapped handle
1913      * will block.
1914      */
1915     fh->oOverlapRead = GNUNET_malloc (sizeof (OVERLAPPED));
1916     fh->oOverlapWrite = GNUNET_malloc (sizeof (OVERLAPPED));
1917     fh->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
1918     fh->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
1919   }
1920
1921   return fh;
1922 }
1923 #endif
1924
1925 /**
1926  * Get a handle from a native integer FD.
1927  *
1928  * @param fno native integer file descriptor
1929  * @return file handle corresponding to the descriptor
1930  */
1931 struct GNUNET_DISK_FileHandle *
1932 GNUNET_DISK_get_handle_from_int_fd (int fno)
1933 {
1934   struct GNUNET_DISK_FileHandle *fh;
1935
1936 #ifndef WINDOWS
1937   fh = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
1938
1939   fh->fd = fno;
1940 #else
1941   intptr_t osfh;
1942
1943   osfh = _get_osfhandle (fno);
1944   if (INVALID_HANDLE_VALUE == (HANDLE) osfh)
1945     return NULL;
1946
1947   fh = GNUNET_DISK_get_handle_from_w32_handle ((HANDLE) osfh);
1948 #endif
1949
1950   return fh;
1951 }
1952
1953
1954 /**
1955  * Get a handle from a native streaming FD.
1956  *
1957  * @param fd native streaming file descriptor
1958  * @return file handle corresponding to the descriptor
1959  */
1960 struct GNUNET_DISK_FileHandle *
1961 GNUNET_DISK_get_handle_from_native (FILE *fd)
1962 {
1963   int fno;
1964
1965   fno = fileno (fd);
1966   if (-1 == fno)
1967     return NULL;
1968
1969   return GNUNET_DISK_get_handle_from_int_fd (fno);
1970 }
1971
1972
1973 /**
1974  * Construct full path to a file inside of the private
1975  * directory used by GNUnet.  Also creates the corresponding
1976  * directory.  If the resulting name is supposed to be
1977  * a directory, end the last argument in '/' (or pass
1978  * DIR_SEPARATOR_STR as the last argument before NULL).
1979  *
1980  * @param cfg configuration to use (determines HOME)
1981  * @param serviceName name of the service
1982  * @param ... is NULL-terminated list of
1983  *                path components to append to the
1984  *                private directory name.
1985  * @return the constructed filename
1986  */
1987 char *
1988 GNUNET_DISK_get_home_filename (const struct GNUNET_CONFIGURATION_Handle *cfg,
1989                                const char *serviceName, ...)
1990 {
1991   const char *c;
1992   char *pfx;
1993   char *ret;
1994   va_list ap;
1995   unsigned int needed;
1996
1997   if (GNUNET_OK !=
1998       GNUNET_CONFIGURATION_get_value_filename (cfg, serviceName, "HOME", &pfx))
1999     return NULL;
2000   if (pfx == NULL)
2001   {
2002     LOG (GNUNET_ERROR_TYPE_WARNING,
2003          _("No `%s' specified for service `%s' in configuration.\n"), "HOME",
2004          serviceName);
2005     return NULL;
2006   }
2007   needed = strlen (pfx) + 2;
2008   if ((pfx[strlen (pfx) - 1] != '/') && (pfx[strlen (pfx) - 1] != '\\'))
2009     needed++;
2010   va_start (ap, serviceName);
2011   while (1)
2012   {
2013     c = va_arg (ap, const char *);
2014
2015     if (c == NULL)
2016       break;
2017     needed += strlen (c);
2018     if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
2019       needed++;
2020   }
2021   va_end (ap);
2022   ret = GNUNET_malloc (needed);
2023   strcpy (ret, pfx);
2024   GNUNET_free (pfx);
2025   va_start (ap, serviceName);
2026   while (1)
2027   {
2028     c = va_arg (ap, const char *);
2029
2030     if (c == NULL)
2031       break;
2032     if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
2033       strcat (ret, DIR_SEPARATOR_STR);
2034     strcat (ret, c);
2035   }
2036   va_end (ap);
2037   if ((ret[strlen (ret) - 1] != '/') && (ret[strlen (ret) - 1] != '\\'))
2038     (void) GNUNET_DISK_directory_create_for_file (ret);
2039   else
2040     (void) GNUNET_DISK_directory_create (ret);
2041   return ret;
2042 }
2043
2044
2045 /**
2046  * Handle for a memory-mapping operation.
2047  */
2048 struct GNUNET_DISK_MapHandle
2049 {
2050   /**
2051    * Address where the map is in memory.
2052    */
2053   void *addr;
2054
2055 #ifdef MINGW
2056   /**
2057    * Underlying OS handle.
2058    */
2059   HANDLE h;
2060 #else
2061   /**
2062    * Number of bytes mapped.
2063    */
2064   size_t len;
2065 #endif
2066 };
2067
2068
2069 #ifndef MAP_FAILED
2070 #define MAP_FAILED ((void *) -1)
2071 #endif
2072
2073 /**
2074  * Map a file into memory
2075  *
2076  * @param h open file handle
2077  * @param m handle to the new mapping
2078  * @param access access specification, GNUNET_DISK_MAP_TYPE_xxx
2079  * @param len size of the mapping
2080  * @return pointer to the mapped memory region, NULL on failure
2081  */
2082 void *
2083 GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h,
2084                       struct GNUNET_DISK_MapHandle **m,
2085                       enum GNUNET_DISK_MapType access, size_t len)
2086 {
2087   if (h == NULL)
2088   {
2089     errno = EINVAL;
2090     return NULL;
2091   }
2092
2093 #ifdef MINGW
2094   DWORD mapAccess, protect;
2095
2096   if ((access & GNUNET_DISK_MAP_TYPE_READ) &&
2097       (access & GNUNET_DISK_MAP_TYPE_WRITE))
2098   {
2099     protect = PAGE_READWRITE;
2100     mapAccess = FILE_MAP_ALL_ACCESS;
2101   }
2102   else if (access & GNUNET_DISK_MAP_TYPE_READ)
2103   {
2104     protect = PAGE_READONLY;
2105     mapAccess = FILE_MAP_READ;
2106   }
2107   else if (access & GNUNET_DISK_MAP_TYPE_WRITE)
2108   {
2109     protect = PAGE_READWRITE;
2110     mapAccess = FILE_MAP_WRITE;
2111   }
2112   else
2113   {
2114     GNUNET_break (0);
2115     return NULL;
2116   }
2117
2118   *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
2119   (*m)->h = CreateFileMapping (h->h, NULL, protect, 0, 0, NULL);
2120   if ((*m)->h == INVALID_HANDLE_VALUE)
2121   {
2122     SetErrnoFromWinError (GetLastError ());
2123     GNUNET_free (*m);
2124     return NULL;
2125   }
2126
2127   (*m)->addr = MapViewOfFile ((*m)->h, mapAccess, 0, 0, len);
2128   if (!(*m)->addr)
2129   {
2130     SetErrnoFromWinError (GetLastError ());
2131     CloseHandle ((*m)->h);
2132     GNUNET_free (*m);
2133   }
2134
2135   return (*m)->addr;
2136 #else
2137   int prot;
2138
2139   prot = 0;
2140   if (access & GNUNET_DISK_MAP_TYPE_READ)
2141     prot = PROT_READ;
2142   if (access & GNUNET_DISK_MAP_TYPE_WRITE)
2143     prot |= PROT_WRITE;
2144   *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
2145   (*m)->addr = mmap (NULL, len, prot, MAP_SHARED, h->fd, 0);
2146   GNUNET_assert (NULL != (*m)->addr);
2147   if (MAP_FAILED == (*m)->addr)
2148   {
2149     GNUNET_free (*m);
2150     return NULL;
2151   }
2152   (*m)->len = len;
2153   return (*m)->addr;
2154 #endif
2155 }
2156
2157 /**
2158  * Unmap a file
2159  * @param h mapping handle
2160  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2161  */
2162 int
2163 GNUNET_DISK_file_unmap (struct GNUNET_DISK_MapHandle *h)
2164 {
2165   int ret;
2166
2167   if (h == NULL)
2168   {
2169     errno = EINVAL;
2170     return GNUNET_SYSERR;
2171   }
2172
2173 #ifdef MINGW
2174   ret = UnmapViewOfFile (h->addr) ? GNUNET_OK : GNUNET_SYSERR;
2175   if (ret != GNUNET_OK)
2176     SetErrnoFromWinError (GetLastError ());
2177   if (!CloseHandle (h->h) && (ret == GNUNET_OK))
2178   {
2179     ret = GNUNET_SYSERR;
2180     SetErrnoFromWinError (GetLastError ());
2181   }
2182 #else
2183   ret = munmap (h->addr, h->len) != -1 ? GNUNET_OK : GNUNET_SYSERR;
2184 #endif
2185   GNUNET_free (h);
2186   return ret;
2187 }
2188
2189
2190 /**
2191  * Write file changes to disk
2192  * @param h handle to an open file
2193  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2194  */
2195 int
2196 GNUNET_DISK_file_sync (const struct GNUNET_DISK_FileHandle *h)
2197 {
2198   if (h == NULL)
2199   {
2200     errno = EINVAL;
2201     return GNUNET_SYSERR;
2202   }
2203
2204 #ifdef MINGW
2205   int ret;
2206
2207   ret = FlushFileBuffers (h->h) ? GNUNET_OK : GNUNET_SYSERR;
2208   if (ret != GNUNET_OK)
2209     SetErrnoFromWinError (GetLastError ());
2210   return ret;
2211 #elif defined(FREEBSD) || defined(OPENBSD) || defined(DARWIN)
2212   return fsync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
2213 #else
2214   return fdatasync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
2215 #endif
2216 }
2217
2218
2219 #if WINDOWS
2220 /* Copyright Bob Byrnes  <byrnes <at> curl.com>
2221    http://permalink.gmane.org/gmane.os.cygwin.patches/2121
2222 */
2223 /* Create a pipe, and return handles to the read and write ends,
2224    just like CreatePipe, but ensure that the write end permits
2225    FILE_READ_ATTRIBUTES access, on later versions of win32 where
2226    this is supported.  This access is needed by NtQueryInformationFile,
2227    which is used to implement select and nonblocking writes.
2228    Note that the return value is either NO_ERROR or GetLastError,
2229    unlike CreatePipe, which returns a bool for success or failure.  */
2230 static int
2231 create_selectable_pipe (PHANDLE read_pipe_ptr, PHANDLE write_pipe_ptr,
2232                         LPSECURITY_ATTRIBUTES sa_ptr, DWORD psize,
2233                         DWORD dwReadMode, DWORD dwWriteMode)
2234 {
2235   /* Default to error. */
2236   *read_pipe_ptr = *write_pipe_ptr = INVALID_HANDLE_VALUE;
2237
2238   HANDLE read_pipe;
2239   HANDLE write_pipe;
2240
2241   /* Ensure that there is enough pipe buffer space for atomic writes.  */
2242   if (psize < PIPE_BUF)
2243     psize = PIPE_BUF;
2244
2245   char pipename[MAX_PATH];
2246
2247   /* Retry CreateNamedPipe as long as the pipe name is in use.
2248    * Retrying will probably never be necessary, but we want
2249    * to be as robust as possible.  */
2250   while (1)
2251   {
2252     static volatile LONG pipe_unique_id;
2253
2254     snprintf (pipename, sizeof pipename, "\\\\.\\pipe\\gnunet-%d-%ld",
2255               getpid (), InterlockedIncrement ((LONG *) & pipe_unique_id));
2256     LOG (GNUNET_ERROR_TYPE_DEBUG, "CreateNamedPipe: name = %s, size = %lu\n",
2257          pipename, psize);
2258     /* Use CreateNamedPipe instead of CreatePipe, because the latter
2259      * returns a write handle that does not permit FILE_READ_ATTRIBUTES
2260      * access, on versions of win32 earlier than WinXP SP2.
2261      * CreatePipe also stupidly creates a full duplex pipe, which is
2262      * a waste, since only a single direction is actually used.
2263      * It's important to only allow a single instance, to ensure that
2264      * the pipe was not created earlier by some other process, even if
2265      * the pid has been reused.  */
2266     read_pipe = CreateNamedPipeA (pipename, PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE | dwReadMode, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1,   /* max instances */
2267                                   psize,        /* output buffer size */
2268                                   psize,        /* input buffer size */
2269                                   NMPWAIT_USE_DEFAULT_WAIT, sa_ptr);
2270
2271     if (read_pipe != INVALID_HANDLE_VALUE)
2272     {
2273       LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe read handle = %p\n", read_pipe);
2274       break;
2275     }
2276
2277     DWORD err = GetLastError ();
2278
2279     switch (err)
2280     {
2281     case ERROR_PIPE_BUSY:
2282       /* The pipe is already open with compatible parameters.
2283        * Pick a new name and retry.  */
2284       LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe busy, retrying\n");
2285       continue;
2286     case ERROR_ACCESS_DENIED:
2287       /* The pipe is already open with incompatible parameters.
2288        * Pick a new name and retry.  */
2289       LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe access denied, retrying\n");
2290       continue;
2291     case ERROR_CALL_NOT_IMPLEMENTED:
2292       /* We are on an older Win9x platform without named pipes.
2293        * Return an anonymous pipe as the best approximation.  */
2294       LOG (GNUNET_ERROR_TYPE_DEBUG,
2295            "CreateNamedPipe not implemented, resorting to "
2296            "CreatePipe: size = %lu\n", psize);
2297       if (CreatePipe (read_pipe_ptr, write_pipe_ptr, sa_ptr, psize))
2298       {
2299         LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe read handle = %p, write handle = %p\n",
2300              *read_pipe_ptr,
2301              *write_pipe_ptr);
2302         return GNUNET_OK;
2303       }
2304       err = GetLastError ();
2305       LOG (GNUNET_ERROR_TYPE_ERROR, "CreatePipe failed: %d\n", err);
2306       return err;
2307     default:
2308       LOG (GNUNET_ERROR_TYPE_ERROR, "CreateNamedPipe failed: %d\n", err);
2309       return err;
2310     }
2311     /* NOTREACHED */
2312   }
2313   LOG (GNUNET_ERROR_TYPE_DEBUG, "CreateFile: name = %s\n", pipename);
2314
2315   /* Open the named pipe for writing.
2316    * Be sure to permit FILE_READ_ATTRIBUTES access.  */
2317   write_pipe = CreateFileA (pipename, GENERIC_WRITE | FILE_READ_ATTRIBUTES, 0,  /* share mode */
2318                             sa_ptr, OPEN_EXISTING, dwWriteMode, /* flags and attributes */
2319                             0); /* handle to template file */
2320
2321   if (write_pipe == INVALID_HANDLE_VALUE)
2322   {
2323     /* Failure. */
2324     DWORD err = GetLastError ();
2325
2326     LOG (GNUNET_ERROR_TYPE_DEBUG, "CreateFile failed: %d\n", err);
2327     CloseHandle (read_pipe);
2328     return err;
2329   }
2330   LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe write handle = %p\n", write_pipe);
2331   /* Success. */
2332   *read_pipe_ptr = read_pipe;
2333   *write_pipe_ptr = write_pipe;
2334   return GNUNET_OK;
2335 }
2336 #endif
2337
2338
2339 /**
2340  * Creates an interprocess channel
2341  *
2342  * @param blocking_read creates an asynchronous pipe for reading if set to GNUNET_NO
2343  * @param blocking_write creates an asynchronous pipe for writing if set to GNUNET_NO
2344  * @param inherit_read inherit the parent processes stdin (only for windows)
2345  * @param inherit_write inherit the parent processes stdout (only for windows)
2346  * @return handle to the new pipe, NULL on error
2347  */
2348 struct GNUNET_DISK_PipeHandle *
2349 GNUNET_DISK_pipe (int blocking_read, int blocking_write, int inherit_read, int inherit_write)
2350 {
2351 #ifndef MINGW
2352   int fd[2];
2353   int ret;
2354   int eno;
2355
2356   ret = pipe (fd);
2357   if (ret == -1)
2358   {
2359     eno = errno;
2360     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
2361     errno = eno;
2362     return NULL;
2363   }
2364   return GNUNET_DISK_pipe_from_fd (blocking_read,
2365                                    blocking_write,
2366                                    fd);
2367 #else
2368   struct GNUNET_DISK_PipeHandle *p;
2369   BOOL ret;
2370   HANDLE tmp_handle;
2371   int save_errno;
2372
2373   p = GNUNET_malloc (sizeof (struct GNUNET_DISK_PipeHandle));
2374   p->fd[0] = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
2375   p->fd[1] = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
2376
2377   /* All pipes are overlapped. If you want them to block - just
2378    * call WriteFile() and ReadFile() with NULL overlapped pointer.
2379    * NOTE: calling with NULL overlapped pointer works only
2380    * for pipes, and doesn't seem to be a documented feature.
2381    * It will NOT work for files, because overlapped files need
2382    * to read offsets from the overlapped structure, regardless.
2383    * Pipes are not seekable, and need no offsets, which is
2384    * probably why it works for them.
2385    */
2386   ret =
2387       create_selectable_pipe (&p->fd[0]->h, &p->fd[1]->h, NULL, 0,
2388                               FILE_FLAG_OVERLAPPED,
2389                               FILE_FLAG_OVERLAPPED);
2390   if (!ret)
2391   {
2392     SetErrnoFromWinError (GetLastError ());
2393     save_errno = errno;
2394     GNUNET_free (p->fd[0]);
2395     GNUNET_free (p->fd[1]);
2396     GNUNET_free (p);
2397     errno = save_errno;
2398     return NULL;
2399   }
2400   if (!DuplicateHandle
2401       (GetCurrentProcess (), p->fd[0]->h, GetCurrentProcess (), &tmp_handle, 0,
2402        inherit_read == GNUNET_YES ? TRUE : FALSE, DUPLICATE_SAME_ACCESS))
2403   {
2404     SetErrnoFromWinError (GetLastError ());
2405     save_errno = errno;
2406     CloseHandle (p->fd[0]->h);
2407     CloseHandle (p->fd[1]->h);
2408     GNUNET_free (p->fd[0]);
2409     GNUNET_free (p->fd[1]);
2410     GNUNET_free (p);
2411     errno = save_errno;
2412     return NULL;
2413   }
2414   CloseHandle (p->fd[0]->h);
2415   p->fd[0]->h = tmp_handle;
2416
2417   if (!DuplicateHandle
2418       (GetCurrentProcess (), p->fd[1]->h, GetCurrentProcess (), &tmp_handle, 0,
2419        inherit_write == GNUNET_YES ? TRUE : FALSE, DUPLICATE_SAME_ACCESS))
2420   {
2421     SetErrnoFromWinError (GetLastError ());
2422     save_errno = errno;
2423     CloseHandle (p->fd[0]->h);
2424     CloseHandle (p->fd[1]->h);
2425     GNUNET_free (p->fd[0]);
2426     GNUNET_free (p->fd[1]);
2427     GNUNET_free (p);
2428     errno = save_errno;
2429     return NULL;
2430   }
2431   CloseHandle (p->fd[1]->h);
2432   p->fd[1]->h = tmp_handle;
2433
2434   p->fd[0]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2435   p->fd[1]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2436
2437   p->fd[0]->oOverlapRead = GNUNET_malloc (sizeof (OVERLAPPED));
2438   p->fd[0]->oOverlapWrite = GNUNET_malloc (sizeof (OVERLAPPED));
2439   p->fd[1]->oOverlapRead = GNUNET_malloc (sizeof (OVERLAPPED));
2440   p->fd[1]->oOverlapWrite = GNUNET_malloc (sizeof (OVERLAPPED));
2441
2442   p->fd[0]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2443   p->fd[0]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2444
2445   p->fd[1]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2446   p->fd[1]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2447
2448   return p;
2449 #endif
2450 }
2451
2452
2453 /**
2454  * Creates a pipe object from a couple of file descriptors.
2455  * Useful for wrapping existing pipe FDs.
2456  *
2457  * @param blocking_read creates an asynchronous pipe for reading if set to GNUNET_NO
2458  * @param blocking_write creates an asynchronous pipe for writing if set to GNUNET_NO
2459  * @param fd an array of two fd values. One of them may be -1 for read-only or write-only pipes
2460  *
2461  * @return handle to the new pipe, NULL on error
2462  */
2463 struct GNUNET_DISK_PipeHandle *
2464 GNUNET_DISK_pipe_from_fd (int blocking_read, int blocking_write, int fd[2])
2465 {
2466   struct GNUNET_DISK_PipeHandle *p;
2467
2468   p = GNUNET_malloc (sizeof (struct GNUNET_DISK_PipeHandle));
2469
2470 #ifndef MINGW
2471   int ret;
2472   int flags;
2473   int eno = 0; /* make gcc happy */
2474
2475   ret = 0;
2476   if (fd[0] >= 0)
2477   {
2478     p->fd[0] = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
2479     p->fd[0]->fd = fd[0];
2480     if (!blocking_read)
2481     {
2482       flags = fcntl (fd[0], F_GETFL);
2483       flags |= O_NONBLOCK;
2484       if (0 > fcntl (fd[0], F_SETFL, flags))
2485       {
2486         ret = -1;
2487         eno = errno;
2488       }
2489     }
2490     flags = fcntl (fd[0], F_GETFD);
2491     flags |= FD_CLOEXEC;
2492     if (0 > fcntl (fd[0], F_SETFD, flags))
2493     {
2494       ret = -1;
2495       eno = errno;
2496     }
2497   }
2498
2499   if (fd[1] >= 0)
2500   {
2501     p->fd[1] = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
2502     p->fd[1]->fd = fd[1];
2503     if (!blocking_write)
2504     {
2505       flags = fcntl (fd[1], F_GETFL);
2506       flags |= O_NONBLOCK;
2507       if (0 > fcntl (fd[1], F_SETFL, flags))
2508       {
2509         ret = -1;
2510         eno = errno;
2511       }
2512     }
2513     flags = fcntl (fd[1], F_GETFD);
2514     flags |= FD_CLOEXEC;
2515     if (0 > fcntl (fd[1], F_SETFD, flags))
2516     {
2517       ret = -1;
2518       eno = errno;
2519     }
2520   }
2521   if (ret == -1)
2522   {
2523     errno = eno;
2524     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fcntl");
2525     if (p->fd[0]->fd >= 0)
2526       GNUNET_break (0 == close (p->fd[0]->fd));
2527     if (p->fd[1]->fd >= 0)
2528       GNUNET_break (0 == close (p->fd[1]->fd));
2529     GNUNET_free_non_null (p->fd[0]);
2530     GNUNET_free_non_null (p->fd[1]);
2531     GNUNET_free (p);
2532     errno = eno;
2533     return NULL;
2534   }
2535 #else
2536   if (fd[0] >= 0)
2537   {
2538     p->fd[0] = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
2539     p->fd[0]->h = (HANDLE) _get_osfhandle (fd[0]);
2540     if (p->fd[0]->h != INVALID_HANDLE_VALUE)
2541     {
2542       p->fd[0]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2543       p->fd[0]->oOverlapRead = GNUNET_malloc (sizeof (OVERLAPPED));
2544       p->fd[0]->oOverlapWrite = GNUNET_malloc (sizeof (OVERLAPPED));
2545       p->fd[0]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2546       p->fd[0]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2547     }
2548     else
2549     {
2550       GNUNET_free (p->fd[0]);
2551       p->fd[0] = NULL;
2552     }
2553   }
2554   if (fd[1] >= 0)
2555   {
2556     p->fd[1] = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
2557     p->fd[1]->h = (HANDLE) _get_osfhandle (fd[1]);
2558     if (p->fd[1]->h != INVALID_HANDLE_VALUE)
2559     {
2560       p->fd[1]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2561       p->fd[1]->oOverlapRead = GNUNET_malloc (sizeof (OVERLAPPED));
2562       p->fd[1]->oOverlapWrite = GNUNET_malloc (sizeof (OVERLAPPED));
2563       p->fd[1]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2564       p->fd[1]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2565     }
2566     else
2567     {
2568       GNUNET_free (p->fd[1]);
2569       p->fd[1] = NULL;
2570     }
2571   }
2572
2573 #endif
2574   return p;
2575 }
2576
2577
2578 /**
2579  * Closes an interprocess channel
2580  *
2581  * @param p pipe to close
2582  * @param end which end of the pipe to close
2583  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2584  */
2585 int
2586 GNUNET_DISK_pipe_close_end (struct GNUNET_DISK_PipeHandle *p,
2587                             enum GNUNET_DISK_PipeEnd end)
2588 {
2589   int ret = GNUNET_OK;
2590
2591   if (end == GNUNET_DISK_PIPE_END_READ)
2592   {
2593     if (p->fd[0])
2594     {
2595       ret = GNUNET_DISK_file_close (p->fd[0]);
2596       p->fd[0] = NULL;
2597     }
2598   }
2599   else if (end == GNUNET_DISK_PIPE_END_WRITE)
2600   {
2601     if (p->fd[1])
2602     {
2603       ret = GNUNET_DISK_file_close (p->fd[1]);
2604       p->fd[1] = NULL;
2605     }
2606   }
2607
2608   return ret;
2609 }
2610
2611 /**
2612  * Detaches one of the ends from the pipe.
2613  * Detached end is a fully-functional FileHandle, it will
2614  * not be affected by anything you do with the pipe afterwards.
2615  * Each end of a pipe can only be detched from it once (i.e.
2616  * it is not duplicated).
2617  *
2618  * @param p pipe to detach an end from
2619  * @param end which end of the pipe to detach
2620  * @return Detached end on success, NULL on failure
2621  * (or if that end is not present or is closed).
2622  */
2623 struct GNUNET_DISK_FileHandle *
2624 GNUNET_DISK_pipe_detach_end (struct GNUNET_DISK_PipeHandle *p,
2625                              enum GNUNET_DISK_PipeEnd end)
2626 {
2627   struct GNUNET_DISK_FileHandle *ret = NULL;
2628
2629   if (end == GNUNET_DISK_PIPE_END_READ)
2630   {
2631     if (p->fd[0])
2632     {
2633       ret = p->fd[0];
2634       p->fd[0] = NULL;
2635     }
2636   }
2637   else if (end == GNUNET_DISK_PIPE_END_WRITE)
2638   {
2639     if (p->fd[1])
2640     {
2641       ret = p->fd[1];
2642       p->fd[1] = NULL;
2643     }
2644   }
2645
2646   return ret;
2647 }
2648
2649
2650 /**
2651  * Closes an interprocess channel
2652  *
2653  * @param p pipe to close
2654  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2655  */
2656 int
2657 GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p)
2658 {
2659   int ret = GNUNET_OK;
2660
2661   int read_end_close;
2662   int write_end_close;
2663   int read_end_close_errno;
2664   int write_end_close_errno;
2665
2666   read_end_close = GNUNET_DISK_pipe_close_end (p, GNUNET_DISK_PIPE_END_READ);
2667   read_end_close_errno = errno;
2668   write_end_close = GNUNET_DISK_pipe_close_end (p, GNUNET_DISK_PIPE_END_WRITE);
2669   write_end_close_errno = errno;
2670   GNUNET_free (p);
2671
2672   if (GNUNET_OK != read_end_close)
2673   {
2674     errno = read_end_close_errno;
2675     ret = read_end_close;
2676   }
2677   else if (GNUNET_OK != write_end_close)
2678   {
2679     errno = write_end_close_errno;
2680     ret = write_end_close;
2681   }
2682
2683   return ret;
2684 }
2685
2686
2687 /**
2688  * Get the handle to a particular pipe end
2689  *
2690  * @param p pipe
2691  * @param n end to access
2692  * @return handle for the respective end
2693  */
2694 const struct GNUNET_DISK_FileHandle *
2695 GNUNET_DISK_pipe_handle (const struct GNUNET_DISK_PipeHandle *p,
2696                          enum GNUNET_DISK_PipeEnd n)
2697 {
2698   switch (n)
2699   {
2700   case GNUNET_DISK_PIPE_END_READ:
2701   case GNUNET_DISK_PIPE_END_WRITE:
2702     return p->fd[n];
2703   default:
2704     GNUNET_break (0);
2705     return NULL;
2706   }
2707 }
2708
2709
2710 /**
2711  * Retrieve OS file handle
2712  * @internal
2713  * @param fh GNUnet file descriptor
2714  * @param dst destination buffer
2715  * @param dst_len length of dst
2716  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2717  */
2718 int
2719 GNUNET_DISK_internal_file_handle_ (const struct GNUNET_DISK_FileHandle *fh,
2720                                    void *dst, size_t dst_len)
2721 {
2722 #ifdef MINGW
2723   if (dst_len < sizeof (HANDLE))
2724     return GNUNET_SYSERR;
2725   *((HANDLE *) dst) = fh->h;
2726 #else
2727   if (dst_len < sizeof (int))
2728     return GNUNET_SYSERR;
2729   *((int *) dst) = fh->fd;
2730 #endif
2731
2732   return GNUNET_OK;
2733 }
2734
2735 /* end of disk.c */