2 This file is part of GNUnet.
3 Copyright (C) 2001--2013 GNUnet e.V.
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 3, or (at your
8 option) any later version.
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.
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., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
22 * @brief disk IO convenience methods
23 * @author Christian Grothoff
28 #include "gnunet_strings_lib.h"
29 #include "gnunet_disk_lib.h"
31 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
33 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
35 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
38 * Block size for IO for copying files.
40 #define COPY_BLK_SIZE 65536
42 #include <sys/types.h>
47 #include <sys/param.h>
50 #include <sys/mount.h>
52 #if HAVE_SYS_STATVFS_H
53 #include <sys/statvfs.h>
57 #define _IFMT 0170000 /* type of file */
58 #define _IFLNK 0120000 /* symbolic link */
59 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
64 * Handle used to manage a pipe.
66 struct GNUNET_DISK_PipeHandle
69 * File descriptors for the pipe.
70 * One or both of them could be NULL.
72 struct GNUNET_DISK_FileHandle *fd[2];
77 * Closure for the recursion to determine the file size
80 struct GetFileSizeData
83 * Set to the total file size.
88 * GNUNET_YES if symbolic links should be included.
90 int include_sym_links;
93 * GNUNET_YES if mode is file-only (return total == -1 for directories).
101 * Translate GNUnet-internal permission bitmap to UNIX file
102 * access permission bitmap.
104 * @param perm file permissions, GNUnet style
105 * @return file permissions, UNIX style
108 translate_unix_perms (enum GNUNET_DISK_AccessPermissions perm)
113 if (perm & GNUNET_DISK_PERM_USER_READ)
115 if (perm & GNUNET_DISK_PERM_USER_WRITE)
117 if (perm & GNUNET_DISK_PERM_USER_EXEC)
119 if (perm & GNUNET_DISK_PERM_GROUP_READ)
121 if (perm & GNUNET_DISK_PERM_GROUP_WRITE)
123 if (perm & GNUNET_DISK_PERM_GROUP_EXEC)
125 if (perm & GNUNET_DISK_PERM_OTHER_READ)
127 if (perm & GNUNET_DISK_PERM_OTHER_WRITE)
129 if (perm & GNUNET_DISK_PERM_OTHER_EXEC)
138 * Iterate over all files in the given directory and
139 * accumulate their size.
141 * @param cls closure of type `struct GetFileSizeData`
142 * @param fn current filename we are looking at
143 * @return #GNUNET_SYSERR on serious errors, otherwise #GNUNET_OK
146 getSizeRec (void *cls, const char *fn)
148 struct GetFileSizeData *gfsd = cls;
150 #if defined (HAVE_STAT64) && !(defined (_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64)
153 if (0 != STAT64 (fn, &buf))
155 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_DEBUG, "stat64", fn);
156 return GNUNET_SYSERR;
161 if (0 != STAT (fn, &buf))
163 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_DEBUG, "stat", fn);
164 return GNUNET_SYSERR;
167 if ((S_ISDIR (buf.st_mode)) && (gfsd->single_file_mode == GNUNET_YES))
170 return GNUNET_SYSERR;
172 if ((!S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES))
173 gfsd->total += buf.st_size;
174 if ((S_ISDIR (buf.st_mode)) && (0 == ACCESS (fn, X_OK)) &&
175 ((!S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES)))
177 if (GNUNET_SYSERR == GNUNET_DISK_directory_scan (fn, &getSizeRec, gfsd))
178 return GNUNET_SYSERR;
185 * Checks whether a handle is invalid
187 * @param h handle to check
188 * @return #GNUNET_YES if invalid, #GNUNET_NO if valid
191 GNUNET_DISK_handle_invalid (const struct GNUNET_DISK_FileHandle *h)
194 return ((!h) || (h->h == INVALID_HANDLE_VALUE)) ? GNUNET_YES : GNUNET_NO;
196 return ((!h) || (h->fd == -1)) ? GNUNET_YES : GNUNET_NO;
201 * Get the size of an open file.
203 * @param fh open file handle
204 * @param size where to write size of the file
205 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
208 GNUNET_DISK_file_handle_size (struct GNUNET_DISK_FileHandle *fh,
214 b = GetFileSizeEx (fh->h, &li);
217 SetErrnoFromWinError (GetLastError ());
218 return GNUNET_SYSERR;
220 *size = (off_t) li.QuadPart;
224 if (0 != FSTAT (fh->fd, &sbuf))
225 return GNUNET_SYSERR;
226 *size = sbuf.st_size;
233 * Move the read/write pointer in a file
235 * @param h handle of an open file
236 * @param offset position to move to
237 * @param whence specification to which position the offset parameter relates to
238 * @return the new position on success, #GNUNET_SYSERR otherwise
241 GNUNET_DISK_file_seek (const struct GNUNET_DISK_FileHandle * h, off_t offset,
242 enum GNUNET_DISK_Seek whence)
247 return GNUNET_SYSERR;
252 LARGE_INTEGER new_pos;
255 static DWORD t[] = { FILE_BEGIN, FILE_CURRENT, FILE_END };
256 li.QuadPart = offset;
258 b = SetFilePointerEx (h->h, li, &new_pos, t[whence]);
261 SetErrnoFromWinError (GetLastError ());
262 return GNUNET_SYSERR;
264 return (off_t) new_pos.QuadPart;
266 static int t[] = { SEEK_SET, SEEK_CUR, SEEK_END };
268 return lseek (h->fd, offset, t[whence]);
274 * Get the size of the file (or directory) of the given file (in
277 * @param filename name of the file or directory
278 * @param size set to the size of the file (or,
279 * in the case of directories, the sum
280 * of all sizes of files in the directory)
281 * @param include_symbolic_links should symbolic links be
283 * @param single_file_mode #GNUNET_YES to only get size of one file
284 * and return #GNUNET_SYSERR for directories.
285 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
288 GNUNET_DISK_file_size (const char *filename,
290 int include_symbolic_links,
291 int single_file_mode)
293 struct GetFileSizeData gfsd;
296 GNUNET_assert (size != NULL);
298 gfsd.include_sym_links = include_symbolic_links;
299 gfsd.single_file_mode = single_file_mode;
300 ret = getSizeRec (&gfsd, filename);
307 * Obtain some unique identifiers for the given file
308 * that can be used to identify it in the local system.
309 * This function is used between GNUnet processes to
310 * quickly check if two files with the same absolute path
311 * are actually identical. The two processes represent
312 * the same peer but may communicate over the network
313 * (and the file may be on an NFS volume). This function
314 * may not be supported on all operating systems.
316 * @param filename name of the file
317 * @param dev set to the device ID
318 * @param ino set to the inode ID
319 * @return #GNUNET_OK on success
322 GNUNET_DISK_file_get_identifiers (const char *filename, uint64_t * dev,
327 // FIXME NILS: test this
328 struct GNUNET_DISK_FileHandle *fh;
329 BY_HANDLE_FILE_INFORMATION info;
332 fh = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ, 0);
334 return GNUNET_SYSERR;
335 succ = GetFileInformationByHandle (fh->h, &info);
336 GNUNET_DISK_file_close (fh);
339 return GNUNET_SYSERR;
341 *dev = info.dwVolumeSerialNumber;
342 *ino = ((((uint64_t) info.nFileIndexHigh) << (sizeof (DWORD) * 8)) | info.nFileIndexLow);
349 if (0 != stat (filename, &sbuf))
351 return GNUNET_SYSERR;
353 *ino = (uint64_t) sbuf.st_ino;
362 if (0 != statvfs (filename, &fbuf))
364 return GNUNET_SYSERR;
366 *dev = (uint64_t) fbuf.f_fsid;
372 if (0 != statfs (filename, &fbuf))
374 return GNUNET_SYSERR;
376 *dev = ((uint64_t) fbuf.f_fsid.val[0]) << 32 ||
377 ((uint64_t) fbuf.f_fsid.val[1]);
382 #endif /* !WINDOWS */
388 * Create the name for a temporary file or directory from a template.
390 * @param t template (without XXXXX or "/tmp/")
391 * @return name ready for passing to 'mktemp' or 'mkdtemp', NULL on error
394 mktemp_name (const char *t)
400 if ((t[0] != '/') && (t[0] != '\\')
402 && !(isalpha ((int) t[0]) && (t[0] != '\0') && (t[1] == ':'))
406 /* FIXME: This uses system codepage on W32, not UTF-8 */
407 tmpdir = getenv ("TMPDIR");
409 tmpdir = getenv ("TMP");
411 tmpdir = getenv ("TEMP");
414 GNUNET_asprintf (&tmpl, "%s/%s%s", tmpdir, t, "XXXXXX");
418 GNUNET_asprintf (&tmpl, "%s%s", t, "XXXXXX");
421 fn = (char *) GNUNET_malloc (MAX_PATH + 1);
422 if (ERROR_SUCCESS != plibc_conv_to_win_path (tmpl, fn))
445 tfn = GNUNET_strdup (fn);
446 random_fn = _mktemp (tfn);
447 if (NULL == random_fn)
452 /* FIXME: assume fn to be UTF-8-encoded and do the right thing */
453 if (0 == CreateDirectoryA (tfn, NULL))
455 DWORD error = GetLastError ();
457 if (ERROR_ALREADY_EXISTS == error)
468 * Update POSIX permissions mask of a file on disk. If both argumets
469 * are #GNUNET_NO, the file is made world-read-write-executable (777).
470 * Does nothing on W32.
472 * @param fn name of the file to update
473 * @param require_uid_match #GNUNET_YES means 700
474 * @param require_gid_match #GNUNET_YES means 770 unless @a require_uid_match is set
477 GNUNET_DISK_fix_permissions (const char *fn,
478 int require_uid_match,
479 int require_gid_match)
487 * Update POSIX permissions mask of a file on disk. If both argumets
488 * are #GNUNET_NO, the file is made world-read-write-executable (777).
490 * @param fn name of the file to update
491 * @param require_uid_match #GNUNET_YES means 700
492 * @param require_gid_match #GNUNET_YES means 770 unless @a require_uid_match is set
495 GNUNET_DISK_fix_permissions (const char *fn,
496 int require_uid_match,
497 int require_gid_match)
501 if (GNUNET_YES == require_uid_match)
502 mode = S_IRUSR | S_IWUSR | S_IXUSR;
503 else if (GNUNET_YES == require_gid_match)
504 mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP;
506 mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH;
507 if (0 != chmod (fn, mode))
508 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
516 * Create an (empty) temporary directory on disk. If the given name is not
517 * an absolute path, the current 'TMPDIR' will be prepended. In any case,
518 * 6 random characters will be appended to the name to create a unique
521 * @param t component to use for the name;
522 * does NOT contain "XXXXXX" or "/tmp/".
523 * @return NULL on error, otherwise name of fresh
524 * file on disk in directory for temporary files
527 GNUNET_DISK_mkdtemp (const char *t)
532 omask = umask (S_IWGRP | S_IWOTH | S_IRGRP | S_IROTH);
533 fn = mktemp_name (t);
534 if (fn != mkdtemp (fn))
536 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "mkdtemp", fn);
547 * Move a file out of the way (create a backup) by
548 * renaming it to "orig.NUM~" where NUM is the smallest
549 * number that is not used yet.
551 * @param fil name of the file to back up
554 GNUNET_DISK_file_backup (const char *fil)
560 slen = strlen (fil) + 20;
561 target = GNUNET_malloc (slen);
565 GNUNET_snprintf (target, slen,
569 } while (0 == access (target, F_OK));
570 if (0 != rename (fil, target))
571 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
574 GNUNET_free (target);
579 * Create an (empty) temporary file on disk. If the given name is not
580 * an absolute path, the current 'TMPDIR' will be prepended. In any case,
581 * 6 random characters will be appended to the name to create a unique
584 * @param t component to use for the name;
585 * does NOT contain "XXXXXX" or "/tmp/".
586 * @return NULL on error, otherwise name of fresh
587 * file on disk in directory for temporary files
590 GNUNET_DISK_mktemp (const char *t)
596 omask = umask (S_IWGRP | S_IWOTH | S_IRGRP | S_IROTH);
597 fn = mktemp_name (t);
598 if (-1 == (fd = mkstemp (fn)))
600 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "mkstemp", fn);
607 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "close", fn);
613 * Test if @a fil is a directory and listable. Optionally, also check if the
614 * directory is readable. Will not print an error message if the directory does
615 * not exist. Will log errors if #GNUNET_SYSERR is returned (i.e., a file exists
616 * with the same name).
618 * @param fil filename to test
619 * @param is_readable #GNUNET_YES to additionally check if @a fil is readable;
620 * #GNUNET_NO to disable this check
621 * @return #GNUNET_YES if yes, #GNUNET_NO if not; #GNUNET_SYSERR if it
622 * does not exist or stat'ed
625 GNUNET_DISK_directory_test (const char *fil, int is_readable)
627 struct stat filestat;
630 ret = STAT (fil, &filestat);
634 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", fil);
635 return GNUNET_SYSERR;
637 if (!S_ISDIR (filestat.st_mode))
639 LOG (GNUNET_ERROR_TYPE_DEBUG,
640 "A file already exits with the same name %s\n", fil);
643 if (GNUNET_YES == is_readable)
644 ret = ACCESS (fil, R_OK | X_OK);
646 ret = ACCESS (fil, X_OK);
649 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", fil);
657 * Check that fil corresponds to a filename
658 * (of a file that exists and that is not a directory).
660 * @param fil filename to check
661 * @return #GNUNET_YES if yes, #GNUNET_NO if not a file, #GNUNET_SYSERR if something
662 * else (will print an error message in that case, too).
665 GNUNET_DISK_file_test (const char *fil)
667 struct stat filestat;
671 rdir = GNUNET_STRINGS_filename_expand (fil);
673 return GNUNET_SYSERR;
675 ret = STAT (rdir, &filestat);
680 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", rdir);
682 return GNUNET_SYSERR;
687 if (!S_ISREG (filestat.st_mode))
692 if (ACCESS (rdir, F_OK) < 0)
694 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", rdir);
696 return GNUNET_SYSERR;
704 * Implementation of "mkdir -p"
706 * @param dir the directory to create
707 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
710 GNUNET_DISK_directory_create (const char *dir)
718 rdir = GNUNET_STRINGS_filename_expand (dir);
720 return GNUNET_SYSERR;
724 pos = 1; /* skip heading '/' */
726 /* Local or Network path? */
727 if (strncmp (rdir, "\\\\", 2) == 0)
732 if (rdir[pos] == '\\')
742 pos = 3; /* strlen("C:\\") */
745 /* Check which low level directories already exist */
747 rdir[len] = DIR_SEPARATOR;
750 if (DIR_SEPARATOR == rdir[pos2])
753 ret = GNUNET_DISK_directory_test (rdir, GNUNET_NO);
754 if (GNUNET_NO == ret)
757 return GNUNET_SYSERR;
759 rdir[pos2] = DIR_SEPARATOR;
760 if (GNUNET_YES == ret)
771 /* Start creating directories */
774 if ((rdir[pos] == DIR_SEPARATOR) || (pos == len))
777 ret = GNUNET_DISK_directory_test (rdir, GNUNET_NO);
778 if (GNUNET_NO == ret)
781 return GNUNET_SYSERR;
783 if (GNUNET_SYSERR == ret)
786 ret = mkdir (rdir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); /* 755 */
788 wchar_t wrdir[MAX_PATH + 1];
789 if (ERROR_SUCCESS == plibc_conv_to_win_pathwconv(rdir, wrdir))
790 ret = !CreateDirectoryW (wrdir, NULL);
794 if ((ret != 0) && (errno != EEXIST))
796 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "mkdir", rdir);
798 return GNUNET_SYSERR;
801 rdir[pos] = DIR_SEPARATOR;
811 * Create the directory structure for storing a file.
813 * @param filename name of a file in the directory
814 * @returns #GNUNET_OK on success,
815 * #GNUNET_SYSERR on failure,
816 * #GNUNET_NO if the directory
817 * exists but is not writeable for us
820 GNUNET_DISK_directory_create_for_file (const char *filename)
827 rdir = GNUNET_STRINGS_filename_expand (filename);
831 return GNUNET_SYSERR;
834 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
837 /* The empty path is invalid and in this case refers to / */
841 rdir = GNUNET_strdup ("/");
843 ret = GNUNET_DISK_directory_create (rdir);
844 if ((GNUNET_OK == ret) && (0 != ACCESS (rdir, W_OK)))
854 * Read the contents of a binary file into a buffer.
856 * @param h handle to an open file
857 * @param result the buffer to write the result to
858 * @param len the maximum number of bytes to read
859 * @return the number of bytes read on success, #GNUNET_SYSERR on failure
862 GNUNET_DISK_file_read (const struct GNUNET_DISK_FileHandle *h,
869 return GNUNET_SYSERR;
875 if (h->type == GNUNET_DISK_HANLDE_TYPE_FILE)
877 if (!ReadFile (h->h, result, len, &bytes_read, NULL))
879 SetErrnoFromWinError (GetLastError ());
880 return GNUNET_SYSERR;
883 else if (h->type == GNUNET_DISK_HANLDE_TYPE_PIPE)
885 if (!ReadFile (h->h, result, len, &bytes_read, h->oOverlapRead))
887 if (GetLastError () != ERROR_IO_PENDING)
889 LOG (GNUNET_ERROR_TYPE_DEBUG,
890 "Error reading from pipe: %u\n",
892 SetErrnoFromWinError (GetLastError ());
893 return GNUNET_SYSERR;
895 LOG (GNUNET_ERROR_TYPE_DEBUG, "Will get overlapped result\n");
896 GetOverlappedResult (h->h, h->oOverlapRead, &bytes_read, TRUE);
898 LOG (GNUNET_ERROR_TYPE_DEBUG, "Read %u bytes from pipe\n", bytes_read);
906 return read (h->fd, result, len);
912 * Read the contents of a binary file into a buffer.
913 * Guarantees not to block (returns GNUNET_SYSERR and sets errno to EAGAIN
914 * when no data can be read).
916 * @param h handle to an open file
917 * @param result the buffer to write the result to
918 * @param len the maximum number of bytes to read
919 * @return the number of bytes read on success, #GNUNET_SYSERR on failure
922 GNUNET_DISK_file_read_non_blocking (const struct GNUNET_DISK_FileHandle *h,
929 return GNUNET_SYSERR;
935 if (h->type == GNUNET_DISK_HANLDE_TYPE_FILE)
937 if (!ReadFile (h->h, result, len, &bytes_read, NULL))
939 SetErrnoFromWinError (GetLastError ());
940 return GNUNET_SYSERR;
943 else if (h->type == GNUNET_DISK_HANLDE_TYPE_PIPE)
945 if (!ReadFile (h->h, result, len, &bytes_read, h->oOverlapRead))
947 if (GetLastError () != ERROR_IO_PENDING)
949 LOG (GNUNET_ERROR_TYPE_DEBUG, "Error reading from pipe: %u\n", GetLastError ());
950 SetErrnoFromWinError (GetLastError ());
951 return GNUNET_SYSERR;
955 LOG (GNUNET_ERROR_TYPE_DEBUG,
956 "ReadFile() queued a read, cancelling\n");
959 return GNUNET_SYSERR;
962 LOG (GNUNET_ERROR_TYPE_DEBUG,
975 /* set to non-blocking, read, then set back */
976 flags = fcntl (h->fd, F_GETFL);
977 if (0 == (flags & O_NONBLOCK))
978 (void) fcntl (h->fd, F_SETFL, flags | O_NONBLOCK);
979 ret = read (h->fd, result, len);
980 if (0 == (flags & O_NONBLOCK))
983 (void) fcntl (h->fd, F_SETFL, flags);
992 * Read the contents of a binary file into a buffer.
994 * @param fn file name
995 * @param result the buffer to write the result to
996 * @param len the maximum number of bytes to read
997 * @return number of bytes read, #GNUNET_SYSERR on failure
1000 GNUNET_DISK_fn_read (const char *fn,
1004 struct GNUNET_DISK_FileHandle *fh;
1008 fh = GNUNET_DISK_file_open (fn,
1009 GNUNET_DISK_OPEN_READ,
1010 GNUNET_DISK_PERM_NONE);
1012 return GNUNET_SYSERR;
1013 ret = GNUNET_DISK_file_read (fh, result, len);
1015 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
1022 * Write a buffer to a file.
1024 * @param h handle to open file
1025 * @param buffer the data to write
1026 * @param n number of bytes to write
1027 * @return number of bytes written on success, #GNUNET_SYSERR on error
1030 GNUNET_DISK_file_write (const struct GNUNET_DISK_FileHandle * h,
1031 const void *buffer, size_t n)
1036 return GNUNET_SYSERR;
1040 DWORD bytes_written;
1042 if (h->type == GNUNET_DISK_HANLDE_TYPE_FILE)
1044 if (!WriteFile (h->h, buffer, n, &bytes_written, NULL))
1046 SetErrnoFromWinError (GetLastError ());
1047 return GNUNET_SYSERR;
1050 else if (h->type == GNUNET_DISK_HANLDE_TYPE_PIPE)
1052 LOG (GNUNET_ERROR_TYPE_DEBUG, "It is a pipe trying to write %u bytes\n", n);
1053 if (!WriteFile (h->h, buffer, n, &bytes_written, h->oOverlapWrite))
1055 if (GetLastError () != ERROR_IO_PENDING)
1057 SetErrnoFromWinError (GetLastError ());
1058 LOG (GNUNET_ERROR_TYPE_DEBUG, "Error writing to pipe: %u\n",
1060 return GNUNET_SYSERR;
1062 LOG (GNUNET_ERROR_TYPE_DEBUG, "Will get overlapped result\n");
1063 if (!GetOverlappedResult (h->h, h->oOverlapWrite, &bytes_written, TRUE))
1065 SetErrnoFromWinError (GetLastError ());
1066 LOG (GNUNET_ERROR_TYPE_DEBUG,
1067 "Error getting overlapped result while writing to pipe: %u\n",
1069 return GNUNET_SYSERR;
1075 if (!GetOverlappedResult (h->h, h->oOverlapWrite, &ovr, TRUE))
1077 LOG (GNUNET_ERROR_TYPE_DEBUG,
1078 "Error getting control overlapped result while writing to pipe: %u\n",
1083 LOG (GNUNET_ERROR_TYPE_DEBUG,
1084 "Wrote %u bytes (ovr says %u), picking the greatest\n",
1085 bytes_written, ovr);
1088 if (bytes_written == 0)
1092 LOG (GNUNET_ERROR_TYPE_DEBUG, "Wrote %u bytes, returning -1 with EAGAIN\n", bytes_written);
1094 return GNUNET_SYSERR;
1097 LOG (GNUNET_ERROR_TYPE_DEBUG, "Wrote %u bytes\n", bytes_written);
1103 return bytes_written;
1105 return write (h->fd, buffer, n);
1111 * Write a buffer to a file, blocking, if necessary.
1113 * @param h handle to open file
1114 * @param buffer the data to write
1115 * @param n number of bytes to write
1116 * @return number of bytes written on success, #GNUNET_SYSERR on error
1119 GNUNET_DISK_file_write_blocking (const struct GNUNET_DISK_FileHandle * h,
1126 return GNUNET_SYSERR;
1130 DWORD bytes_written;
1131 /* We do a non-overlapped write, which is as blocking as it gets */
1132 LOG (GNUNET_ERROR_TYPE_DEBUG, "Writing %u bytes\n", n);
1133 if (!WriteFile (h->h, buffer, n, &bytes_written, NULL))
1135 SetErrnoFromWinError (GetLastError ());
1136 LOG (GNUNET_ERROR_TYPE_DEBUG, "Error writing to pipe: %u\n",
1138 return GNUNET_SYSERR;
1140 if (bytes_written == 0 && n > 0)
1142 LOG (GNUNET_ERROR_TYPE_DEBUG, "Waiting for pipe to clean\n");
1143 WaitForSingleObject (h->h, INFINITE);
1144 if (!WriteFile (h->h, buffer, n, &bytes_written, NULL))
1146 SetErrnoFromWinError (GetLastError ());
1147 LOG (GNUNET_ERROR_TYPE_DEBUG, "Error writing to pipe: %u\n",
1149 return GNUNET_SYSERR;
1152 LOG (GNUNET_ERROR_TYPE_DEBUG,
1155 return bytes_written;
1160 /* set to blocking, write, then set back */
1161 flags = fcntl (h->fd, F_GETFL);
1162 if (0 != (flags & O_NONBLOCK))
1163 (void) fcntl (h->fd, F_SETFL, flags - O_NONBLOCK);
1164 ret = write (h->fd, buffer, n);
1165 if (0 == (flags & O_NONBLOCK))
1166 (void) fcntl (h->fd, F_SETFL, flags);
1173 * Write a buffer to a file. If the file is longer than the
1174 * number of bytes that will be written, it will be truncated.
1176 * @param fn file name
1177 * @param buffer the data to write
1178 * @param n number of bytes to write
1179 * @param mode file permissions
1180 * @return number of bytes written on success, #GNUNET_SYSERR on error
1183 GNUNET_DISK_fn_write (const char *fn,
1186 enum GNUNET_DISK_AccessPermissions mode)
1188 struct GNUNET_DISK_FileHandle *fh;
1191 fh = GNUNET_DISK_file_open (fn,
1192 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE
1193 | GNUNET_DISK_OPEN_CREATE, mode);
1195 return GNUNET_SYSERR;
1196 ret = GNUNET_DISK_file_write (fh, buffer, n);
1197 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
1203 * Scan a directory for files.
1205 * @param dir_name the name of the directory
1206 * @param callback the method to call for each file,
1207 * can be NULL, in that case, we only count
1208 * @param callback_cls closure for @a callback
1209 * @return the number of files found, #GNUNET_SYSERR on error or
1210 * ieration aborted by callback returning #GNUNET_SYSERR
1213 GNUNET_DISK_directory_scan (const char *dir_name,
1214 GNUNET_FileNameCallback callback,
1218 struct dirent *finfo;
1224 unsigned int name_len;
1225 unsigned int n_size;
1227 GNUNET_assert (NULL != dir_name);
1228 dname = GNUNET_STRINGS_filename_expand (dir_name);
1230 return GNUNET_SYSERR;
1231 while ((strlen (dname) > 0) && (dname[strlen (dname) - 1] == DIR_SEPARATOR))
1232 dname[strlen (dname) - 1] = '\0';
1233 if (0 != STAT (dname, &istat))
1235 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", dname);
1236 GNUNET_free (dname);
1237 return GNUNET_SYSERR;
1239 if (! S_ISDIR (istat.st_mode))
1241 LOG (GNUNET_ERROR_TYPE_WARNING,
1242 _("Expected `%s' to be a directory!\n"),
1244 GNUNET_free (dname);
1245 return GNUNET_SYSERR;
1248 dinfo = OPENDIR (dname);
1249 if ((errno == EACCES) || (NULL == dinfo))
1251 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "opendir", dname);
1254 GNUNET_free (dname);
1255 return GNUNET_SYSERR;
1258 n_size = strlen (dname) + name_len + 2;
1259 name = GNUNET_malloc (n_size);
1260 while (NULL != (finfo = READDIR (dinfo)))
1262 if ((0 == strcmp (finfo->d_name, ".")) ||
1263 (0 == strcmp (finfo->d_name, "..")))
1265 if (NULL != callback)
1267 if (name_len < strlen (finfo->d_name))
1270 name_len = strlen (finfo->d_name);
1271 n_size = strlen (dname) + name_len + 2;
1272 name = GNUNET_malloc (n_size);
1274 /* dname can end in "/" only if dname == "/";
1275 * if dname does not end in "/", we need to add
1276 * a "/" (otherwise, we must not!) */
1277 GNUNET_snprintf (name, n_size, "%s%s%s", dname,
1278 (strcmp (dname, DIR_SEPARATOR_STR) ==
1279 0) ? "" : DIR_SEPARATOR_STR, finfo->d_name);
1280 ret = callback (callback_cls, name);
1281 if (GNUNET_OK != ret)
1285 GNUNET_free (dname);
1286 if (GNUNET_NO == ret)
1288 return GNUNET_SYSERR;
1295 GNUNET_free (dname);
1301 * Function that removes the given directory by calling
1302 * "GNUNET_DISK_directory_remove".
1304 * @param unused not used
1305 * @param fn directory to remove
1306 * @return #GNUNET_OK
1309 remove_helper (void *unused, const char *fn)
1311 (void) GNUNET_DISK_directory_remove (fn);
1317 * Remove all files in a directory (rm -rf). Call with
1320 * @param filename the file to remove
1321 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1324 GNUNET_DISK_directory_remove (const char *filename)
1328 if (NULL == filename)
1331 return GNUNET_SYSERR;
1333 if (0 != LSTAT (filename, &istat))
1334 return GNUNET_NO; /* file may not exist... */
1335 (void) CHMOD (filename, S_IWUSR | S_IRUSR | S_IXUSR);
1336 if (UNLINK (filename) == 0)
1338 if ((errno != EISDIR) &&
1339 /* EISDIR is not sufficient in all cases, e.g.
1340 * sticky /tmp directory may result in EPERM on BSD.
1341 * So we also explicitly check "isDirectory" */
1342 (GNUNET_YES != GNUNET_DISK_directory_test (filename, GNUNET_YES)))
1344 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "rmdir", filename);
1345 return GNUNET_SYSERR;
1347 if (GNUNET_SYSERR ==
1348 GNUNET_DISK_directory_scan (filename, &remove_helper, NULL))
1349 return GNUNET_SYSERR;
1350 if (0 != RMDIR (filename))
1352 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "rmdir", filename);
1353 return GNUNET_SYSERR;
1362 * @param src file to copy
1363 * @param dst destination file name
1364 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1367 GNUNET_DISK_file_copy (const char *src,
1374 struct GNUNET_DISK_FileHandle *in;
1375 struct GNUNET_DISK_FileHandle *out;
1377 if (GNUNET_OK != GNUNET_DISK_file_size (src, &size, GNUNET_YES, GNUNET_YES))
1378 return GNUNET_SYSERR;
1380 in = GNUNET_DISK_file_open (src, GNUNET_DISK_OPEN_READ,
1381 GNUNET_DISK_PERM_NONE);
1383 return GNUNET_SYSERR;
1385 GNUNET_DISK_file_open (dst,
1386 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE |
1387 GNUNET_DISK_OPEN_FAILIFEXISTS,
1388 GNUNET_DISK_PERM_USER_READ |
1389 GNUNET_DISK_PERM_USER_WRITE |
1390 GNUNET_DISK_PERM_GROUP_READ |
1391 GNUNET_DISK_PERM_GROUP_WRITE);
1394 GNUNET_DISK_file_close (in);
1395 return GNUNET_SYSERR;
1397 buf = GNUNET_malloc (COPY_BLK_SIZE);
1400 len = COPY_BLK_SIZE;
1401 if (len > size - pos)
1403 if (len != GNUNET_DISK_file_read (in, buf, len))
1405 if (len != GNUNET_DISK_file_write (out, buf, len))
1410 GNUNET_DISK_file_close (in);
1411 GNUNET_DISK_file_close (out);
1415 GNUNET_DISK_file_close (in);
1416 GNUNET_DISK_file_close (out);
1417 return GNUNET_SYSERR;
1422 * @brief Removes special characters as ':' from a filename.
1423 * @param fn the filename to canonicalize
1426 GNUNET_DISK_filename_canonicalize (char *fn)
1436 if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' || c == '"' ||
1437 c == '<' || c == '>' || c == '|')
1449 * @brief Change owner of a file
1451 * @param filename name of file to change the owner of
1452 * @param user name of the new owner
1453 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1456 GNUNET_DISK_file_change_owner (const char *filename, const char *user)
1461 pws = getpwnam (user);
1464 LOG (GNUNET_ERROR_TYPE_ERROR,
1465 _("Cannot obtain information about user `%s': %s\n"), user,
1467 return GNUNET_SYSERR;
1469 if (0 != chown (filename, pws->pw_uid, pws->pw_gid))
1470 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "chown", filename);
1477 * Lock a part of a file
1478 * @param fh file handle
1479 * @param lock_start absolute position from where to lock
1480 * @param lock_end absolute position until where to lock
1481 * @param excl GNUNET_YES for an exclusive lock
1482 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1485 GNUNET_DISK_file_lock (struct GNUNET_DISK_FileHandle *fh, off_t lock_start,
1486 off_t lock_end, int excl)
1491 return GNUNET_SYSERR;
1497 memset (&fl, 0, sizeof (struct flock));
1498 fl.l_type = excl ? F_WRLCK : F_RDLCK;
1499 fl.l_whence = SEEK_SET;
1500 fl.l_start = lock_start;
1501 fl.l_len = lock_end;
1503 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1506 off_t diff = lock_end - lock_start;
1507 DWORD diff_low, diff_high;
1508 diff_low = (DWORD) (diff & 0xFFFFFFFF);
1509 diff_high = (DWORD) ((diff >> (sizeof (DWORD) * 8)) & 0xFFFFFFFF);
1511 memset (&o, 0, sizeof (OVERLAPPED));
1512 o.Offset = (DWORD) (lock_start & 0xFFFFFFFF);;
1513 o.OffsetHigh = (DWORD) (((lock_start & ~0xFFFFFFFF) >> (sizeof (DWORD) * 8)) & 0xFFFFFFFF);
1516 (fh->h, (excl ? LOCKFILE_EXCLUSIVE_LOCK : 0) | LOCKFILE_FAIL_IMMEDIATELY,
1517 0, diff_low, diff_high, &o))
1519 SetErrnoFromWinError (GetLastError ());
1520 return GNUNET_SYSERR;
1529 * Unlock a part of a file
1530 * @param fh file handle
1531 * @param unlock_start absolute position from where to unlock
1532 * @param unlock_end absolute position until where to unlock
1533 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1536 GNUNET_DISK_file_unlock (struct GNUNET_DISK_FileHandle *fh, off_t unlock_start,
1542 return GNUNET_SYSERR;
1548 memset (&fl, 0, sizeof (struct flock));
1549 fl.l_type = F_UNLCK;
1550 fl.l_whence = SEEK_SET;
1551 fl.l_start = unlock_start;
1552 fl.l_len = unlock_end;
1554 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1557 off_t diff = unlock_end - unlock_start;
1558 DWORD diff_low, diff_high;
1559 diff_low = (DWORD) (diff & 0xFFFFFFFF);
1560 diff_high = (DWORD) ((diff >> (sizeof (DWORD) * 8)) & 0xFFFFFFFF);
1562 memset (&o, 0, sizeof (OVERLAPPED));
1563 o.Offset = (DWORD) (unlock_start & 0xFFFFFFFF);;
1564 o.OffsetHigh = (DWORD) (((unlock_start & ~0xFFFFFFFF) >> (sizeof (DWORD) * 8)) & 0xFFFFFFFF);
1566 if (!UnlockFileEx (fh->h, 0, diff_low, diff_high, &o))
1568 SetErrnoFromWinError (GetLastError ());
1569 return GNUNET_SYSERR;
1578 * Open a file. Note that the access permissions will only be
1579 * used if a new file is created and if the underlying operating
1580 * system supports the given permissions.
1582 * @param fn file name to be opened
1583 * @param flags opening flags, a combination of GNUNET_DISK_OPEN_xxx bit flags
1584 * @param perm permissions for the newly created file, use
1585 * #GNUNET_DISK_PERM_NONE if a file could not be created by this
1586 * call (because of flags)
1587 * @return IO handle on success, NULL on error
1589 struct GNUNET_DISK_FileHandle *
1590 GNUNET_DISK_file_open (const char *fn,
1591 enum GNUNET_DISK_OpenFlags flags,
1592 enum GNUNET_DISK_AccessPermissions perm)
1595 struct GNUNET_DISK_FileHandle *ret;
1601 wchar_t wexpfn[MAX_PATH + 1];
1608 expfn = GNUNET_STRINGS_filename_expand (fn);
1613 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1614 oflags = O_RDWR; /* note: O_RDWR is NOT always O_RDONLY | O_WRONLY */
1615 else if (flags & GNUNET_DISK_OPEN_READ)
1617 else if (flags & GNUNET_DISK_OPEN_WRITE)
1622 GNUNET_free (expfn);
1625 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1626 oflags |= (O_CREAT | O_EXCL);
1627 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1629 if (flags & GNUNET_DISK_OPEN_APPEND)
1631 if (flags & GNUNET_DISK_OPEN_CREATE)
1633 (void) GNUNET_DISK_directory_create_for_file (expfn);
1635 mode = translate_unix_perms (perm);
1638 fd = open (expfn, oflags
1642 | O_LARGEFILE, mode);
1645 if (0 == (flags & GNUNET_DISK_OPEN_FAILIFEXISTS))
1646 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1648 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_DEBUG, "open", expfn);
1649 GNUNET_free (expfn);
1656 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1657 access = FILE_READ_DATA | FILE_WRITE_DATA;
1658 else if (flags & GNUNET_DISK_OPEN_READ)
1659 access = FILE_READ_DATA;
1660 else if (flags & GNUNET_DISK_OPEN_WRITE)
1661 access = FILE_WRITE_DATA;
1663 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1667 else if (flags & GNUNET_DISK_OPEN_CREATE)
1669 (void) GNUNET_DISK_directory_create_for_file (expfn);
1670 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1671 disp = CREATE_ALWAYS;
1675 else if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1677 disp = TRUNCATE_EXISTING;
1681 disp = OPEN_EXISTING;
1684 if (ERROR_SUCCESS == plibc_conv_to_win_pathwconv(expfn, wexpfn))
1685 h = CreateFileW (wexpfn, access,
1686 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1687 disp, FILE_ATTRIBUTE_NORMAL, NULL);
1689 h = INVALID_HANDLE_VALUE;
1690 if (h == INVALID_HANDLE_VALUE)
1693 SetErrnoFromWinError (GetLastError ());
1695 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_INFO, "open", expfn);
1696 GNUNET_free (expfn);
1701 if (flags & GNUNET_DISK_OPEN_APPEND)
1702 if (SetFilePointer (h, 0, 0, FILE_END) == INVALID_SET_FILE_POINTER)
1704 SetErrnoFromWinError (GetLastError ());
1705 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "SetFilePointer", expfn);
1707 GNUNET_free (expfn);
1712 ret = GNUNET_new (struct GNUNET_DISK_FileHandle);
1715 ret->type = GNUNET_DISK_HANLDE_TYPE_FILE;
1719 GNUNET_free (expfn);
1725 * Close an open file
1726 * @param h file handle
1727 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1730 GNUNET_DISK_file_close (struct GNUNET_DISK_FileHandle *h)
1736 return GNUNET_SYSERR;
1742 if (!CloseHandle (h->h))
1744 SetErrnoFromWinError (GetLastError ());
1745 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close");
1746 ret = GNUNET_SYSERR;
1748 if (h->oOverlapRead)
1750 if (!CloseHandle (h->oOverlapRead->hEvent))
1752 SetErrnoFromWinError (GetLastError ());
1753 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close");
1754 ret = GNUNET_SYSERR;
1756 GNUNET_free (h->oOverlapRead);
1758 if (h->oOverlapWrite)
1760 if (!CloseHandle (h->oOverlapWrite->hEvent))
1762 SetErrnoFromWinError (GetLastError ());
1763 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close");
1764 ret = GNUNET_SYSERR;
1766 GNUNET_free (h->oOverlapWrite);
1769 if (close (h->fd) != 0)
1771 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close");
1772 ret = GNUNET_SYSERR;
1781 * Get a GNUnet file handle from a W32 handle.
1783 * @param handle native handle
1784 * @return GNUnet file handle corresponding to the W32 handle
1786 struct GNUNET_DISK_FileHandle *
1787 GNUNET_DISK_get_handle_from_w32_handle (HANDLE osfh)
1789 struct GNUNET_DISK_FileHandle *fh;
1792 enum GNUNET_FILE_Type ftype;
1794 dwret = GetFileType (osfh);
1797 case FILE_TYPE_DISK:
1798 ftype = GNUNET_DISK_HANLDE_TYPE_FILE;
1800 case FILE_TYPE_PIPE:
1801 ftype = GNUNET_DISK_HANLDE_TYPE_PIPE;
1803 case FILE_TYPE_UNKNOWN:
1804 if (GetLastError () == NO_ERROR || GetLastError () == ERROR_INVALID_HANDLE)
1806 if (0 != ResetEvent (osfh))
1807 ftype = GNUNET_DISK_HANLDE_TYPE_EVENT;
1816 fh = GNUNET_new (struct GNUNET_DISK_FileHandle);
1820 if (ftype == GNUNET_DISK_HANLDE_TYPE_PIPE)
1823 * Note that we can't make it overlapped if it isn't already.
1824 * (ReOpenFile() is only available in 2003/Vista).
1825 * The process that opened this file in the first place (usually a parent
1826 * process, if this is stdin/stdout/stderr) must make it overlapped,
1827 * otherwise we're screwed, as selecting on non-overlapped handle
1830 fh->oOverlapRead = GNUNET_new (OVERLAPPED);
1831 fh->oOverlapWrite = GNUNET_new (OVERLAPPED);
1832 fh->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
1833 fh->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
1841 * Get a handle from a native integer FD.
1843 * @param fno native integer file descriptor
1844 * @return file handle corresponding to the descriptor, NULL on error
1846 struct GNUNET_DISK_FileHandle *
1847 GNUNET_DISK_get_handle_from_int_fd (int fno)
1849 struct GNUNET_DISK_FileHandle *fh;
1851 if ( (((off_t) -1) == lseek (fno, 0, SEEK_CUR)) &&
1853 return NULL; /* invalid FD */
1856 fh = GNUNET_new (struct GNUNET_DISK_FileHandle);
1862 osfh = _get_osfhandle (fno);
1863 if (INVALID_HANDLE_VALUE == (HANDLE) osfh)
1866 fh = GNUNET_DISK_get_handle_from_w32_handle ((HANDLE) osfh);
1874 * Get a handle from a native streaming FD.
1876 * @param fd native streaming file descriptor
1877 * @return file handle corresponding to the descriptor
1879 struct GNUNET_DISK_FileHandle *
1880 GNUNET_DISK_get_handle_from_native (FILE *fd)
1888 return GNUNET_DISK_get_handle_from_int_fd (fno);
1893 * Handle for a memory-mapping operation.
1895 struct GNUNET_DISK_MapHandle
1898 * Address where the map is in memory.
1904 * Underlying OS handle.
1909 * Number of bytes mapped.
1917 #define MAP_FAILED ((void *) -1)
1921 * Map a file into memory
1923 * @param h open file handle
1924 * @param m handle to the new mapping
1925 * @param access access specification, GNUNET_DISK_MAP_TYPE_xxx
1926 * @param len size of the mapping
1927 * @return pointer to the mapped memory region, NULL on failure
1930 GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h,
1931 struct GNUNET_DISK_MapHandle **m,
1932 enum GNUNET_DISK_MapType access, size_t len)
1941 DWORD mapAccess, protect;
1943 if ((access & GNUNET_DISK_MAP_TYPE_READ) &&
1944 (access & GNUNET_DISK_MAP_TYPE_WRITE))
1946 protect = PAGE_READWRITE;
1947 mapAccess = FILE_MAP_ALL_ACCESS;
1949 else if (access & GNUNET_DISK_MAP_TYPE_READ)
1951 protect = PAGE_READONLY;
1952 mapAccess = FILE_MAP_READ;
1954 else if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1956 protect = PAGE_READWRITE;
1957 mapAccess = FILE_MAP_WRITE;
1965 *m = GNUNET_new (struct GNUNET_DISK_MapHandle);
1966 (*m)->h = CreateFileMapping (h->h, NULL, protect, 0, 0, NULL);
1967 if ((*m)->h == INVALID_HANDLE_VALUE)
1969 SetErrnoFromWinError (GetLastError ());
1974 (*m)->addr = MapViewOfFile ((*m)->h, mapAccess, 0, 0, len);
1977 SetErrnoFromWinError (GetLastError ());
1978 CloseHandle ((*m)->h);
1987 if (access & GNUNET_DISK_MAP_TYPE_READ)
1989 if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1991 *m = GNUNET_new (struct GNUNET_DISK_MapHandle);
1992 (*m)->addr = mmap (NULL, len, prot, MAP_SHARED, h->fd, 0);
1993 GNUNET_assert (NULL != (*m)->addr);
1994 if (MAP_FAILED == (*m)->addr)
2006 * @param h mapping handle
2007 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2010 GNUNET_DISK_file_unmap (struct GNUNET_DISK_MapHandle *h)
2017 return GNUNET_SYSERR;
2021 ret = UnmapViewOfFile (h->addr) ? GNUNET_OK : GNUNET_SYSERR;
2022 if (ret != GNUNET_OK)
2023 SetErrnoFromWinError (GetLastError ());
2024 if (!CloseHandle (h->h) && (ret == GNUNET_OK))
2026 ret = GNUNET_SYSERR;
2027 SetErrnoFromWinError (GetLastError ());
2030 ret = munmap (h->addr, h->len) != -1 ? GNUNET_OK : GNUNET_SYSERR;
2038 * Write file changes to disk
2039 * @param h handle to an open file
2040 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2043 GNUNET_DISK_file_sync (const struct GNUNET_DISK_FileHandle *h)
2048 return GNUNET_SYSERR;
2054 ret = FlushFileBuffers (h->h) ? GNUNET_OK : GNUNET_SYSERR;
2055 if (ret != GNUNET_OK)
2056 SetErrnoFromWinError (GetLastError ());
2058 #elif defined(FREEBSD) || defined(OPENBSD) || defined(DARWIN)
2059 return fsync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
2061 return fdatasync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
2068 #define PIPE_BUF 512
2070 /* Copyright Bob Byrnes <byrnes <at> curl.com>
2071 http://permalink.gmane.org/gmane.os.cygwin.patches/2121
2073 /* Create a pipe, and return handles to the read and write ends,
2074 just like CreatePipe, but ensure that the write end permits
2075 FILE_READ_ATTRIBUTES access, on later versions of win32 where
2076 this is supported. This access is needed by NtQueryInformationFile,
2077 which is used to implement select and nonblocking writes.
2078 Note that the return value is either NO_ERROR or GetLastError,
2079 unlike CreatePipe, which returns a bool for success or failure. */
2081 create_selectable_pipe (PHANDLE read_pipe_ptr, PHANDLE write_pipe_ptr,
2082 LPSECURITY_ATTRIBUTES sa_ptr, DWORD psize,
2083 DWORD dwReadMode, DWORD dwWriteMode)
2085 /* Default to error. */
2086 *read_pipe_ptr = *write_pipe_ptr = INVALID_HANDLE_VALUE;
2091 /* Ensure that there is enough pipe buffer space for atomic writes. */
2092 if (psize < PIPE_BUF)
2095 char pipename[MAX_PATH];
2097 /* Retry CreateNamedPipe as long as the pipe name is in use.
2098 * Retrying will probably never be necessary, but we want
2099 * to be as robust as possible. */
2102 static volatile LONG pipe_unique_id;
2104 snprintf (pipename, sizeof pipename, "\\\\.\\pipe\\gnunet-%d-%ld",
2105 getpid (), InterlockedIncrement ((LONG *) & pipe_unique_id));
2106 LOG (GNUNET_ERROR_TYPE_DEBUG, "CreateNamedPipe: name = %s, size = %lu\n",
2108 /* Use CreateNamedPipe instead of CreatePipe, because the latter
2109 * returns a write handle that does not permit FILE_READ_ATTRIBUTES
2110 * access, on versions of win32 earlier than WinXP SP2.
2111 * CreatePipe also stupidly creates a full duplex pipe, which is
2112 * a waste, since only a single direction is actually used.
2113 * It's important to only allow a single instance, to ensure that
2114 * the pipe was not created earlier by some other process, even if
2115 * the pid has been reused. */
2116 read_pipe = CreateNamedPipeA (pipename, PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE | dwReadMode, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, /* max instances */
2117 psize, /* output buffer size */
2118 psize, /* input buffer size */
2119 NMPWAIT_USE_DEFAULT_WAIT, sa_ptr);
2121 if (read_pipe != INVALID_HANDLE_VALUE)
2123 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe read handle = %p\n", read_pipe);
2127 DWORD err = GetLastError ();
2131 case ERROR_PIPE_BUSY:
2132 /* The pipe is already open with compatible parameters.
2133 * Pick a new name and retry. */
2134 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe busy, retrying\n");
2136 case ERROR_ACCESS_DENIED:
2137 /* The pipe is already open with incompatible parameters.
2138 * Pick a new name and retry. */
2139 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe access denied, retrying\n");
2141 case ERROR_CALL_NOT_IMPLEMENTED:
2142 /* We are on an older Win9x platform without named pipes.
2143 * Return an anonymous pipe as the best approximation. */
2144 LOG (GNUNET_ERROR_TYPE_DEBUG,
2145 "CreateNamedPipe not implemented, resorting to "
2146 "CreatePipe: size = %lu\n", psize);
2147 if (CreatePipe (read_pipe_ptr, write_pipe_ptr, sa_ptr, psize))
2149 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe read handle = %p, write handle = %p\n",
2154 err = GetLastError ();
2155 LOG (GNUNET_ERROR_TYPE_ERROR, "CreatePipe failed: %d\n", err);
2158 LOG (GNUNET_ERROR_TYPE_ERROR, "CreateNamedPipe failed: %d\n", err);
2163 LOG (GNUNET_ERROR_TYPE_DEBUG, "CreateFile: name = %s\n", pipename);
2165 /* Open the named pipe for writing.
2166 * Be sure to permit FILE_READ_ATTRIBUTES access. */
2167 write_pipe = CreateFileA (pipename, GENERIC_WRITE | FILE_READ_ATTRIBUTES, 0, /* share mode */
2168 sa_ptr, OPEN_EXISTING, dwWriteMode, /* flags and attributes */
2169 0); /* handle to template file */
2171 if (write_pipe == INVALID_HANDLE_VALUE)
2174 DWORD err = GetLastError ();
2176 LOG (GNUNET_ERROR_TYPE_DEBUG, "CreateFile failed: %d\n", err);
2177 CloseHandle (read_pipe);
2180 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe write handle = %p\n", write_pipe);
2182 *read_pipe_ptr = read_pipe;
2183 *write_pipe_ptr = write_pipe;
2190 * Creates an interprocess channel
2192 * @param blocking_read creates an asynchronous pipe for reading if set to GNUNET_NO
2193 * @param blocking_write creates an asynchronous pipe for writing if set to GNUNET_NO
2194 * @param inherit_read inherit the parent processes stdin (only for windows)
2195 * @param inherit_write inherit the parent processes stdout (only for windows)
2196 * @return handle to the new pipe, NULL on error
2198 struct GNUNET_DISK_PipeHandle *
2199 GNUNET_DISK_pipe (int blocking_read, int blocking_write, int inherit_read, int inherit_write)
2210 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
2214 return GNUNET_DISK_pipe_from_fd (blocking_read,
2218 struct GNUNET_DISK_PipeHandle *p;
2223 p = GNUNET_new (struct GNUNET_DISK_PipeHandle);
2224 p->fd[0] = GNUNET_new (struct GNUNET_DISK_FileHandle);
2225 p->fd[1] = GNUNET_new (struct GNUNET_DISK_FileHandle);
2227 /* All pipes are overlapped. If you want them to block - just
2228 * call WriteFile() and ReadFile() with NULL overlapped pointer.
2229 * NOTE: calling with NULL overlapped pointer works only
2230 * for pipes, and doesn't seem to be a documented feature.
2231 * It will NOT work for files, because overlapped files need
2232 * to read offsets from the overlapped structure, regardless.
2233 * Pipes are not seekable, and need no offsets, which is
2234 * probably why it works for them.
2237 create_selectable_pipe (&p->fd[0]->h, &p->fd[1]->h, NULL, 0,
2238 FILE_FLAG_OVERLAPPED,
2239 FILE_FLAG_OVERLAPPED);
2242 SetErrnoFromWinError (GetLastError ());
2244 GNUNET_free (p->fd[0]);
2245 GNUNET_free (p->fd[1]);
2250 if (!DuplicateHandle
2251 (GetCurrentProcess (), p->fd[0]->h, GetCurrentProcess (), &tmp_handle, 0,
2252 inherit_read == GNUNET_YES ? TRUE : FALSE, DUPLICATE_SAME_ACCESS))
2254 SetErrnoFromWinError (GetLastError ());
2256 CloseHandle (p->fd[0]->h);
2257 CloseHandle (p->fd[1]->h);
2258 GNUNET_free (p->fd[0]);
2259 GNUNET_free (p->fd[1]);
2264 CloseHandle (p->fd[0]->h);
2265 p->fd[0]->h = tmp_handle;
2267 if (!DuplicateHandle
2268 (GetCurrentProcess (), p->fd[1]->h, GetCurrentProcess (), &tmp_handle, 0,
2269 inherit_write == GNUNET_YES ? TRUE : FALSE, DUPLICATE_SAME_ACCESS))
2271 SetErrnoFromWinError (GetLastError ());
2273 CloseHandle (p->fd[0]->h);
2274 CloseHandle (p->fd[1]->h);
2275 GNUNET_free (p->fd[0]);
2276 GNUNET_free (p->fd[1]);
2281 CloseHandle (p->fd[1]->h);
2282 p->fd[1]->h = tmp_handle;
2284 p->fd[0]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2285 p->fd[1]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2287 p->fd[0]->oOverlapRead = GNUNET_new (OVERLAPPED);
2288 p->fd[0]->oOverlapWrite = GNUNET_new (OVERLAPPED);
2289 p->fd[1]->oOverlapRead = GNUNET_new (OVERLAPPED);
2290 p->fd[1]->oOverlapWrite = GNUNET_new (OVERLAPPED);
2292 p->fd[0]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2293 p->fd[0]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2295 p->fd[1]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2296 p->fd[1]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2304 * Creates a pipe object from a couple of file descriptors.
2305 * Useful for wrapping existing pipe FDs.
2307 * @param blocking_read creates an asynchronous pipe for reading if set to GNUNET_NO
2308 * @param blocking_write creates an asynchronous pipe for writing if set to GNUNET_NO
2309 * @param fd an array of two fd values. One of them may be -1 for read-only or write-only pipes
2311 * @return handle to the new pipe, NULL on error
2313 struct GNUNET_DISK_PipeHandle *
2314 GNUNET_DISK_pipe_from_fd (int blocking_read, int blocking_write, int fd[2])
2316 struct GNUNET_DISK_PipeHandle *p;
2318 p = GNUNET_new (struct GNUNET_DISK_PipeHandle);
2323 int eno = 0; /* make gcc happy */
2328 p->fd[0] = GNUNET_new (struct GNUNET_DISK_FileHandle);
2329 p->fd[0]->fd = fd[0];
2332 flags = fcntl (fd[0], F_GETFL);
2333 flags |= O_NONBLOCK;
2334 if (0 > fcntl (fd[0], F_SETFL, flags))
2340 flags = fcntl (fd[0], F_GETFD);
2341 flags |= FD_CLOEXEC;
2342 if (0 > fcntl (fd[0], F_SETFD, flags))
2351 p->fd[1] = GNUNET_new (struct GNUNET_DISK_FileHandle);
2352 p->fd[1]->fd = fd[1];
2353 if (!blocking_write)
2355 flags = fcntl (fd[1], F_GETFL);
2356 flags |= O_NONBLOCK;
2357 if (0 > fcntl (fd[1], F_SETFL, flags))
2363 flags = fcntl (fd[1], F_GETFD);
2364 flags |= FD_CLOEXEC;
2365 if (0 > fcntl (fd[1], F_SETFD, flags))
2374 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fcntl");
2375 if (p->fd[0]->fd >= 0)
2376 GNUNET_break (0 == close (p->fd[0]->fd));
2377 if (p->fd[1]->fd >= 0)
2378 GNUNET_break (0 == close (p->fd[1]->fd));
2379 GNUNET_free_non_null (p->fd[0]);
2380 GNUNET_free_non_null (p->fd[1]);
2388 p->fd[0] = GNUNET_new (struct GNUNET_DISK_FileHandle);
2389 p->fd[0]->h = (HANDLE) _get_osfhandle (fd[0]);
2390 if (p->fd[0]->h != INVALID_HANDLE_VALUE)
2392 p->fd[0]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2393 p->fd[0]->oOverlapRead = GNUNET_new (OVERLAPPED);
2394 p->fd[0]->oOverlapWrite = GNUNET_new (OVERLAPPED);
2395 p->fd[0]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2396 p->fd[0]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2400 GNUNET_free (p->fd[0]);
2406 p->fd[1] = GNUNET_new (struct GNUNET_DISK_FileHandle);
2407 p->fd[1]->h = (HANDLE) _get_osfhandle (fd[1]);
2408 if (p->fd[1]->h != INVALID_HANDLE_VALUE)
2410 p->fd[1]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2411 p->fd[1]->oOverlapRead = GNUNET_new (OVERLAPPED);
2412 p->fd[1]->oOverlapWrite = GNUNET_new (OVERLAPPED);
2413 p->fd[1]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2414 p->fd[1]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2418 GNUNET_free (p->fd[1]);
2429 * Closes an interprocess channel
2431 * @param p pipe to close
2432 * @param end which end of the pipe to close
2433 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2436 GNUNET_DISK_pipe_close_end (struct GNUNET_DISK_PipeHandle *p,
2437 enum GNUNET_DISK_PipeEnd end)
2439 int ret = GNUNET_OK;
2441 if (end == GNUNET_DISK_PIPE_END_READ)
2445 ret = GNUNET_DISK_file_close (p->fd[0]);
2449 else if (end == GNUNET_DISK_PIPE_END_WRITE)
2453 ret = GNUNET_DISK_file_close (p->fd[1]);
2462 * Detaches one of the ends from the pipe.
2463 * Detached end is a fully-functional FileHandle, it will
2464 * not be affected by anything you do with the pipe afterwards.
2465 * Each end of a pipe can only be detched from it once (i.e.
2466 * it is not duplicated).
2468 * @param p pipe to detach an end from
2469 * @param end which end of the pipe to detach
2470 * @return Detached end on success, NULL on failure
2471 * (or if that end is not present or is closed).
2473 struct GNUNET_DISK_FileHandle *
2474 GNUNET_DISK_pipe_detach_end (struct GNUNET_DISK_PipeHandle *p,
2475 enum GNUNET_DISK_PipeEnd end)
2477 struct GNUNET_DISK_FileHandle *ret = NULL;
2479 if (end == GNUNET_DISK_PIPE_END_READ)
2487 else if (end == GNUNET_DISK_PIPE_END_WRITE)
2501 * Closes an interprocess channel
2503 * @param p pipe to close
2504 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2507 GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p)
2509 int ret = GNUNET_OK;
2512 int write_end_close;
2513 int read_end_close_errno;
2514 int write_end_close_errno;
2516 read_end_close = GNUNET_DISK_pipe_close_end (p, GNUNET_DISK_PIPE_END_READ);
2517 read_end_close_errno = errno;
2518 write_end_close = GNUNET_DISK_pipe_close_end (p, GNUNET_DISK_PIPE_END_WRITE);
2519 write_end_close_errno = errno;
2522 if (GNUNET_OK != read_end_close)
2524 errno = read_end_close_errno;
2525 ret = read_end_close;
2527 else if (GNUNET_OK != write_end_close)
2529 errno = write_end_close_errno;
2530 ret = write_end_close;
2538 * Get the handle to a particular pipe end
2541 * @param n end to access
2542 * @return handle for the respective end
2544 const struct GNUNET_DISK_FileHandle *
2545 GNUNET_DISK_pipe_handle (const struct GNUNET_DISK_PipeHandle *p,
2546 enum GNUNET_DISK_PipeEnd n)
2550 case GNUNET_DISK_PIPE_END_READ:
2551 case GNUNET_DISK_PIPE_END_WRITE:
2561 * Retrieve OS file handle
2563 * @param fh GNUnet file descriptor
2564 * @param dst destination buffer
2565 * @param dst_len length of dst
2566 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
2569 GNUNET_DISK_internal_file_handle_ (const struct GNUNET_DISK_FileHandle *fh,
2570 void *dst, size_t dst_len)
2573 return GNUNET_SYSERR;
2575 if (dst_len < sizeof (HANDLE))
2576 return GNUNET_SYSERR;
2577 *((HANDLE *) dst) = fh->h;
2579 if (dst_len < sizeof (int))
2580 return GNUNET_SYSERR;
2581 *((int *) dst) = fh->fd;