2 This file is part of GNUnet.
3 (C) 2001, 2002, 2005, 2006, 2009 Christian Grothoff (and other contributing authors)
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.
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., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
23 * @brief disk IO convenience methods
24 * @author Christian Grothoff
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"
37 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
39 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
41 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
43 #define DEBUG_NPIPE GNUNET_EXTRA_LOGGING
45 #define DEBUG_PIPE GNUNET_EXTRA_LOGGING
48 * Block size for IO for copying files.
50 #define COPY_BLK_SIZE 65536
54 #if defined(LINUX) || defined(CYGWIN)
57 #if defined(SOMEBSD) || defined(DARWIN)
58 #include <sys/param.h>
59 #include <sys/mount.h>
62 #include <sys/types.h>
63 #include <sys/statvfs.h>
68 ULONG PipeSerialNumber;
70 #define _IFMT 0170000 /* type of file */
71 #define _IFLNK 0120000 /* symbolic link */
72 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
74 #error PORT-ME: need to port statfs (how much space is left on the drive?)
80 #if !defined(SOMEBSD) && !defined(DARWIN) && !defined(WINDOWS)
84 #include <sys/statvfs.h>
89 * Handle used to manage a pipe.
91 struct GNUNET_DISK_PipeHandle
94 * File descriptors for the pipe.
96 struct GNUNET_DISK_FileHandle *fd[2];
101 * Closure for the recursion to determine the file size
104 struct GetFileSizeData
107 * Set to the total file size.
112 * GNUNET_YES if symbolic links should be included.
114 int include_sym_links;
119 translate_unix_perms (enum GNUNET_DISK_AccessPermissions perm)
124 if (perm & GNUNET_DISK_PERM_USER_READ)
126 if (perm & GNUNET_DISK_PERM_USER_WRITE)
128 if (perm & GNUNET_DISK_PERM_USER_EXEC)
130 if (perm & GNUNET_DISK_PERM_GROUP_READ)
132 if (perm & GNUNET_DISK_PERM_GROUP_WRITE)
134 if (perm & GNUNET_DISK_PERM_GROUP_EXEC)
136 if (perm & GNUNET_DISK_PERM_OTHER_READ)
138 if (perm & GNUNET_DISK_PERM_OTHER_WRITE)
140 if (perm & GNUNET_DISK_PERM_OTHER_EXEC)
148 * Iterate over all files in the given directory and
149 * accumulate their size.
151 * @param cls closure of type "struct GetFileSizeData"
152 * @param fn current filename we are looking at
153 * @return GNUNET_SYSERR on serious errors, otherwise GNUNET_OK
156 getSizeRec (void *cls, const char *fn)
158 struct GetFileSizeData *gfsd = cls;
167 if (0 != STAT64 (fn, &buf))
169 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat64", fn);
170 return GNUNET_SYSERR;
173 if (0 != STAT (fn, &buf))
175 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", fn);
176 return GNUNET_SYSERR;
179 if ((!S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES))
180 gfsd->total += buf.st_size;
181 if ((S_ISDIR (buf.st_mode)) && (0 == ACCESS (fn, X_OK)) &&
182 ((!S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES)))
184 if (GNUNET_SYSERR == GNUNET_DISK_directory_scan (fn, &getSizeRec, gfsd))
185 return GNUNET_SYSERR;
192 * Checks whether a handle is invalid
194 * @param h handle to check
195 * @return GNUNET_YES if invalid, GNUNET_NO if valid
198 GNUNET_DISK_handle_invalid (const struct GNUNET_DISK_FileHandle *h)
201 return ((!h) || (h->h == INVALID_HANDLE_VALUE)) ? GNUNET_YES : GNUNET_NO;
203 return ((!h) || (h->fd == -1)) ? GNUNET_YES : GNUNET_NO;
209 * Move the read/write pointer in a file
211 * @param h handle of an open file
212 * @param offset position to move to
213 * @param whence specification to which position the offset parameter relates to
214 * @return the new position on success, GNUNET_SYSERR otherwise
217 GNUNET_DISK_file_seek (const struct GNUNET_DISK_FileHandle * h, off_t offset,
218 enum GNUNET_DISK_Seek whence)
223 return GNUNET_SYSERR;
229 static DWORD t[] = {[GNUNET_DISK_SEEK_SET] = FILE_BEGIN,
230 [GNUNET_DISK_SEEK_CUR] = FILE_CURRENT,[GNUNET_DISK_SEEK_END] = FILE_END
233 ret = SetFilePointer (h->h, offset, NULL, t[whence]);
234 if (ret == INVALID_SET_FILE_POINTER)
236 SetErrnoFromWinError (GetLastError ());
237 return GNUNET_SYSERR;
241 static int t[] = {[GNUNET_DISK_SEEK_SET] = SEEK_SET,
242 [GNUNET_DISK_SEEK_CUR] = SEEK_CUR,[GNUNET_DISK_SEEK_END] = SEEK_END
245 return lseek (h->fd, offset, t[whence]);
251 * Get the size of the file (or directory) of the given file (in
254 * @param filename name of the file or directory
255 * @param size set to the size of the file (or,
256 * in the case of directories, the sum
257 * of all sizes of files in the directory)
258 * @param includeSymLinks should symbolic links be
260 * @return GNUNET_SYSERR on error, GNUNET_OK on success
263 GNUNET_DISK_file_size (const char *filename, uint64_t * size,
266 struct GetFileSizeData gfsd;
269 GNUNET_assert (size != NULL);
271 gfsd.include_sym_links = includeSymLinks;
272 ret = getSizeRec (&gfsd, filename);
279 * Obtain some unique identifiers for the given file
280 * that can be used to identify it in the local system.
281 * This function is used between GNUnet processes to
282 * quickly check if two files with the same absolute path
283 * are actually identical. The two processes represent
284 * the same peer but may communicate over the network
285 * (and the file may be on an NFS volume). This function
286 * may not be supported on all operating systems.
288 * @param filename name of the file
289 * @param dev set to the device ID
290 * @param ino set to the inode ID
291 * @return GNUNET_OK on success
294 GNUNET_DISK_file_get_identifiers (const char *filename, uint64_t * dev,
301 if ((0 == stat (filename, &sbuf)) && (0 == statvfs (filename, &fbuf)))
303 *dev = (uint64_t) fbuf.f_fsid;
304 *ino = (uint64_t) sbuf.st_ino;
311 if ((0 == stat (filename, &sbuf)) && (0 == statfs (filename, &fbuf)))
313 *dev = ((uint64_t) fbuf.f_fsid.val[0]) << 32 ||
314 ((uint64_t) fbuf.f_fsid.val[1]);
315 *ino = (uint64_t) sbuf.st_ino;
319 // FIXME NILS: test this
320 struct GNUNET_DISK_FileHandle *fh;
321 BY_HANDLE_FILE_INFORMATION info;
324 fh = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ, 0);
326 return GNUNET_SYSERR;
327 succ = GetFileInformationByHandle (fh->h, &info);
328 GNUNET_DISK_file_close (fh);
331 *dev = info.dwVolumeSerialNumber;
332 *ino = ((info.nFileIndexHigh << sizeof (DWORD)) | info.nFileIndexLow);
336 return GNUNET_SYSERR;
339 return GNUNET_SYSERR;
344 * Create an (empty) temporary file on disk. If the given name is not
345 * an absolute path, the current 'TMPDIR' will be prepended. In any case,
346 * 6 random characters will be appended to the name to create a unique
349 * @param t component to use for the name;
350 * does NOT contain "XXXXXX" or "/tmp/".
351 * @return NULL on error, otherwise name of fresh
352 * file on disk in directory for temporary files
355 GNUNET_DISK_mktemp (const char *t)
362 if ((t[0] != '/') && (t[0] != '\\')
364 && !(isalpha ((int) t[0]) && (t[0] != '\0') && (t[1] == ':'))
368 tmpdir = getenv ("TMPDIR");
369 tmpdir = tmpdir ? tmpdir : "/tmp";
370 GNUNET_asprintf (&tmpl, "%s/%s%s", tmpdir, t, "XXXXXX");
374 GNUNET_asprintf (&tmpl, "%s%s", t, "XXXXXX");
377 fn = (char *) GNUNET_malloc (MAX_PATH + 1);
378 if (ERROR_SUCCESS != plibc_conv_to_win_path (tmpl, fn))
391 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "mkstemp", fn);
396 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "close", fn);
402 * Get the number of blocks that are left on the partition that
403 * contains the given file (for normal users).
405 * @param part a file on the partition to check
406 * @return -1 on errors, otherwise the number of free blocks
409 GNUNET_DISK_get_blocks_available (const char *part)
414 if (0 != statvfs (part, &buf))
416 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
426 path = GNUNET_STRINGS_filename_expand (part);
429 memcpy (szDrive, path, 3);
432 if (!GetDiskFreeSpace (szDrive, &dwDummy, &dwDummy, &dwBlocks, &dwDummy))
434 LOG (GNUNET_ERROR_TYPE_WARNING,
435 _("`%s' failed for drive `%s': %u\n"), "GetDiskFreeSpace",
436 szDrive, GetLastError ());
444 if (0 != statfs (part, &s))
446 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "statfs", part);
455 * Test if "fil" is a directory.
456 * Will not print an error message if the directory
457 * does not exist. Will log errors if GNUNET_SYSERR is
458 * returned (i.e., a file exists with the same name).
460 * @param fil filename to test
461 * @return GNUNET_YES if yes, GNUNET_NO if not, GNUNET_SYSERR if it
465 GNUNET_DISK_directory_test (const char *fil)
467 struct stat filestat;
470 ret = STAT (fil, &filestat);
475 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", fil);
476 return GNUNET_SYSERR;
480 if (!S_ISDIR (filestat.st_mode))
482 if (ACCESS (fil, R_OK | X_OK) < 0)
484 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", fil);
485 return GNUNET_SYSERR;
491 * Check that fil corresponds to a filename
492 * (of a file that exists and that is not a directory).
494 * @param fil filename to check
495 * @return GNUNET_YES if yes, GNUNET_NO if not a file, GNUNET_SYSERR if something
496 * else (will print an error message in that case, too).
499 GNUNET_DISK_file_test (const char *fil)
501 struct stat filestat;
505 rdir = GNUNET_STRINGS_filename_expand (fil);
507 return GNUNET_SYSERR;
509 ret = STAT (rdir, &filestat);
514 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", rdir);
516 return GNUNET_SYSERR;
521 if (!S_ISREG (filestat.st_mode))
526 if (ACCESS (rdir, R_OK) < 0)
528 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", rdir);
530 return GNUNET_SYSERR;
538 * Implementation of "mkdir -p"
539 * @param dir the directory to create
540 * @returns GNUNET_OK on success, GNUNET_SYSERR on failure
543 GNUNET_DISK_directory_create (const char *dir)
550 rdir = GNUNET_STRINGS_filename_expand (dir);
552 return GNUNET_SYSERR;
556 pos = 1; /* skip heading '/' */
558 /* Local or Network path? */
559 if (strncmp (rdir, "\\\\", 2) == 0)
564 if (rdir[pos] == '\\')
574 pos = 3; /* strlen("C:\\") */
579 if ((rdir[pos] == DIR_SEPARATOR) || (pos == len))
582 ret = GNUNET_DISK_directory_test (rdir);
583 if (ret == GNUNET_SYSERR)
586 return GNUNET_SYSERR;
588 if (ret == GNUNET_NO)
591 ret = mkdir (rdir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); /* 755 */
595 if ((ret != 0) && (errno != EEXIST))
597 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "mkdir", rdir);
599 return GNUNET_SYSERR;
602 rdir[pos] = DIR_SEPARATOR;
612 * Create the directory structure for storing
615 * @param filename name of a file in the directory
616 * @returns GNUNET_OK on success,
617 * GNUNET_SYSERR on failure,
618 * GNUNET_NO if the directory
619 * exists but is not writeable for us
622 GNUNET_DISK_directory_create_for_file (const char *filename)
628 rdir = GNUNET_STRINGS_filename_expand (filename);
630 return GNUNET_SYSERR;
632 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
635 ret = GNUNET_DISK_directory_create (rdir);
636 if ((ret == GNUNET_OK) && (0 != ACCESS (rdir, W_OK)))
644 * Read the contents of a binary file into a buffer.
645 * @param h handle to an open file
646 * @param result the buffer to write the result to
647 * @param len the maximum number of bytes to read
648 * @return the number of bytes read on success, GNUNET_SYSERR on failure
651 GNUNET_DISK_file_read (const struct GNUNET_DISK_FileHandle * h, void *result,
657 return GNUNET_SYSERR;
663 if (h->type != GNUNET_PIPE)
665 if (!ReadFile (h->h, result, len, &bytesRead, NULL))
667 SetErrnoFromWinError (GetLastError ());
668 return GNUNET_SYSERR;
673 if (!ReadFile (h->h, result, len, NULL, h->oOverlapRead))
675 if (GetLastError () != ERROR_IO_PENDING)
677 SetErrnoFromWinError (GetLastError ());
678 return GNUNET_SYSERR;
681 GetOverlappedResult (h->h, h->oOverlapRead, &bytesRead, TRUE);
685 return read (h->fd, result, len);
691 * Read the contents of a binary file into a buffer.
693 * @param fn file name
694 * @param result the buffer to write the result to
695 * @param len the maximum number of bytes to read
696 * @return number of bytes read, GNUNET_SYSERR on failure
699 GNUNET_DISK_fn_read (const char *fn, void *result, size_t len)
701 struct GNUNET_DISK_FileHandle *fh;
705 GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_READ, GNUNET_DISK_PERM_NONE);
707 return GNUNET_SYSERR;
708 ret = GNUNET_DISK_file_read (fh, result, len);
709 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
716 * Write a buffer to a file.
717 * @param h handle to open file
718 * @param buffer the data to write
719 * @param n number of bytes to write
720 * @return number of bytes written on success, GNUNET_SYSERR on error
723 GNUNET_DISK_file_write (const struct GNUNET_DISK_FileHandle * h,
724 const void *buffer, size_t n)
729 return GNUNET_SYSERR;
735 if (h->type != GNUNET_PIPE)
737 if (!WriteFile (h->h, buffer, n, &bytesWritten, NULL))
739 SetErrnoFromWinError (GetLastError ());
740 return GNUNET_SYSERR;
746 LOG (GNUNET_ERROR_TYPE_DEBUG, "It is a pipe trying to write\n");
748 if (!WriteFile (h->h, buffer, n, NULL, h->oOverlapWrite))
750 if (GetLastError () != ERROR_IO_PENDING)
752 SetErrnoFromWinError (GetLastError ());
754 LOG (GNUNET_ERROR_TYPE_DEBUG, "Error writing to pipe\n");
756 return GNUNET_SYSERR;
760 LOG (GNUNET_ERROR_TYPE_DEBUG, "Will get overlapped result\n");
762 GetOverlappedResult (h->h, h->oOverlapWrite, &bytesWritten, TRUE);
766 return write (h->fd, buffer, n);
771 * Write a buffer to a file. If the file is longer than the
772 * number of bytes that will be written, it will be truncated.
774 * @param fn file name
775 * @param buffer the data to write
776 * @param n number of bytes to write
777 * @param mode file permissions
778 * @return number of bytes written on success, GNUNET_SYSERR on error
781 GNUNET_DISK_fn_write (const char *fn, const void *buffer, size_t n,
782 enum GNUNET_DISK_AccessPermissions mode)
784 struct GNUNET_DISK_FileHandle *fh;
787 fh = GNUNET_DISK_file_open (fn,
788 GNUNET_DISK_OPEN_WRITE |
789 GNUNET_DISK_OPEN_TRUNCATE |
790 GNUNET_DISK_OPEN_CREATE, mode);
792 return GNUNET_SYSERR;
793 ret = GNUNET_DISK_file_write (fh, buffer, n);
794 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
799 * Scan a directory for files.
801 * @param dirName the name of the directory
802 * @param callback the method to call for each file,
803 * can be NULL, in that case, we only count
804 * @param callback_cls closure for callback
805 * @return the number of files found, GNUNET_SYSERR on error or
806 * ieration aborted by callback returning GNUNET_SYSERR
809 GNUNET_DISK_directory_scan (const char *dirName,
810 GNUNET_FileNameCallback callback,
814 struct dirent *finfo;
819 unsigned int name_len;
822 GNUNET_assert (dirName != NULL);
823 dname = GNUNET_STRINGS_filename_expand (dirName);
825 return GNUNET_SYSERR;
826 while ((strlen (dname) > 0) && (dname[strlen (dname) - 1] == DIR_SEPARATOR))
827 dname[strlen (dname) - 1] = '\0';
828 if (0 != STAT (dname, &istat))
830 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", dname);
832 return GNUNET_SYSERR;
834 if (!S_ISDIR (istat.st_mode))
836 LOG (GNUNET_ERROR_TYPE_WARNING,
837 _("Expected `%s' to be a directory!\n"), dirName);
839 return GNUNET_SYSERR;
842 dinfo = OPENDIR (dname);
843 if ((errno == EACCES) || (dinfo == NULL))
845 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "opendir", dname);
849 return GNUNET_SYSERR;
852 n_size = strlen (dname) + name_len + 2;
853 name = GNUNET_malloc (n_size);
854 while ((finfo = readdir (dinfo)) != NULL)
856 if ((0 == strcmp (finfo->d_name, ".")) ||
857 (0 == strcmp (finfo->d_name, "..")))
859 if (callback != NULL)
861 if (name_len < strlen (finfo->d_name))
864 name_len = strlen (finfo->d_name);
865 n_size = strlen (dname) + name_len + 2;
866 name = GNUNET_malloc (n_size);
868 /* dname can end in "/" only if dname == "/";
869 * if dname does not end in "/", we need to add
870 * a "/" (otherwise, we must not!) */
871 GNUNET_snprintf (name, n_size, "%s%s%s", dname,
872 (strcmp (dname, DIR_SEPARATOR_STR) ==
873 0) ? "" : DIR_SEPARATOR_STR, finfo->d_name);
874 if (GNUNET_OK != callback (callback_cls, name))
879 return GNUNET_SYSERR;
892 * Opaque handle used for iterating over a directory.
894 struct GNUNET_DISK_DirectoryIterator
898 * Function to call on directory entries.
900 GNUNET_DISK_DirectoryIteratorCallback callback;
903 * Closure for callback.
908 * Reference to directory.
918 * Next filename to process.
925 enum GNUNET_SCHEDULER_Priority priority;
931 * Task used by the directory iterator.
934 directory_iterator_task (void *cls,
935 const struct GNUNET_SCHEDULER_TaskContext *tc)
937 struct GNUNET_DISK_DirectoryIterator *iter = cls;
940 name = iter->next_name;
941 GNUNET_assert (name != NULL);
942 iter->next_name = NULL;
943 iter->callback (iter->callback_cls, iter, name, iter->dirname);
949 * This function must be called during the DiskIteratorCallback
950 * (exactly once) to schedule the task to process the next
951 * filename in the directory (if there is one).
953 * @param iter opaque handle for the iterator
954 * @param can set to GNUNET_YES to terminate the iteration early
955 * @return GNUNET_YES if iteration will continue,
956 * GNUNET_NO if this was the last entry (and iteration is complete),
957 * GNUNET_SYSERR if abort was YES
960 GNUNET_DISK_directory_iterator_next (struct GNUNET_DISK_DirectoryIterator
963 struct dirent *finfo;
965 GNUNET_assert (iter->next_name == NULL);
966 if (can == GNUNET_YES)
968 closedir (iter->directory);
969 GNUNET_free (iter->dirname);
971 return GNUNET_SYSERR;
973 while (NULL != (finfo = readdir (iter->directory)))
975 if ((0 == strcmp (finfo->d_name, ".")) ||
976 (0 == strcmp (finfo->d_name, "..")))
978 GNUNET_asprintf (&iter->next_name, "%s%s%s", iter->dirname,
979 DIR_SEPARATOR_STR, finfo->d_name);
984 GNUNET_DISK_directory_iterator_next (iter, GNUNET_YES);
987 GNUNET_SCHEDULER_add_with_priority (iter->priority,
988 &directory_iterator_task, iter);
994 * Scan a directory for files using the scheduler to run a task for
995 * each entry. The name of the directory must be expanded first (!).
996 * If a scheduler does not need to be used, GNUNET_DISK_directory_scan
997 * may provide a simpler API.
999 * @param prio priority to use
1000 * @param dirName the name of the directory
1001 * @param callback the method to call for each file
1002 * @param callback_cls closure for callback
1005 GNUNET_DISK_directory_iterator_start (enum GNUNET_SCHEDULER_Priority prio,
1006 const char *dirName,
1007 GNUNET_DISK_DirectoryIteratorCallback
1008 callback, void *callback_cls)
1010 struct GNUNET_DISK_DirectoryIterator *di;
1012 di = GNUNET_malloc (sizeof (struct GNUNET_DISK_DirectoryIterator));
1013 di->callback = callback;
1014 di->callback_cls = callback_cls;
1015 di->directory = OPENDIR (dirName);
1016 if (di->directory == NULL)
1019 callback (callback_cls, NULL, NULL, NULL);
1022 di->dirname = GNUNET_strdup (dirName);
1023 di->priority = prio;
1024 GNUNET_DISK_directory_iterator_next (di, GNUNET_NO);
1029 * Function that removes the given directory by calling
1030 * "GNUNET_DISK_directory_remove".
1032 * @param unused not used
1033 * @param fn directory to remove
1037 remove_helper (void *unused, const char *fn)
1039 (void) GNUNET_DISK_directory_remove (fn);
1045 * Remove all files in a directory (rm -rf). Call with
1049 * @param fileName the file to remove
1050 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1053 GNUNET_DISK_directory_remove (const char *fileName)
1057 if (0 != LSTAT (fileName, &istat))
1058 return GNUNET_NO; /* file may not exist... */
1059 CHMOD (fileName, S_IWUSR | S_IRUSR | S_IXUSR);
1060 if (UNLINK (fileName) == 0)
1062 if ((errno != EISDIR) &&
1063 /* EISDIR is not sufficient in all cases, e.g.
1064 * sticky /tmp directory may result in EPERM on BSD.
1065 * So we also explicitly check "isDirectory" */
1066 (GNUNET_YES != GNUNET_DISK_directory_test (fileName)))
1068 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "rmdir", fileName);
1069 return GNUNET_SYSERR;
1071 if (GNUNET_SYSERR ==
1072 GNUNET_DISK_directory_scan (fileName, &remove_helper, NULL))
1073 return GNUNET_SYSERR;
1074 if (0 != RMDIR (fileName))
1076 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "rmdir", fileName);
1077 return GNUNET_SYSERR;
1086 * @param src file to copy
1087 * @param dst destination file name
1088 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1091 GNUNET_DISK_file_copy (const char *src, const char *dst)
1097 struct GNUNET_DISK_FileHandle *in;
1098 struct GNUNET_DISK_FileHandle *out;
1100 if (GNUNET_OK != GNUNET_DISK_file_size (src, &size, GNUNET_YES))
1101 return GNUNET_SYSERR;
1103 in = GNUNET_DISK_file_open (src, GNUNET_DISK_OPEN_READ,
1104 GNUNET_DISK_PERM_NONE);
1106 return GNUNET_SYSERR;
1108 GNUNET_DISK_file_open (dst,
1109 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE |
1110 GNUNET_DISK_OPEN_FAILIFEXISTS,
1111 GNUNET_DISK_PERM_USER_READ |
1112 GNUNET_DISK_PERM_USER_WRITE |
1113 GNUNET_DISK_PERM_GROUP_READ |
1114 GNUNET_DISK_PERM_GROUP_WRITE);
1117 GNUNET_DISK_file_close (in);
1118 return GNUNET_SYSERR;
1120 buf = GNUNET_malloc (COPY_BLK_SIZE);
1123 len = COPY_BLK_SIZE;
1124 if (len > size - pos)
1126 if (len != GNUNET_DISK_file_read (in, buf, len))
1128 if (len != GNUNET_DISK_file_write (out, buf, len))
1133 GNUNET_DISK_file_close (in);
1134 GNUNET_DISK_file_close (out);
1138 GNUNET_DISK_file_close (in);
1139 GNUNET_DISK_file_close (out);
1140 return GNUNET_SYSERR;
1145 * @brief Removes special characters as ':' from a filename.
1146 * @param fn the filename to canonicalize
1149 GNUNET_DISK_filename_canonicalize (char *fn)
1159 if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?'
1160 || c == '"' || c == '<' || c == '>' || c == '|')
1172 * @brief Change owner of a file
1174 * @param filename name of file to change the owner of
1175 * @param user name of the new owner
1176 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1179 GNUNET_DISK_file_change_owner (const char *filename, const char *user)
1184 pws = getpwnam (user);
1187 LOG (GNUNET_ERROR_TYPE_ERROR,
1188 _("Cannot obtain information about user `%s': %s\n"), user,
1190 return GNUNET_SYSERR;
1192 if (0 != chown (filename, pws->pw_uid, pws->pw_gid))
1193 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "chown", filename);
1200 * Lock a part of a file
1201 * @param fh file handle
1202 * @param lockStart absolute position from where to lock
1203 * @param lockEnd absolute position until where to lock
1204 * @param excl GNUNET_YES for an exclusive lock
1205 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1208 GNUNET_DISK_file_lock (struct GNUNET_DISK_FileHandle *fh, off_t lockStart,
1209 off_t lockEnd, int excl)
1214 return GNUNET_SYSERR;
1220 memset (&fl, 0, sizeof (struct flock));
1221 fl.l_type = excl ? F_WRLCK : F_RDLCK;
1222 fl.l_whence = SEEK_SET;
1223 fl.l_start = lockStart;
1226 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1230 memset (&o, 0, sizeof (OVERLAPPED));
1231 o.Offset = lockStart;
1235 (excl ? LOCKFILE_EXCLUSIVE_LOCK : 0) | LOCKFILE_FAIL_IMMEDIATELY, 0,
1236 lockEnd - lockStart, 0, &o))
1238 SetErrnoFromWinError (GetLastError ());
1239 return GNUNET_SYSERR;
1248 * Unlock a part of a file
1249 * @param fh file handle
1250 * @param unlockStart absolute position from where to unlock
1251 * @param unlockEnd absolute position until where to unlock
1252 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1255 GNUNET_DISK_file_unlock (struct GNUNET_DISK_FileHandle *fh, off_t unlockStart,
1261 return GNUNET_SYSERR;
1267 memset (&fl, 0, sizeof (struct flock));
1268 fl.l_type = F_UNLCK;
1269 fl.l_whence = SEEK_SET;
1270 fl.l_start = unlockStart;
1271 fl.l_len = unlockEnd;
1273 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1277 memset (&o, 0, sizeof (OVERLAPPED));
1278 o.Offset = unlockStart;
1280 if (!UnlockFileEx (fh->h, 0, unlockEnd - unlockStart, 0, &o))
1282 SetErrnoFromWinError (GetLastError ());
1283 return GNUNET_SYSERR;
1292 * Open a file. Note that the access permissions will only be
1293 * used if a new file is created and if the underlying operating
1294 * system supports the given permissions.
1296 * @param fn file name to be opened
1297 * @param flags opening flags, a combination of GNUNET_DISK_OPEN_xxx bit flags
1298 * @param perm permissions for the newly created file, use
1299 * GNUNET_DISK_PERM_USER_NONE if a file could not be created by this
1300 * call (because of flags)
1301 * @return IO handle on success, NULL on error
1303 struct GNUNET_DISK_FileHandle *
1304 GNUNET_DISK_file_open (const char *fn, enum GNUNET_DISK_OpenFlags flags,
1305 enum GNUNET_DISK_AccessPermissions perm)
1308 struct GNUNET_DISK_FileHandle *ret;
1320 expfn = GNUNET_STRINGS_filename_expand (fn);
1325 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1326 oflags = O_RDWR; /* note: O_RDWR is NOT always O_RDONLY | O_WRONLY */
1327 else if (flags & GNUNET_DISK_OPEN_READ)
1329 else if (flags & GNUNET_DISK_OPEN_WRITE)
1334 GNUNET_free (expfn);
1337 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1338 oflags |= (O_CREAT | O_EXCL);
1339 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1341 if (flags & GNUNET_DISK_OPEN_APPEND)
1343 if (flags & GNUNET_DISK_OPEN_CREATE)
1345 (void) GNUNET_DISK_directory_create_for_file (expfn);
1347 mode = translate_unix_perms (perm);
1350 fd = open (expfn, oflags | O_LARGEFILE, mode);
1353 if (0 == (flags & GNUNET_DISK_OPEN_FAILIFEXISTS))
1354 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1356 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_DEBUG, "open", expfn);
1357 GNUNET_free (expfn);
1364 if (GNUNET_DISK_OPEN_READWRITE == (flags & GNUNET_DISK_OPEN_READWRITE))
1365 access = FILE_READ_DATA | FILE_WRITE_DATA;
1366 else if (flags & GNUNET_DISK_OPEN_READ)
1367 access = FILE_READ_DATA;
1368 else if (flags & GNUNET_DISK_OPEN_WRITE)
1369 access = FILE_WRITE_DATA;
1371 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1375 else if (flags & GNUNET_DISK_OPEN_CREATE)
1377 (void) GNUNET_DISK_directory_create_for_file (expfn);
1378 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1379 disp = CREATE_ALWAYS;
1383 else if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1385 disp = TRUNCATE_EXISTING;
1389 disp = OPEN_EXISTING;
1392 /* TODO: access priviledges? */
1393 h = CreateFile (expfn, access,
1394 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
1395 NULL, disp, FILE_ATTRIBUTE_NORMAL, NULL);
1396 if (h == INVALID_HANDLE_VALUE)
1398 SetErrnoFromWinError (GetLastError ());
1399 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1400 GNUNET_free (expfn);
1404 if (flags & GNUNET_DISK_OPEN_APPEND)
1405 if (SetFilePointer (h, 0, 0, FILE_END) == INVALID_SET_FILE_POINTER)
1407 SetErrnoFromWinError (GetLastError ());
1408 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "SetFilePointer",
1411 GNUNET_free (expfn);
1416 ret = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
1419 ret->type = GNUNET_DISK_FILE;
1423 GNUNET_free (expfn);
1429 * Close an open file
1430 * @param h file handle
1431 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1434 GNUNET_DISK_file_close (struct GNUNET_DISK_FileHandle *h)
1439 return GNUNET_SYSERR;
1443 if (!CloseHandle (h->h))
1445 SetErrnoFromWinError (GetLastError ());
1446 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close");
1447 GNUNET_free (h->oOverlapRead);
1448 GNUNET_free (h->oOverlapWrite);
1450 return GNUNET_SYSERR;
1453 if (close (h->fd) != 0)
1455 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close");
1457 return GNUNET_SYSERR;
1466 * Construct full path to a file inside of the private
1467 * directory used by GNUnet. Also creates the corresponding
1468 * directory. If the resulting name is supposed to be
1469 * a directory, end the last argument in '/' (or pass
1470 * DIR_SEPARATOR_STR as the last argument before NULL).
1472 * @param cfg configuration to use (determines HOME)
1473 * @param serviceName name of the service
1474 * @param ... is NULL-terminated list of
1475 * path components to append to the
1476 * private directory name.
1477 * @return the constructed filename
1480 GNUNET_DISK_get_home_filename (const struct GNUNET_CONFIGURATION_Handle *cfg,
1481 const char *serviceName, ...)
1487 unsigned int needed;
1490 GNUNET_CONFIGURATION_get_value_filename (cfg, serviceName, "HOME",
1495 LOG (GNUNET_ERROR_TYPE_WARNING,
1496 _("No `%s' specified for service `%s' in configuration.\n"),
1497 "HOME", serviceName);
1500 needed = strlen (pfx) + 2;
1501 if ((pfx[strlen (pfx) - 1] != '/') && (pfx[strlen (pfx) - 1] != '\\'))
1503 va_start (ap, serviceName);
1506 c = va_arg (ap, const char *);
1510 needed += strlen (c);
1511 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1515 ret = GNUNET_malloc (needed);
1518 va_start (ap, serviceName);
1521 c = va_arg (ap, const char *);
1525 if ((c[strlen (c) - 1] != '/') && (c[strlen (c) - 1] != '\\'))
1526 strcat (ret, DIR_SEPARATOR_STR);
1530 if ((ret[strlen (ret) - 1] != '/') && (ret[strlen (ret) - 1] != '\\'))
1531 (void) GNUNET_DISK_directory_create_for_file (ret);
1533 (void) GNUNET_DISK_directory_create (ret);
1539 * Handle for a memory-mapping operation.
1541 struct GNUNET_DISK_MapHandle
1544 * Address where the map is in memory.
1550 * Underlying OS handle.
1555 * Number of bytes mapped.
1563 #define MAP_FAILED ((void *) -1)
1567 * Map a file into memory
1569 * @param h open file handle
1570 * @param m handle to the new mapping
1571 * @param access access specification, GNUNET_DISK_MAP_TYPE_xxx
1572 * @param len size of the mapping
1573 * @return pointer to the mapped memory region, NULL on failure
1576 GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h,
1577 struct GNUNET_DISK_MapHandle **m,
1578 enum GNUNET_DISK_MapType access, size_t len)
1587 DWORD mapAccess, protect;
1589 if ((access & GNUNET_DISK_MAP_TYPE_READ) &&
1590 (access & GNUNET_DISK_MAP_TYPE_WRITE))
1592 protect = PAGE_READWRITE;
1593 mapAccess = FILE_MAP_ALL_ACCESS;
1595 else if (access & GNUNET_DISK_MAP_TYPE_READ)
1597 protect = PAGE_READONLY;
1598 mapAccess = FILE_MAP_READ;
1600 else if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1602 protect = PAGE_READWRITE;
1603 mapAccess = FILE_MAP_WRITE;
1611 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1612 (*m)->h = CreateFileMapping (h->h, NULL, protect, 0, 0, NULL);
1613 if ((*m)->h == INVALID_HANDLE_VALUE)
1615 SetErrnoFromWinError (GetLastError ());
1620 (*m)->addr = MapViewOfFile ((*m)->h, mapAccess, 0, 0, len);
1623 SetErrnoFromWinError (GetLastError ());
1624 CloseHandle ((*m)->h);
1633 if (access & GNUNET_DISK_MAP_TYPE_READ)
1635 if (access & GNUNET_DISK_MAP_TYPE_WRITE)
1637 *m = GNUNET_malloc (sizeof (struct GNUNET_DISK_MapHandle));
1638 (*m)->addr = mmap (NULL, len, prot, MAP_SHARED, h->fd, 0);
1639 GNUNET_assert (NULL != (*m)->addr);
1640 if (MAP_FAILED == (*m)->addr)
1652 * @param h mapping handle
1653 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1656 GNUNET_DISK_file_unmap (struct GNUNET_DISK_MapHandle *h)
1663 return GNUNET_SYSERR;
1667 ret = UnmapViewOfFile (h->addr) ? GNUNET_OK : GNUNET_SYSERR;
1668 if (ret != GNUNET_OK)
1669 SetErrnoFromWinError (GetLastError ());
1670 if (!CloseHandle (h->h) && (ret == GNUNET_OK))
1672 ret = GNUNET_SYSERR;
1673 SetErrnoFromWinError (GetLastError ());
1676 ret = munmap (h->addr, h->len) != -1 ? GNUNET_OK : GNUNET_SYSERR;
1684 * Write file changes to disk
1685 * @param h handle to an open file
1686 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1689 GNUNET_DISK_file_sync (const struct GNUNET_DISK_FileHandle *h)
1694 return GNUNET_SYSERR;
1700 ret = FlushFileBuffers (h->h) ? GNUNET_OK : GNUNET_SYSERR;
1701 if (ret != GNUNET_OK)
1702 SetErrnoFromWinError (GetLastError ());
1704 #elif defined(FREEBSD) || defined(OPENBSD) || defined(DARWIN)
1705 return fsync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
1707 return fdatasync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
1712 /* Copyright Bob Byrnes <byrnes <at> curl.com>
1713 http://permalink.gmane.org/gmane.os.cygwin.patches/2121
1715 /* Create a pipe, and return handles to the read and write ends,
1716 just like CreatePipe, but ensure that the write end permits
1717 FILE_READ_ATTRIBUTES access, on later versions of win32 where
1718 this is supported. This access is needed by NtQueryInformationFile,
1719 which is used to implement select and nonblocking writes.
1720 Note that the return value is either NO_ERROR or GetLastError,
1721 unlike CreatePipe, which returns a bool for success or failure. */
1723 create_selectable_pipe (PHANDLE read_pipe_ptr, PHANDLE write_pipe_ptr,
1724 LPSECURITY_ATTRIBUTES sa_ptr, DWORD psize,
1725 DWORD dwReadMode, DWORD dwWriteMode)
1727 /* Default to error. */
1728 *read_pipe_ptr = *write_pipe_ptr = INVALID_HANDLE_VALUE;
1730 HANDLE read_pipe = INVALID_HANDLE_VALUE, write_pipe = INVALID_HANDLE_VALUE;
1732 /* Ensure that there is enough pipe buffer space for atomic writes. */
1733 if (psize < PIPE_BUF)
1736 char pipename[MAX_PATH];
1738 /* Retry CreateNamedPipe as long as the pipe name is in use.
1739 * Retrying will probably never be necessary, but we want
1740 * to be as robust as possible. */
1743 static volatile LONG pipe_unique_id;
1745 snprintf (pipename, sizeof pipename, "\\\\.\\pipe\\gnunet-%d-%ld",
1746 getpid (), InterlockedIncrement ((LONG *) & pipe_unique_id));
1748 LOG (GNUNET_ERROR_TYPE_DEBUG,
1749 "CreateNamedPipe: name = %s, size = %lu\n", pipename, psize);
1751 /* Use CreateNamedPipe instead of CreatePipe, because the latter
1752 * returns a write handle that does not permit FILE_READ_ATTRIBUTES
1753 * access, on versions of win32 earlier than WinXP SP2.
1754 * CreatePipe also stupidly creates a full duplex pipe, which is
1755 * a waste, since only a single direction is actually used.
1756 * It's important to only allow a single instance, to ensure that
1757 * the pipe was not created earlier by some other process, even if
1758 * the pid has been reused. We avoid FILE_FLAG_FIRST_PIPE_INSTANCE
1759 * because that is only available for Win2k SP2 and WinXP. */
1760 read_pipe = CreateNamedPipeA (pipename, PIPE_ACCESS_INBOUND | dwReadMode, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, /* max instances */
1761 psize, /* output buffer size */
1762 psize, /* input buffer size */
1763 NMPWAIT_USE_DEFAULT_WAIT, sa_ptr);
1765 if (read_pipe != INVALID_HANDLE_VALUE)
1768 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe read handle = %p\n", read_pipe);
1773 DWORD err = GetLastError ();
1777 case ERROR_PIPE_BUSY:
1778 /* The pipe is already open with compatible parameters.
1779 * Pick a new name and retry. */
1781 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe busy, retrying\n");
1784 case ERROR_ACCESS_DENIED:
1785 /* The pipe is already open with incompatible parameters.
1786 * Pick a new name and retry. */
1788 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe access denied, retrying\n");
1791 case ERROR_CALL_NOT_IMPLEMENTED:
1792 /* We are on an older Win9x platform without named pipes.
1793 * Return an anonymous pipe as the best approximation. */
1795 LOG (GNUNET_ERROR_TYPE_DEBUG,
1796 "CreateNamedPipe not implemented, resorting to "
1797 "CreatePipe: size = %lu\n", psize);
1799 if (CreatePipe (read_pipe_ptr, write_pipe_ptr, sa_ptr, psize))
1802 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe read handle = %p\n",
1804 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe write handle = %p\n",
1809 err = GetLastError ();
1810 LOG (GNUNET_ERROR_TYPE_ERROR, "CreatePipe failed: %d\n", err);
1813 LOG (GNUNET_ERROR_TYPE_ERROR, "CreateNamedPipe failed: %d\n", err);
1819 LOG (GNUNET_ERROR_TYPE_DEBUG, "CreateFile: name = %s\n", pipename);
1822 /* Open the named pipe for writing.
1823 * Be sure to permit FILE_READ_ATTRIBUTES access. */
1824 write_pipe = CreateFileA (pipename, GENERIC_WRITE | FILE_READ_ATTRIBUTES, 0, /* share mode */
1825 sa_ptr, OPEN_EXISTING, dwWriteMode, /* flags and attributes */
1826 0); /* handle to template file */
1828 if (write_pipe == INVALID_HANDLE_VALUE)
1831 DWORD err = GetLastError ();
1834 LOG (GNUNET_ERROR_TYPE_DEBUG, "CreateFile failed: %d\n", err);
1836 CloseHandle (read_pipe);
1840 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe write handle = %p\n", write_pipe);
1843 *read_pipe_ptr = read_pipe;
1844 *write_pipe_ptr = write_pipe;
1850 * Creates an interprocess channel
1852 * @param blocking creates an asynchronous pipe if set to GNUNET_NO
1853 * @param inherit_read inherit the parent processes stdin (only for windows)
1854 * @param inherit_write inherit the parent processes stdout (only for windows)
1856 * @return handle to the new pipe, NULL on error
1858 struct GNUNET_DISK_PipeHandle *
1859 GNUNET_DISK_pipe (int blocking, int inherit_read, int inherit_write)
1861 struct GNUNET_DISK_PipeHandle *p;
1862 struct GNUNET_DISK_FileHandle *fds;
1864 p = GNUNET_malloc (sizeof (struct GNUNET_DISK_PipeHandle) +
1865 2 * sizeof (struct GNUNET_DISK_FileHandle));
1866 fds = (struct GNUNET_DISK_FileHandle *) &p[1];
1879 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
1884 p->fd[0]->fd = fd[0];
1885 p->fd[1]->fd = fd[1];
1887 flags = fcntl (fd[0], F_GETFL);
1889 flags |= O_NONBLOCK;
1890 if (0 > fcntl (fd[0], F_SETFL, flags))
1892 flags = fcntl (fd[0], F_GETFD);
1893 flags |= FD_CLOEXEC;
1894 if (0 > fcntl (fd[0], F_SETFD, flags))
1897 flags = fcntl (fd[1], F_GETFL);
1899 flags |= O_NONBLOCK;
1900 if (0 > fcntl (fd[1], F_SETFL, flags))
1902 flags = fcntl (fd[1], F_GETFD);
1903 flags |= FD_CLOEXEC;
1904 if (0 > fcntl (fd[1], F_SETFD, flags))
1909 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fcntl");
1910 GNUNET_break (0 == close (p->fd[0]->fd));
1911 GNUNET_break (0 == close (p->fd[1]->fd));
1921 create_selectable_pipe (&p->fd[0]->h, &p->fd[1]->h, NULL, 0,
1922 FILE_FLAG_OVERLAPPED, FILE_FLAG_OVERLAPPED);
1926 SetErrnoFromWinError (GetLastError ());
1929 if (!DuplicateHandle
1930 (GetCurrentProcess (), p->fd[0]->h, GetCurrentProcess (), &tmp_handle,
1931 0, inherit_read == GNUNET_YES ? TRUE : FALSE, DUPLICATE_SAME_ACCESS))
1933 SetErrnoFromWinError (GetLastError ());
1934 CloseHandle (p->fd[0]->h);
1935 CloseHandle (p->fd[1]->h);
1939 CloseHandle (p->fd[0]->h);
1940 p->fd[0]->h = tmp_handle;
1942 if (!DuplicateHandle
1943 (GetCurrentProcess (), p->fd[1]->h, GetCurrentProcess (), &tmp_handle,
1944 0, inherit_write == GNUNET_YES ? TRUE : FALSE, DUPLICATE_SAME_ACCESS))
1946 SetErrnoFromWinError (GetLastError ());
1947 CloseHandle (p->fd[0]->h);
1948 CloseHandle (p->fd[1]->h);
1952 CloseHandle (p->fd[1]->h);
1953 p->fd[1]->h = tmp_handle;
1959 SetNamedPipeHandleState (p->fd[0]->h, &mode, NULL, NULL);
1960 SetNamedPipeHandleState (p->fd[1]->h, &mode, NULL, NULL);
1961 /* this always fails on Windows 95, so we don't care about error handling */
1963 p->fd[0]->type = GNUNET_PIPE;
1964 p->fd[1]->type = GNUNET_PIPE;
1966 p->fd[0]->oOverlapRead = GNUNET_malloc (sizeof (OVERLAPPED));
1967 p->fd[0]->oOverlapWrite = GNUNET_malloc (sizeof (OVERLAPPED));
1968 p->fd[1]->oOverlapRead = GNUNET_malloc (sizeof (OVERLAPPED));
1969 p->fd[1]->oOverlapWrite = GNUNET_malloc (sizeof (OVERLAPPED));
1971 p->fd[0]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
1972 p->fd[0]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
1974 p->fd[1]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
1975 p->fd[1]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
1983 * Closes an interprocess channel
1985 * @param p pipe to close
1986 * @param end which end of the pipe to close
1987 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1990 GNUNET_DISK_pipe_close_end (struct GNUNET_DISK_PipeHandle *p,
1991 enum GNUNET_DISK_PipeEnd end)
1993 int ret = GNUNET_OK;
1997 if (end == GNUNET_DISK_PIPE_END_READ)
1999 if (!CloseHandle (p->fd[0]->h))
2001 SetErrnoFromWinError (GetLastError ());
2002 ret = GNUNET_SYSERR;
2004 p->fd[0]->h = INVALID_HANDLE_VALUE;
2006 else if (end == GNUNET_DISK_PIPE_END_WRITE)
2008 if (!CloseHandle (p->fd[1]->h))
2010 SetErrnoFromWinError (GetLastError ());
2011 ret = GNUNET_SYSERR;
2013 p->fd[1]->h = INVALID_HANDLE_VALUE;
2018 if (end == GNUNET_DISK_PIPE_END_READ)
2020 if (0 != close (p->fd[0]->fd))
2022 ret = GNUNET_SYSERR;
2027 else if (end == GNUNET_DISK_PIPE_END_WRITE)
2029 if (0 != close (p->fd[1]->fd))
2031 ret = GNUNET_SYSERR;
2042 * Closes an interprocess channel
2044 * @param p pipe to close
2045 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2048 GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p)
2050 int ret = GNUNET_OK;
2054 if (!CloseHandle (p->fd[0]->h))
2056 SetErrnoFromWinError (GetLastError ());
2057 ret = GNUNET_SYSERR;
2059 if (!CloseHandle (p->fd[1]->h))
2061 SetErrnoFromWinError (GetLastError ());
2062 ret = GNUNET_SYSERR;
2067 if (p->fd[0]->fd != -1)
2069 if (0 != close (p->fd[0]->fd))
2071 ret = GNUNET_SYSERR;
2076 if (p->fd[1]->fd != -1)
2078 if (0 != close (p->fd[1]->fd))
2080 ret = GNUNET_SYSERR;
2092 * Creates a named pipe/FIFO and opens it
2093 * @param fn pointer to the name of the named pipe or to NULL
2094 * @param flags open flags
2095 * @param perm access permissions
2096 * @return pipe handle on success, NULL on error
2098 struct GNUNET_DISK_FileHandle *
2099 GNUNET_DISK_npipe_create (char **fn, enum GNUNET_DISK_OpenFlags flags,
2100 enum GNUNET_DISK_AccessPermissions perm)
2103 struct GNUNET_DISK_FileHandle *ret;
2109 if (flags & GNUNET_DISK_OPEN_READWRITE)
2110 openMode = PIPE_ACCESS_DUPLEX;
2111 else if (flags & GNUNET_DISK_OPEN_READ)
2112 openMode = PIPE_ACCESS_INBOUND;
2113 else if (flags & GNUNET_DISK_OPEN_WRITE)
2114 openMode = PIPE_ACCESS_OUTBOUND;
2116 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
2117 openMode |= FILE_FLAG_FIRST_PIPE_INSTANCE;
2126 GNUNET_asprintf (&name, "\\\\.\\pipe\\%.246s", fn);
2128 LOG (GNUNET_ERROR_TYPE_DEBUG,
2129 "Trying to create an instance of named pipe `%s'\n", name);
2131 h = CreateNamedPipe (name, openMode | FILE_FLAG_OVERLAPPED,
2132 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 2, 1, 1,
2137 GNUNET_asprintf (fn, "\\\\.\\pipe\\gnunet-%llu",
2138 GNUNET_CRYPTO_random_u64
2139 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
2141 LOG (GNUNET_ERROR_TYPE_DEBUG,
2142 "Trying to create unique named pipe `%s'\n", *fn);
2144 h = CreateNamedPipe (*fn,
2145 openMode | FILE_FLAG_OVERLAPPED |
2146 FILE_FLAG_FIRST_PIPE_INSTANCE,
2147 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 2, 1, 1,
2150 error_code = GetLastError ();
2153 /* don't re-set name to NULL yet */
2154 if (h == INVALID_HANDLE_VALUE)
2156 SetErrnoFromWinError (error_code);
2158 LOG (GNUNET_ERROR_TYPE_DEBUG,
2159 "Pipe creation have failed because of %d, errno is %d\n",
2165 LOG (GNUNET_ERROR_TYPE_DEBUG,
2166 "Pipe was to be unique, considering re-creation\n");
2170 if (error_code != ERROR_ACCESS_DENIED
2171 && error_code != ERROR_PIPE_BUSY)
2176 LOG (GNUNET_ERROR_TYPE_DEBUG,
2177 "Pipe name was not unique, trying again\n");
2187 ret = GNUNET_malloc (sizeof (*ret));
2189 ret->type = GNUNET_PIPE;
2191 ret->oOverlapRead = GNUNET_malloc (sizeof (OVERLAPPED));
2192 ret->oOverlapWrite = GNUNET_malloc (sizeof (OVERLAPPED));
2194 ret->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2195 ret->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2201 char dir[] = "/tmp/gnunet-pipe-XXXXXX";
2203 if (mkdtemp (dir) == NULL)
2205 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "mkdtemp");
2208 GNUNET_asprintf (fn, "%s/child-control", dir);
2211 if (mkfifo (*fn, translate_unix_perms (perm)) == -1)
2213 if ((errno != EEXIST) || (0 != (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)))
2217 flags = flags & (~GNUNET_DISK_OPEN_FAILIFEXISTS);
2218 return GNUNET_DISK_file_open (*fn, flags, perm);
2224 * Opens already existing named pipe/FIFO
2226 * @param fn name of an existing named pipe
2227 * @param flags open flags
2228 * @param perm access permissions
2229 * @return pipe handle on success, NULL on error
2231 struct GNUNET_DISK_FileHandle *
2232 GNUNET_DISK_npipe_open (const char *fn, enum GNUNET_DISK_OpenFlags flags,
2233 enum GNUNET_DISK_AccessPermissions perm)
2236 struct GNUNET_DISK_FileHandle *ret;
2241 if (flags & GNUNET_DISK_OPEN_READWRITE)
2242 openMode = GENERIC_WRITE | GENERIC_READ;
2243 else if (flags & GNUNET_DISK_OPEN_READ)
2244 openMode = GENERIC_READ;
2245 else if (flags & GNUNET_DISK_OPEN_WRITE)
2246 openMode = GENERIC_WRITE;
2248 h = CreateFile (fn, openMode, 0, NULL, OPEN_EXISTING,
2249 FILE_FLAG_OVERLAPPED | FILE_READ_ATTRIBUTES, NULL);
2250 if (h == INVALID_HANDLE_VALUE)
2252 SetErrnoFromWinError (GetLastError ());
2256 ret = GNUNET_malloc (sizeof (*ret));
2258 ret->type = GNUNET_PIPE;
2259 ret->oOverlapRead = GNUNET_malloc (sizeof (OVERLAPPED));
2260 ret->oOverlapWrite = GNUNET_malloc (sizeof (OVERLAPPED));
2261 ret->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2262 ret->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2266 flags = flags & (~GNUNET_DISK_OPEN_FAILIFEXISTS);
2267 return GNUNET_DISK_file_open (fn, flags, perm);
2272 * Closes a named pipe/FIFO
2273 * @param pipe named pipe
2274 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2277 GNUNET_DISK_npipe_close (struct GNUNET_DISK_FileHandle *pipe)
2280 return close (pipe->fd) == 0 ? GNUNET_OK : GNUNET_SYSERR;
2284 ret = CloseHandle (pipe->h);
2287 SetErrnoFromWinError (GetLastError ());
2288 return GNUNET_SYSERR;
2297 * Get the handle to a particular pipe end
2300 * @param n end to access
2301 * @return handle for the respective end
2303 const struct GNUNET_DISK_FileHandle *
2304 GNUNET_DISK_pipe_handle (const struct GNUNET_DISK_PipeHandle *p,
2305 enum GNUNET_DISK_PipeEnd n)
2309 case GNUNET_DISK_PIPE_END_READ:
2310 case GNUNET_DISK_PIPE_END_WRITE:
2320 * Retrieve OS file handle
2322 * @param fh GNUnet file descriptor
2323 * @param dst destination buffer
2324 * @param dst_len length of dst
2325 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2328 GNUNET_DISK_internal_file_handle_ (const struct GNUNET_DISK_FileHandle *fh,
2329 void *dst, size_t dst_len)
2332 if (dst_len < sizeof (HANDLE))
2333 return GNUNET_SYSERR;
2334 *((HANDLE *) dst) = fh->h;
2336 if (dst_len < sizeof (int))
2337 return GNUNET_SYSERR;
2338 *((int *) dst) = fh->fd;