simplify filesys.c via gnulib's select and fstat modules
[bpt/guile.git] / libguile / filesys.c
1 /* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2004, 2006,
2 * 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public License
6 * as published by the Free Software Foundation; either version 3 of
7 * the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 * 02110-1301 USA
18 */
19
20
21 \f
22 /* This file contains POSIX file system access procedures. Procedures
23 essential to the compiler and run-time (`stat', `canonicalize-path',
24 etc.) are compiled even with `--disable-posix'. */
25
26
27 /* See stime.c for comments on why _POSIX_C_SOURCE is not always defined. */
28 #define _LARGEFILE64_SOURCE /* ask for stat64 etc */
29 #ifdef __hpux
30 #define _POSIX_C_SOURCE 199506L /* for readdir_r */
31 #endif
32
33 #ifdef HAVE_CONFIG_H
34 # include <config.h>
35 #endif
36
37 #include <alloca.h>
38
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <errno.h>
42
43 #include "libguile/_scm.h"
44 #include "libguile/smob.h"
45 #include "libguile/feature.h"
46 #include "libguile/fports.h"
47 #include "libguile/private-gc.h" /* for SCM_MAX */
48 #include "libguile/strings.h"
49 #include "libguile/vectors.h"
50 #include "libguile/dynwind.h"
51
52 #include "libguile/validate.h"
53 #include "libguile/filesys.h"
54
55 \f
56 #ifdef HAVE_IO_H
57 #include <io.h>
58 #endif
59
60 #ifdef HAVE_DIRECT_H
61 #include <direct.h>
62 #endif
63
64 #ifdef TIME_WITH_SYS_TIME
65 # include <sys/time.h>
66 # include <time.h>
67 #else
68 # if HAVE_SYS_TIME_H
69 # include <sys/time.h>
70 # else
71 # include <time.h>
72 # endif
73 #endif
74
75 #ifdef HAVE_UNISTD_H
76 #include <unistd.h>
77 #endif
78
79 #ifdef LIBC_H_WITH_UNISTD_H
80 #include <libc.h>
81 #endif
82
83 #include <sys/select.h>
84
85 #ifdef HAVE_STRING_H
86 #include <string.h>
87 #endif
88
89 #include <sys/types.h>
90 #include <sys/stat.h>
91 #include <fcntl.h>
92
93 #ifdef HAVE_PWD_H
94 #include <pwd.h>
95 #endif
96
97 #include <dirent.h>
98
99 #define NAMLEN(dirent) strlen ((dirent)->d_name)
100
101 /* Some more definitions for the native Windows port. */
102 #ifdef __MINGW32__
103 # define fsync(fd) _commit (fd)
104 #endif /* __MINGW32__ */
105
106
107 \f
108
109 /* Two helper macros for an often used pattern */
110
111 #define STRING_SYSCALL(str,cstr,code) \
112 do { \
113 int eno; \
114 char *cstr = scm_to_locale_string (str); \
115 SCM_SYSCALL (code); \
116 eno = errno; free (cstr); errno = eno; \
117 } while (0)
118
119 #define STRING2_SYSCALL(str1,cstr1,str2,cstr2,code) \
120 do { \
121 int eno; \
122 char *cstr1, *cstr2; \
123 scm_dynwind_begin (0); \
124 cstr1 = scm_to_locale_string (str1); \
125 scm_dynwind_free (cstr1); \
126 cstr2 = scm_to_locale_string (str2); \
127 scm_dynwind_free (cstr2); \
128 SCM_SYSCALL (code); \
129 eno = errno; scm_dynwind_end (); errno = eno; \
130 } while (0)
131
132 \f
133
134 #ifdef HAVE_POSIX
135
136 /* {Permissions}
137 */
138
139 #ifdef HAVE_CHOWN
140 SCM_DEFINE (scm_chown, "chown", 3, 0, 0,
141 (SCM object, SCM owner, SCM group),
142 "Change the ownership and group of the file referred to by @var{object} to\n"
143 "the integer values @var{owner} and @var{group}. @var{object} can be\n"
144 "a string containing a file name or, if the platform\n"
145 "supports fchown, a port or integer file descriptor\n"
146 "which is open on the file. The return value\n"
147 "is unspecified.\n\n"
148 "If @var{object} is a symbolic link, either the\n"
149 "ownership of the link or the ownership of the referenced file will be\n"
150 "changed depending on the operating system (lchown is\n"
151 "unsupported at present). If @var{owner} or @var{group} is specified\n"
152 "as @code{-1}, then that ID is not changed.")
153 #define FUNC_NAME s_scm_chown
154 {
155 int rv;
156
157 object = SCM_COERCE_OUTPORT (object);
158
159 #ifdef HAVE_FCHOWN
160 if (scm_is_integer (object) || (SCM_OPFPORTP (object)))
161 {
162 int fdes = (SCM_OPFPORTP (object)?
163 SCM_FPORT_FDES (object) : scm_to_int (object));
164
165 SCM_SYSCALL (rv = fchown (fdes, scm_to_int (owner), scm_to_int (group)));
166 }
167 else
168 #endif
169 {
170 STRING_SYSCALL (object, c_object,
171 rv = chown (c_object,
172 scm_to_int (owner), scm_to_int (group)));
173 }
174 if (rv == -1)
175 SCM_SYSERROR;
176 return SCM_UNSPECIFIED;
177 }
178 #undef FUNC_NAME
179 #endif /* HAVE_CHOWN */
180
181 \f
182
183 SCM_DEFINE (scm_open_fdes, "open-fdes", 2, 1, 0,
184 (SCM path, SCM flags, SCM mode),
185 "Similar to @code{open} but return a file descriptor instead of\n"
186 "a port.")
187 #define FUNC_NAME s_scm_open_fdes
188 {
189 int fd;
190 int iflags;
191 int imode;
192
193 iflags = SCM_NUM2INT (2, flags);
194 imode = SCM_NUM2INT_DEF (3, mode, 0666);
195 STRING_SYSCALL (path, c_path, fd = open_or_open64 (c_path, iflags, imode));
196 if (fd == -1)
197 SCM_SYSERROR;
198 return scm_from_int (fd);
199 }
200 #undef FUNC_NAME
201
202 SCM_DEFINE (scm_open, "open", 2, 1, 0,
203 (SCM path, SCM flags, SCM mode),
204 "Open the file named by @var{path} for reading and/or writing.\n"
205 "@var{flags} is an integer specifying how the file should be opened.\n"
206 "@var{mode} is an integer specifying the permission bits of the file, if\n"
207 "it needs to be created, before the umask is applied. The default is 666\n"
208 "(Unix itself has no default).\n\n"
209 "@var{flags} can be constructed by combining variables using @code{logior}.\n"
210 "Basic flags are:\n\n"
211 "@defvar O_RDONLY\n"
212 "Open the file read-only.\n"
213 "@end defvar\n"
214 "@defvar O_WRONLY\n"
215 "Open the file write-only.\n"
216 "@end defvar\n"
217 "@defvar O_RDWR\n"
218 "Open the file read/write.\n"
219 "@end defvar\n"
220 "@defvar O_APPEND\n"
221 "Append to the file instead of truncating.\n"
222 "@end defvar\n"
223 "@defvar O_CREAT\n"
224 "Create the file if it does not already exist.\n"
225 "@end defvar\n\n"
226 "See the Unix documentation of the @code{open} system call\n"
227 "for additional flags.")
228 #define FUNC_NAME s_scm_open
229 {
230 SCM newpt;
231 char *port_mode;
232 int fd;
233 int iflags;
234
235 fd = scm_to_int (scm_open_fdes (path, flags, mode));
236 iflags = SCM_NUM2INT (2, flags);
237
238 if ((iflags & O_RDWR) == O_RDWR)
239 {
240 /* Opened read-write. */
241 if (iflags & O_APPEND)
242 port_mode = "a+";
243 else if (iflags & O_CREAT)
244 port_mode = "w+";
245 else
246 port_mode = "r+";
247 }
248 else
249 {
250 /* Opened read-only or write-only. */
251 if (iflags & O_APPEND)
252 port_mode = "a";
253 else if (iflags & O_WRONLY)
254 port_mode = "w";
255 else
256 port_mode = "r";
257 }
258
259 newpt = scm_fdes_to_port (fd, port_mode, path);
260 return newpt;
261 }
262 #undef FUNC_NAME
263
264 SCM_DEFINE (scm_close, "close", 1, 0, 0,
265 (SCM fd_or_port),
266 "Similar to close-port (@pxref{Closing, close-port}),\n"
267 "but also works on file descriptors. A side\n"
268 "effect of closing a file descriptor is that any ports using that file\n"
269 "descriptor are moved to a different file descriptor and have\n"
270 "their revealed counts set to zero.")
271 #define FUNC_NAME s_scm_close
272 {
273 int rv;
274 int fd;
275
276 fd_or_port = SCM_COERCE_OUTPORT (fd_or_port);
277
278 if (SCM_PORTP (fd_or_port))
279 return scm_close_port (fd_or_port);
280 fd = scm_to_int (fd_or_port);
281 scm_evict_ports (fd); /* see scsh manual. */
282 SCM_SYSCALL (rv = close (fd));
283 /* following scsh, closing an already closed file descriptor is
284 not an error. */
285 if (rv < 0 && errno != EBADF)
286 SCM_SYSERROR;
287 return scm_from_bool (rv >= 0);
288 }
289 #undef FUNC_NAME
290
291 SCM_DEFINE (scm_close_fdes, "close-fdes", 1, 0, 0,
292 (SCM fd),
293 "A simple wrapper for the @code{close} system call.\n"
294 "Close file descriptor @var{fd}, which must be an integer.\n"
295 "Unlike close (@pxref{Ports and File Descriptors, close}),\n"
296 "the file descriptor will be closed even if a port is using it.\n"
297 "The return value is unspecified.")
298 #define FUNC_NAME s_scm_close_fdes
299 {
300 int c_fd;
301 int rv;
302
303 c_fd = scm_to_int (fd);
304 SCM_SYSCALL (rv = close (c_fd));
305 if (rv < 0)
306 SCM_SYSERROR;
307 return SCM_UNSPECIFIED;
308 }
309 #undef FUNC_NAME
310
311 #endif /* HAVE_POSIX */
312
313 \f
314 /* {Files}
315 */
316
317 SCM_SYMBOL (scm_sym_regular, "regular");
318 SCM_SYMBOL (scm_sym_directory, "directory");
319 #ifdef S_ISLNK
320 SCM_SYMBOL (scm_sym_symlink, "symlink");
321 #endif
322 SCM_SYMBOL (scm_sym_block_special, "block-special");
323 SCM_SYMBOL (scm_sym_char_special, "char-special");
324 SCM_SYMBOL (scm_sym_fifo, "fifo");
325 SCM_SYMBOL (scm_sym_sock, "socket");
326 SCM_SYMBOL (scm_sym_unknown, "unknown");
327
328 static SCM
329 scm_stat2scm (struct stat_or_stat64 *stat_temp)
330 {
331 SCM ans = scm_c_make_vector (18, SCM_UNSPECIFIED);
332
333 SCM_SIMPLE_VECTOR_SET(ans, 0, scm_from_ulong (stat_temp->st_dev));
334 SCM_SIMPLE_VECTOR_SET(ans, 1, scm_from_ino_t_or_ino64_t (stat_temp->st_ino));
335 SCM_SIMPLE_VECTOR_SET(ans, 2, scm_from_ulong (stat_temp->st_mode));
336 SCM_SIMPLE_VECTOR_SET(ans, 3, scm_from_ulong (stat_temp->st_nlink));
337 SCM_SIMPLE_VECTOR_SET(ans, 4, scm_from_ulong (stat_temp->st_uid));
338 SCM_SIMPLE_VECTOR_SET(ans, 5, scm_from_ulong (stat_temp->st_gid));
339 #ifdef HAVE_STRUCT_STAT_ST_RDEV
340 SCM_SIMPLE_VECTOR_SET(ans, 6, scm_from_ulong (stat_temp->st_rdev));
341 #else
342 SCM_SIMPLE_VECTOR_SET(ans, 6, SCM_BOOL_F);
343 #endif
344 SCM_SIMPLE_VECTOR_SET(ans, 7, scm_from_off_t_or_off64_t (stat_temp->st_size));
345 SCM_SIMPLE_VECTOR_SET(ans, 8, scm_from_ulong (stat_temp->st_atime));
346 SCM_SIMPLE_VECTOR_SET(ans, 9, scm_from_ulong (stat_temp->st_mtime));
347 SCM_SIMPLE_VECTOR_SET(ans, 10, scm_from_ulong (stat_temp->st_ctime));
348 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
349 SCM_SIMPLE_VECTOR_SET(ans, 11, scm_from_ulong (stat_temp->st_blksize));
350 #else
351 SCM_SIMPLE_VECTOR_SET(ans, 11, scm_from_ulong (4096L));
352 #endif
353 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
354 SCM_SIMPLE_VECTOR_SET(ans, 12, scm_from_blkcnt_t_or_blkcnt64_t (stat_temp->st_blocks));
355 #else
356 SCM_SIMPLE_VECTOR_SET(ans, 12, SCM_BOOL_F);
357 #endif
358 {
359 int mode = stat_temp->st_mode;
360
361 if (S_ISREG (mode))
362 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_regular);
363 else if (S_ISDIR (mode))
364 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_directory);
365 #ifdef S_ISLNK
366 /* systems without symlinks probably don't have S_ISLNK */
367 else if (S_ISLNK (mode))
368 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_symlink);
369 #endif
370 else if (S_ISBLK (mode))
371 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_block_special);
372 else if (S_ISCHR (mode))
373 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_char_special);
374 else if (S_ISFIFO (mode))
375 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_fifo);
376 #ifdef S_ISSOCK
377 else if (S_ISSOCK (mode))
378 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_sock);
379 #endif
380 else
381 SCM_SIMPLE_VECTOR_SET(ans, 13, scm_sym_unknown);
382
383 SCM_SIMPLE_VECTOR_SET(ans, 14, scm_from_int ((~S_IFMT) & mode));
384
385 /* the layout of the bits in ve[14] is intended to be portable.
386 If there are systems that don't follow the usual convention,
387 the following could be used:
388
389 tmp = 0;
390 if (S_ISUID & mode) tmp += 1;
391 tmp <<= 1;
392 if (S_IRGRP & mode) tmp += 1;
393 tmp <<= 1;
394 if (S_ISVTX & mode) tmp += 1;
395 tmp <<= 1;
396 if (S_IRUSR & mode) tmp += 1;
397 tmp <<= 1;
398 if (S_IWUSR & mode) tmp += 1;
399 tmp <<= 1;
400 if (S_IXUSR & mode) tmp += 1;
401 tmp <<= 1;
402 if (S_IWGRP & mode) tmp += 1;
403 tmp <<= 1;
404 if (S_IXGRP & mode) tmp += 1;
405 tmp <<= 1;
406 if (S_IROTH & mode) tmp += 1;
407 tmp <<= 1;
408 if (S_IWOTH & mode) tmp += 1;
409 tmp <<= 1;
410 if (S_IXOTH & mode) tmp += 1;
411
412 SCM_SIMPLE_VECTOR_SET(ans, 14, scm_from_int (tmp));
413
414 */
415 }
416 #ifdef HAVE_STRUCT_STAT_ST_ATIM
417 SCM_SIMPLE_VECTOR_SET(ans, 15, scm_from_long (stat_temp->st_atim.tv_nsec));
418 #else
419 SCM_SIMPLE_VECTOR_SET(ans, 15, SCM_I_MAKINUM (0));
420 #endif
421 #ifdef HAVE_STRUCT_STAT_ST_MTIM
422 SCM_SIMPLE_VECTOR_SET(ans, 16, scm_from_long (stat_temp->st_mtim.tv_nsec));
423 #else
424 SCM_SIMPLE_VECTOR_SET(ans, 16, SCM_I_MAKINUM (0));
425 #endif
426 #ifdef HAVE_STRUCT_STAT_ST_CTIM
427 SCM_SIMPLE_VECTOR_SET(ans, 17, scm_from_ulong (stat_temp->st_ctim.tv_sec));
428 #else
429 SCM_SIMPLE_VECTOR_SET(ans, 17, SCM_I_MAKINUM (0));
430 #endif
431
432 return ans;
433 }
434
435 static int
436 is_file_name_separator (SCM c)
437 {
438 if (scm_is_eq (c, SCM_MAKE_CHAR ('/')))
439 return 1;
440 #ifdef __MINGW32__
441 if (scm_is_eq (c, SCM_MAKE_CHAR ('\\')))
442 return 1;
443 #endif
444 return 0;
445 }
446
447 SCM_DEFINE (scm_stat, "stat", 1, 1, 0,
448 (SCM object, SCM exception_on_error),
449 "Return an object containing various information about the file\n"
450 "determined by @var{object}. @var{object} can be a string containing\n"
451 "a file name or a port or integer file descriptor which is open\n"
452 "on a file (in which case @code{fstat} is used as the underlying\n"
453 "system call).\n"
454 "\n"
455 "If the optional @var{exception_on_error} argument is true, which\n"
456 "is the default, an exception will be raised if the underlying\n"
457 "system call returns an error, for example if the file is not\n"
458 "found or is not readable. Otherwise, an error will cause\n"
459 "@code{stat} to return @code{#f}."
460 "\n"
461 "The object returned by a successful call to @code{stat} can be\n"
462 "passed as a single parameter to the following procedures, all of\n"
463 "which return integers:\n"
464 "\n"
465 "@table @code\n"
466 "@item stat:dev\n"
467 "The device containing the file.\n"
468 "@item stat:ino\n"
469 "The file serial number, which distinguishes this file from all\n"
470 "other files on the same device.\n"
471 "@item stat:mode\n"
472 "The mode of the file. This includes file type information and\n"
473 "the file permission bits. See @code{stat:type} and\n"
474 "@code{stat:perms} below.\n"
475 "@item stat:nlink\n"
476 "The number of hard links to the file.\n"
477 "@item stat:uid\n"
478 "The user ID of the file's owner.\n"
479 "@item stat:gid\n"
480 "The group ID of the file.\n"
481 "@item stat:rdev\n"
482 "Device ID; this entry is defined only for character or block\n"
483 "special files.\n"
484 "@item stat:size\n"
485 "The size of a regular file in bytes.\n"
486 "@item stat:atime\n"
487 "The last access time for the file.\n"
488 "@item stat:mtime\n"
489 "The last modification time for the file.\n"
490 "@item stat:ctime\n"
491 "The last modification time for the attributes of the file.\n"
492 "@item stat:blksize\n"
493 "The optimal block size for reading or writing the file, in\n"
494 "bytes.\n"
495 "@item stat:blocks\n"
496 "The amount of disk space that the file occupies measured in\n"
497 "units of 512 byte blocks.\n"
498 "@end table\n"
499 "\n"
500 "In addition, the following procedures return the information\n"
501 "from stat:mode in a more convenient form:\n"
502 "\n"
503 "@table @code\n"
504 "@item stat:type\n"
505 "A symbol representing the type of file. Possible values are\n"
506 "regular, directory, symlink, block-special, char-special, fifo,\n"
507 "socket and unknown\n"
508 "@item stat:perms\n"
509 "An integer representing the access permission bits.\n"
510 "@end table")
511 #define FUNC_NAME s_scm_stat
512 {
513 int rv;
514 int fdes;
515 struct stat_or_stat64 stat_temp;
516
517 if (scm_is_integer (object))
518 {
519 SCM_SYSCALL (rv = fstat_or_fstat64 (scm_to_int (object), &stat_temp));
520 }
521 else if (scm_is_string (object))
522 {
523 char *file = scm_to_locale_string (object);
524 SCM_SYSCALL (rv = stat_or_stat64 (file, &stat_temp));
525 free (file);
526 }
527 else
528 {
529 object = SCM_COERCE_OUTPORT (object);
530 SCM_VALIDATE_OPFPORT (1, object);
531 fdes = SCM_FPORT_FDES (object);
532 SCM_SYSCALL (rv = fstat_or_fstat64 (fdes, &stat_temp));
533 }
534
535 if (rv == -1)
536 {
537 if (SCM_UNBNDP (exception_on_error) || scm_is_true (exception_on_error))
538 {
539 int en = errno;
540 SCM_SYSERROR_MSG ("~A: ~S",
541 scm_list_2 (scm_strerror (scm_from_int (en)),
542 object),
543 en);
544 }
545 else
546 return SCM_BOOL_F;
547 }
548 return scm_stat2scm (&stat_temp);
549 }
550 #undef FUNC_NAME
551
552 #ifdef HAVE_LSTAT
553 SCM_DEFINE (scm_lstat, "lstat", 1, 0, 0,
554 (SCM str),
555 "Similar to @code{stat}, but does not follow symbolic links, i.e.,\n"
556 "it will return information about a symbolic link itself, not the\n"
557 "file it points to. @var{str} must be a string.")
558 #define FUNC_NAME s_scm_lstat
559 {
560 int rv;
561 struct stat_or_stat64 stat_temp;
562
563 STRING_SYSCALL (str, c_str, rv = lstat_or_lstat64 (c_str, &stat_temp));
564 if (rv != 0)
565 {
566 int en = errno;
567
568 SCM_SYSERROR_MSG ("~A: ~S",
569 scm_list_2 (scm_strerror (scm_from_int (en)), str),
570 en);
571 }
572 return scm_stat2scm (&stat_temp);
573 }
574 #undef FUNC_NAME
575 #endif /* HAVE_LSTAT */
576
577 \f
578 #ifdef HAVE_POSIX
579
580 /* {Modifying Directories}
581 */
582
583 #ifdef HAVE_LINK
584 SCM_DEFINE (scm_link, "link", 2, 0, 0,
585 (SCM oldpath, SCM newpath),
586 "Creates a new name @var{newpath} in the file system for the\n"
587 "file named by @var{oldpath}. If @var{oldpath} is a symbolic\n"
588 "link, the link may or may not be followed depending on the\n"
589 "system.")
590 #define FUNC_NAME s_scm_link
591 {
592 int val;
593
594 STRING2_SYSCALL (oldpath, c_oldpath,
595 newpath, c_newpath,
596 val = link (c_oldpath, c_newpath));
597 if (val != 0)
598 SCM_SYSERROR;
599 return SCM_UNSPECIFIED;
600 }
601 #undef FUNC_NAME
602 #endif /* HAVE_LINK */
603
604 \f
605 /* {Navigating Directories}
606 */
607
608
609 SCM_DEFINE (scm_chdir, "chdir", 1, 0, 0,
610 (SCM str),
611 "Change the current working directory to @var{str}.\n"
612 "The return value is unspecified.")
613 #define FUNC_NAME s_scm_chdir
614 {
615 int ans;
616
617 STRING_SYSCALL (str, c_str, ans = chdir (c_str));
618 if (ans != 0)
619 SCM_SYSERROR;
620 return SCM_UNSPECIFIED;
621 }
622 #undef FUNC_NAME
623
624 \f
625
626 /* check that element is a port or file descriptor. if it's a port
627 and its buffer is ready for use, add it to the ports_ready list.
628 otherwise add its file descriptor to *set. the type of list can be
629 determined from pos: SCM_ARG1 for reads, SCM_ARG2 for writes,
630 SCM_ARG3 for excepts. */
631 static int
632 set_element (fd_set *set, SCM *ports_ready, SCM element, int pos)
633 {
634 int fd;
635
636 if (scm_is_integer (element))
637 {
638 fd = scm_to_int (element);
639 }
640 else
641 {
642 int use_buf = 0;
643
644 element = SCM_COERCE_OUTPORT (element);
645 SCM_ASSERT (SCM_OPFPORTP (element), element, pos, "select");
646 if (pos == SCM_ARG1)
647 {
648 /* check whether port has buffered input. */
649 scm_t_port *pt = SCM_PTAB_ENTRY (element);
650
651 if (pt->read_pos < pt->read_end)
652 use_buf = 1;
653 }
654 else if (pos == SCM_ARG2)
655 {
656 /* check whether port's output buffer has room. */
657 scm_t_port *pt = SCM_PTAB_ENTRY (element);
658
659 /* > 1 since writing the last byte in the buffer causes flush. */
660 if (pt->write_end - pt->write_pos > 1)
661 use_buf = 1;
662 }
663 fd = use_buf ? -1 : SCM_FPORT_FDES (element);
664 }
665 if (fd == -1)
666 *ports_ready = scm_cons (element, *ports_ready);
667 else
668 FD_SET (fd, set);
669 return fd;
670 }
671
672 /* check list_or_vec, a list or vector of ports or file descriptors,
673 adding each member to either the ports_ready list (if it's a port
674 with a usable buffer) or to *set. the kind of list_or_vec can be
675 determined from pos: SCM_ARG1 for reads, SCM_ARG2 for writes,
676 SCM_ARG3 for excepts. */
677 static int
678 fill_select_type (fd_set *set, SCM *ports_ready, SCM list_or_vec, int pos)
679 {
680 int max_fd = 0;
681
682 if (scm_is_simple_vector (list_or_vec))
683 {
684 int i = SCM_SIMPLE_VECTOR_LENGTH (list_or_vec);
685
686 while (--i >= 0)
687 {
688 int fd = set_element (set, ports_ready,
689 SCM_SIMPLE_VECTOR_REF (list_or_vec, i), pos);
690
691 if (fd > max_fd)
692 max_fd = fd;
693 }
694 }
695 else
696 {
697 while (!SCM_NULL_OR_NIL_P (list_or_vec))
698 {
699 int fd = set_element (set, ports_ready, SCM_CAR (list_or_vec), pos);
700
701 if (fd > max_fd)
702 max_fd = fd;
703 list_or_vec = SCM_CDR (list_or_vec);
704 }
705 }
706
707 return max_fd;
708 }
709
710 /* if element (a file descriptor or port) appears in *set, cons it to
711 list. return list. */
712 static SCM
713 get_element (fd_set *set, SCM element, SCM list)
714 {
715 int fd;
716
717 if (scm_is_integer (element))
718 {
719 fd = scm_to_int (element);
720 }
721 else
722 {
723 fd = SCM_FPORT_FDES (SCM_COERCE_OUTPORT (element));
724 }
725 if (FD_ISSET (fd, set))
726 list = scm_cons (element, list);
727 return list;
728 }
729
730 /* construct component of scm_select return value.
731 set: pointer to set of file descriptors found by select to be ready
732 ports_ready: ports ready due to buffering
733 list_or_vec: original list/vector handed to scm_select.
734 the return value is a list/vector of ready ports/file descriptors.
735 works by finding the objects in list which correspond to members of
736 *set and appending them to ports_ready. result is converted to a
737 vector if list_or_vec is a vector. */
738 static SCM
739 retrieve_select_type (fd_set *set, SCM ports_ready, SCM list_or_vec)
740 {
741 SCM answer_list = ports_ready;
742
743 if (scm_is_simple_vector (list_or_vec))
744 {
745 int i = SCM_SIMPLE_VECTOR_LENGTH (list_or_vec);
746
747 while (--i >= 0)
748 {
749 answer_list = get_element (set,
750 SCM_SIMPLE_VECTOR_REF (list_or_vec, i),
751 answer_list);
752 }
753 return scm_vector (answer_list);
754 }
755 else
756 {
757 /* list_or_vec must be a list. */
758 while (!SCM_NULL_OR_NIL_P (list_or_vec))
759 {
760 answer_list = get_element (set, SCM_CAR (list_or_vec), answer_list);
761 list_or_vec = SCM_CDR (list_or_vec);
762 }
763 return answer_list;
764 }
765 }
766
767 /* Static helper functions above refer to s_scm_select directly as s_select */
768 SCM_DEFINE (scm_select, "select", 3, 2, 0,
769 (SCM reads, SCM writes, SCM excepts, SCM secs, SCM usecs),
770 "This procedure has a variety of uses: waiting for the ability\n"
771 "to provide input, accept output, or the existence of\n"
772 "exceptional conditions on a collection of ports or file\n"
773 "descriptors, or waiting for a timeout to occur.\n"
774 "It also returns if interrupted by a signal.\n\n"
775 "@var{reads}, @var{writes} and @var{excepts} can be lists or\n"
776 "vectors, with each member a port or a file descriptor.\n"
777 "The value returned is a list of three corresponding\n"
778 "lists or vectors containing only the members which meet the\n"
779 "specified requirement. The ability of port buffers to\n"
780 "provide input or accept output is taken into account.\n"
781 "Ordering of the input lists or vectors is not preserved.\n\n"
782 "The optional arguments @var{secs} and @var{usecs} specify the\n"
783 "timeout. Either @var{secs} can be specified alone, as\n"
784 "either an integer or a real number, or both @var{secs} and\n"
785 "@var{usecs} can be specified as integers, in which case\n"
786 "@var{usecs} is an additional timeout expressed in\n"
787 "microseconds. If @var{secs} is omitted or is @code{#f} then\n"
788 "select will wait for as long as it takes for one of the other\n"
789 "conditions to be satisfied.\n\n"
790 "The scsh version of @code{select} differs as follows:\n"
791 "Only vectors are accepted for the first three arguments.\n"
792 "The @var{usecs} argument is not supported.\n"
793 "Multiple values are returned instead of a list.\n"
794 "Duplicates in the input vectors appear only once in output.\n"
795 "An additional @code{select!} interface is provided.")
796 #define FUNC_NAME s_scm_select
797 {
798 struct timeval timeout;
799 struct timeval * time_ptr;
800 fd_set read_set;
801 fd_set write_set;
802 fd_set except_set;
803 int read_count;
804 int write_count;
805 int except_count;
806 /* these lists accumulate ports which are ready due to buffering.
807 their file descriptors don't need to be added to the select sets. */
808 SCM read_ports_ready = SCM_EOL;
809 SCM write_ports_ready = SCM_EOL;
810 int max_fd;
811
812 if (scm_is_simple_vector (reads))
813 {
814 read_count = SCM_SIMPLE_VECTOR_LENGTH (reads);
815 }
816 else
817 {
818 read_count = scm_ilength (reads);
819 SCM_ASSERT (read_count >= 0, reads, SCM_ARG1, FUNC_NAME);
820 }
821 if (scm_is_simple_vector (writes))
822 {
823 write_count = SCM_SIMPLE_VECTOR_LENGTH (writes);
824 }
825 else
826 {
827 write_count = scm_ilength (writes);
828 SCM_ASSERT (write_count >= 0, writes, SCM_ARG2, FUNC_NAME);
829 }
830 if (scm_is_simple_vector (excepts))
831 {
832 except_count = SCM_SIMPLE_VECTOR_LENGTH (excepts);
833 }
834 else
835 {
836 except_count = scm_ilength (excepts);
837 SCM_ASSERT (except_count >= 0, excepts, SCM_ARG3, FUNC_NAME);
838 }
839
840 FD_ZERO (&read_set);
841 FD_ZERO (&write_set);
842 FD_ZERO (&except_set);
843
844 max_fd = fill_select_type (&read_set, &read_ports_ready, reads, SCM_ARG1);
845
846 {
847 int write_max = fill_select_type (&write_set, &write_ports_ready,
848 writes, SCM_ARG2);
849 int except_max = fill_select_type (&except_set, NULL,
850 excepts, SCM_ARG3);
851
852 if (write_max > max_fd)
853 max_fd = write_max;
854 if (except_max > max_fd)
855 max_fd = except_max;
856 }
857
858 /* if there's a port with a ready buffer, don't block, just
859 check for ready file descriptors. */
860 if (!scm_is_null (read_ports_ready) || !scm_is_null (write_ports_ready))
861 {
862 timeout.tv_sec = 0;
863 timeout.tv_usec = 0;
864 time_ptr = &timeout;
865 }
866 else if (SCM_UNBNDP (secs) || scm_is_false (secs))
867 time_ptr = 0;
868 else
869 {
870 if (scm_is_unsigned_integer (secs, 0, ULONG_MAX))
871 {
872 timeout.tv_sec = scm_to_ulong (secs);
873 if (SCM_UNBNDP (usecs))
874 timeout.tv_usec = 0;
875 else
876 timeout.tv_usec = scm_to_long (usecs);
877 }
878 else
879 {
880 double fl = scm_to_double (secs);
881
882 if (!SCM_UNBNDP (usecs))
883 SCM_WRONG_TYPE_ARG (4, secs);
884 if (fl > LONG_MAX)
885 SCM_OUT_OF_RANGE (4, secs);
886 timeout.tv_sec = (long) fl;
887 timeout.tv_usec = (long) ((fl - timeout.tv_sec) * 1000000);
888 }
889 time_ptr = &timeout;
890 }
891
892 {
893 int rv = select (max_fd + 1,
894 &read_set, &write_set, &except_set,
895 time_ptr);
896 if (rv < 0)
897 SCM_SYSERROR;
898 }
899 return scm_list_3 (retrieve_select_type (&read_set, read_ports_ready, reads),
900 retrieve_select_type (&write_set, write_ports_ready, writes),
901 retrieve_select_type (&except_set, SCM_EOL, excepts));
902 }
903 #undef FUNC_NAME
904
905 \f
906
907 #ifdef HAVE_FCNTL
908 SCM_DEFINE (scm_fcntl, "fcntl", 2, 1, 0,
909 (SCM object, SCM cmd, SCM value),
910 "Apply @var{cmd} to the specified file descriptor or the underlying\n"
911 "file descriptor of the specified port. @var{value} is an optional\n"
912 "integer argument.\n\n"
913 "Values for @var{cmd} are:\n\n"
914 "@table @code\n"
915 "@item F_DUPFD\n"
916 "Duplicate a file descriptor\n"
917 "@item F_GETFD\n"
918 "Get flags associated with the file descriptor.\n"
919 "@item F_SETFD\n"
920 "Set flags associated with the file descriptor to @var{value}.\n"
921 "@item F_GETFL\n"
922 "Get flags associated with the open file.\n"
923 "@item F_SETFL\n"
924 "Set flags associated with the open file to @var{value}\n"
925 "@item F_GETOWN\n"
926 "Get the process ID of a socket's owner, for @code{SIGIO} signals.\n"
927 "@item F_SETOWN\n"
928 "Set the process that owns a socket to @var{value}, for @code{SIGIO} signals.\n"
929 "@item FD_CLOEXEC\n"
930 "The value used to indicate the \"close on exec\" flag with @code{F_GETFL} or\n"
931 "@code{F_SETFL}.\n"
932 "@end table")
933 #define FUNC_NAME s_scm_fcntl
934 {
935 int rv;
936 int fdes;
937 int ivalue;
938
939 object = SCM_COERCE_OUTPORT (object);
940
941 if (SCM_OPFPORTP (object))
942 fdes = SCM_FPORT_FDES (object);
943 else
944 fdes = scm_to_int (object);
945
946 if (SCM_UNBNDP (value))
947 ivalue = 0;
948 else
949 ivalue = scm_to_int (value);
950
951 SCM_SYSCALL (rv = fcntl (fdes, scm_to_int (cmd), ivalue));
952 if (rv == -1)
953 SCM_SYSERROR;
954 return scm_from_int (rv);
955 }
956 #undef FUNC_NAME
957 #endif /* HAVE_FCNTL */
958
959 SCM_DEFINE (scm_fsync, "fsync", 1, 0, 0,
960 (SCM object),
961 "Copies any unwritten data for the specified output file\n"
962 "descriptor to disk. If @var{object} is a port, its buffer is\n"
963 "flushed before the underlying file descriptor is fsync'd.\n"
964 "The return value is unspecified.")
965 #define FUNC_NAME s_scm_fsync
966 {
967 int fdes;
968
969 object = SCM_COERCE_OUTPORT (object);
970
971 if (SCM_OPFPORTP (object))
972 {
973 scm_flush (object);
974 fdes = SCM_FPORT_FDES (object);
975 }
976 else
977 fdes = scm_to_int (object);
978
979 if (fsync (fdes) == -1)
980 SCM_SYSERROR;
981 return SCM_UNSPECIFIED;
982 }
983 #undef FUNC_NAME
984
985 #ifdef HAVE_SYMLINK
986 SCM_DEFINE (scm_symlink, "symlink", 2, 0, 0,
987 (SCM oldpath, SCM newpath),
988 "Create a symbolic link named @var{oldpath} with the value\n"
989 "(i.e., pointing to) @var{newpath}. The return value is\n"
990 "unspecified.")
991 #define FUNC_NAME s_scm_symlink
992 {
993 int val;
994
995 STRING2_SYSCALL (oldpath, c_oldpath,
996 newpath, c_newpath,
997 val = symlink (c_oldpath, c_newpath));
998 if (val != 0)
999 SCM_SYSERROR;
1000 return SCM_UNSPECIFIED;
1001 }
1002 #undef FUNC_NAME
1003 #endif /* HAVE_SYMLINK */
1004
1005 #ifdef HAVE_READLINK
1006 SCM_DEFINE (scm_readlink, "readlink", 1, 0, 0,
1007 (SCM path),
1008 "Return the value of the symbolic link named by @var{path} (a\n"
1009 "string), i.e., the file that the link points to.")
1010 #define FUNC_NAME s_scm_readlink
1011 {
1012 int rv;
1013 int size = 100;
1014 char *buf;
1015 SCM result;
1016 char *c_path;
1017
1018 scm_dynwind_begin (0);
1019
1020 c_path = scm_to_locale_string (path);
1021 scm_dynwind_free (c_path);
1022
1023 buf = scm_malloc (size);
1024
1025 while ((rv = readlink (c_path, buf, size)) == size)
1026 {
1027 free (buf);
1028 size *= 2;
1029 buf = scm_malloc (size);
1030 }
1031 if (rv == -1)
1032 {
1033 int save_errno = errno;
1034 free (buf);
1035 errno = save_errno;
1036 SCM_SYSERROR;
1037 }
1038 result = scm_take_locale_stringn (buf, rv);
1039
1040 scm_dynwind_end ();
1041 return result;
1042 }
1043 #undef FUNC_NAME
1044 #endif /* HAVE_READLINK */
1045
1046 SCM_DEFINE (scm_copy_file, "copy-file", 2, 0, 0,
1047 (SCM oldfile, SCM newfile),
1048 "Copy the file specified by @var{oldfile} to @var{newfile}.\n"
1049 "The return value is unspecified.")
1050 #define FUNC_NAME s_scm_copy_file
1051 {
1052 char *c_oldfile, *c_newfile;
1053 int oldfd, newfd;
1054 int n, rv;
1055 char buf[BUFSIZ];
1056 struct stat_or_stat64 oldstat;
1057
1058 scm_dynwind_begin (0);
1059
1060 c_oldfile = scm_to_locale_string (oldfile);
1061 scm_dynwind_free (c_oldfile);
1062 c_newfile = scm_to_locale_string (newfile);
1063 scm_dynwind_free (c_newfile);
1064
1065 oldfd = open_or_open64 (c_oldfile, O_RDONLY | O_BINARY);
1066 if (oldfd == -1)
1067 SCM_SYSERROR;
1068
1069 SCM_SYSCALL (rv = fstat_or_fstat64 (oldfd, &oldstat));
1070 if (rv == -1)
1071 goto err_close_oldfd;
1072
1073 /* use POSIX flags instead of 07777?. */
1074 newfd = open_or_open64 (c_newfile, O_WRONLY | O_CREAT | O_TRUNC,
1075 oldstat.st_mode & 07777);
1076 if (newfd == -1)
1077 {
1078 err_close_oldfd:
1079 close (oldfd);
1080 SCM_SYSERROR;
1081 }
1082
1083 while ((n = read (oldfd, buf, sizeof buf)) > 0)
1084 if (write (newfd, buf, n) != n)
1085 {
1086 close (oldfd);
1087 close (newfd);
1088 SCM_SYSERROR;
1089 }
1090 close (oldfd);
1091 if (close (newfd) == -1)
1092 SCM_SYSERROR;
1093
1094 scm_dynwind_end ();
1095 return SCM_UNSPECIFIED;
1096 }
1097 #undef FUNC_NAME
1098
1099 #endif /* HAVE_POSIX */
1100
1101 \f
1102 /* Essential procedures used in (system base compile). */
1103
1104 #ifdef HAVE_GETCWD
1105 SCM_DEFINE (scm_getcwd, "getcwd", 0, 0, 0,
1106 (),
1107 "Return the name of the current working directory.")
1108 #define FUNC_NAME s_scm_getcwd
1109 {
1110 char *rv;
1111 size_t size = 100;
1112 char *wd;
1113 SCM result;
1114
1115 wd = scm_malloc (size);
1116 while ((rv = getcwd (wd, size)) == 0 && errno == ERANGE)
1117 {
1118 free (wd);
1119 size *= 2;
1120 wd = scm_malloc (size);
1121 }
1122 if (rv == 0)
1123 {
1124 int save_errno = errno;
1125 free (wd);
1126 errno = save_errno;
1127 SCM_SYSERROR;
1128 }
1129 result = scm_from_locale_stringn (wd, strlen (wd));
1130 free (wd);
1131 return result;
1132 }
1133 #undef FUNC_NAME
1134 #endif /* HAVE_GETCWD */
1135
1136 #ifdef HAVE_MKDIR
1137 SCM_DEFINE (scm_mkdir, "mkdir", 1, 1, 0,
1138 (SCM path, SCM mode),
1139 "Create a new directory named by @var{path}. If @var{mode} is omitted\n"
1140 "then the permissions of the directory file are set using the current\n"
1141 "umask. Otherwise they are set to the decimal value specified with\n"
1142 "@var{mode}. The return value is unspecified.")
1143 #define FUNC_NAME s_scm_mkdir
1144 {
1145 int rv;
1146 mode_t mask;
1147
1148 if (SCM_UNBNDP (mode))
1149 {
1150 mask = umask (0);
1151 umask (mask);
1152 STRING_SYSCALL (path, c_path, rv = mkdir (c_path, 0777 ^ mask));
1153 }
1154 else
1155 {
1156 STRING_SYSCALL (path, c_path, rv = mkdir (c_path, scm_to_uint (mode)));
1157 }
1158 if (rv != 0)
1159 SCM_SYSERROR;
1160 return SCM_UNSPECIFIED;
1161 }
1162 #undef FUNC_NAME
1163 #endif /* HAVE_MKDIR */
1164
1165 #ifdef HAVE_RMDIR
1166 SCM_DEFINE (scm_rmdir, "rmdir", 1, 0, 0,
1167 (SCM path),
1168 "Remove the existing directory named by @var{path}. The directory must\n"
1169 "be empty for this to succeed. The return value is unspecified.")
1170 #define FUNC_NAME s_scm_rmdir
1171 {
1172 int val;
1173
1174 STRING_SYSCALL (path, c_path, val = rmdir (c_path));
1175 if (val != 0)
1176 SCM_SYSERROR;
1177 return SCM_UNSPECIFIED;
1178 }
1179 #undef FUNC_NAME
1180 #endif
1181
1182 #ifdef HAVE_RENAME
1183 #define my_rename rename
1184 #else
1185 static int
1186 my_rename (const char *oldname, const char *newname)
1187 {
1188 int rv;
1189
1190 SCM_SYSCALL (rv = link (oldname, newname));
1191 if (rv == 0)
1192 {
1193 SCM_SYSCALL (rv = unlink (oldname));
1194 if (rv != 0)
1195 /* unlink failed. remove new name */
1196 SCM_SYSCALL (unlink (newname));
1197 }
1198 return rv;
1199 }
1200 #endif
1201
1202 SCM_DEFINE (scm_rename, "rename-file", 2, 0, 0,
1203 (SCM oldname, SCM newname),
1204 "Renames the file specified by @var{oldname} to @var{newname}.\n"
1205 "The return value is unspecified.")
1206 #define FUNC_NAME s_scm_rename
1207 {
1208 int rv;
1209
1210 STRING2_SYSCALL (oldname, c_oldname,
1211 newname, c_newname,
1212 rv = my_rename (c_oldname, c_newname));
1213 if (rv != 0)
1214 SCM_SYSERROR;
1215 return SCM_UNSPECIFIED;
1216 }
1217 #undef FUNC_NAME
1218
1219
1220 SCM_DEFINE (scm_delete_file, "delete-file", 1, 0, 0,
1221 (SCM str),
1222 "Deletes (or \"unlinks\") the file specified by @var{str}.")
1223 #define FUNC_NAME s_scm_delete_file
1224 {
1225 int ans;
1226 STRING_SYSCALL (str, c_str, ans = unlink (c_str));
1227 if (ans != 0)
1228 SCM_SYSERROR;
1229 return SCM_UNSPECIFIED;
1230 }
1231 #undef FUNC_NAME
1232
1233 SCM_DEFINE (scm_access, "access?", 2, 0, 0,
1234 (SCM path, SCM how),
1235 "Test accessibility of a file under the real UID and GID of the\n"
1236 "calling process. The return is @code{#t} if @var{path} exists\n"
1237 "and the permissions requested by @var{how} are all allowed, or\n"
1238 "@code{#f} if not.\n"
1239 "\n"
1240 "@var{how} is an integer which is one of the following values,\n"
1241 "or a bitwise-OR (@code{logior}) of multiple values.\n"
1242 "\n"
1243 "@defvar R_OK\n"
1244 "Test for read permission.\n"
1245 "@end defvar\n"
1246 "@defvar W_OK\n"
1247 "Test for write permission.\n"
1248 "@end defvar\n"
1249 "@defvar X_OK\n"
1250 "Test for execute permission.\n"
1251 "@end defvar\n"
1252 "@defvar F_OK\n"
1253 "Test for existence of the file. This is implied by each of the\n"
1254 "other tests, so there's no need to combine it with them.\n"
1255 "@end defvar\n"
1256 "\n"
1257 "It's important to note that @code{access?} does not simply\n"
1258 "indicate what will happen on attempting to read or write a\n"
1259 "file. In normal circumstances it does, but in a set-UID or\n"
1260 "set-GID program it doesn't because @code{access?} tests the\n"
1261 "real ID, whereas an open or execute attempt uses the effective\n"
1262 "ID.\n"
1263 "\n"
1264 "A program which will never run set-UID/GID can ignore the\n"
1265 "difference between real and effective IDs, but for maximum\n"
1266 "generality, especially in library functions, it's best not to\n"
1267 "use @code{access?} to predict the result of an open or execute,\n"
1268 "instead simply attempt that and catch any exception.\n"
1269 "\n"
1270 "The main use for @code{access?} is to let a set-UID/GID program\n"
1271 "determine what the invoking user would have been allowed to do,\n"
1272 "without the greater (or perhaps lesser) privileges afforded by\n"
1273 "the effective ID. For more on this, see ``Testing File\n"
1274 "Access'' in The GNU C Library Reference Manual.")
1275 #define FUNC_NAME s_scm_access
1276 {
1277 int rv;
1278 char *c_path;
1279
1280 c_path = scm_to_locale_string (path);
1281 rv = access (c_path, scm_to_int (how));
1282 free (c_path);
1283
1284 return scm_from_bool (!rv);
1285 }
1286 #undef FUNC_NAME
1287
1288 SCM_DEFINE (scm_chmod, "chmod", 2, 0, 0,
1289 (SCM object, SCM mode),
1290 "Changes the permissions of the file referred to by\n"
1291 "@var{object}. @var{object} can be a string containing a file\n"
1292 "name or a port or integer file descriptor which is open on a\n"
1293 "file (in which case @code{fchmod} is used as the underlying\n"
1294 "system call). @var{mode} specifies the new permissions as a\n"
1295 "decimal number, e.g., @code{(chmod \"foo\" #o755)}.\n"
1296 "The return value is unspecified.")
1297 #define FUNC_NAME s_scm_chmod
1298 {
1299 int rv;
1300
1301 object = SCM_COERCE_OUTPORT (object);
1302
1303 #if HAVE_FCHMOD
1304 if (scm_is_integer (object) || SCM_OPFPORTP (object))
1305 {
1306 int fdes;
1307 if (scm_is_integer (object))
1308 fdes = scm_to_int (object);
1309 else
1310 fdes = SCM_FPORT_FDES (object);
1311 SCM_SYSCALL (rv = fchmod (fdes, scm_to_int (mode)));
1312 }
1313 else
1314 #endif
1315 {
1316 STRING_SYSCALL (object, c_object,
1317 rv = chmod (c_object, scm_to_int (mode)));
1318 }
1319 if (rv == -1)
1320 SCM_SYSERROR;
1321 return SCM_UNSPECIFIED;
1322 }
1323 #undef FUNC_NAME
1324
1325 SCM_DEFINE (scm_umask, "umask", 0, 1, 0,
1326 (SCM mode),
1327 "If @var{mode} is omitted, returns a decimal number representing the current\n"
1328 "file creation mask. Otherwise the file creation mask is set to\n"
1329 "@var{mode} and the previous value is returned.\n\n"
1330 "E.g., @code{(umask #o022)} sets the mask to octal 22, decimal 18.")
1331 #define FUNC_NAME s_scm_umask
1332 {
1333 mode_t mask;
1334 if (SCM_UNBNDP (mode))
1335 {
1336 mask = umask (0);
1337 umask (mask);
1338 }
1339 else
1340 {
1341 mask = umask (scm_to_uint (mode));
1342 }
1343 return scm_from_uint (mask);
1344 }
1345 #undef FUNC_NAME
1346
1347 #ifndef HAVE_MKSTEMP
1348 extern int mkstemp (char *);
1349 #endif
1350
1351 SCM_DEFINE (scm_mkstemp, "mkstemp!", 1, 0, 0,
1352 (SCM tmpl),
1353 "Create a new unique file in the file system and return a new\n"
1354 "buffered port open for reading and writing to the file.\n"
1355 "\n"
1356 "@var{tmpl} is a string specifying where the file should be\n"
1357 "created: it must end with @samp{XXXXXX} and those @samp{X}s\n"
1358 "will be changed in the string to return the name of the file.\n"
1359 "(@code{port-filename} on the port also gives the name.)\n"
1360 "\n"
1361 "POSIX doesn't specify the permissions mode of the file, on GNU\n"
1362 "and most systems it's @code{#o600}. An application can use\n"
1363 "@code{chmod} to relax that if desired. For example\n"
1364 "@code{#o666} less @code{umask}, which is usual for ordinary\n"
1365 "file creation,\n"
1366 "\n"
1367 "@example\n"
1368 "(let ((port (mkstemp! (string-copy \"/tmp/myfile-XXXXXX\"))))\n"
1369 " (chmod port (logand #o666 (lognot (umask))))\n"
1370 " ...)\n"
1371 "@end example")
1372 #define FUNC_NAME s_scm_mkstemp
1373 {
1374 char *c_tmpl;
1375 int rv;
1376
1377 scm_dynwind_begin (0);
1378
1379 c_tmpl = scm_to_locale_string (tmpl);
1380 scm_dynwind_free (c_tmpl);
1381
1382 SCM_SYSCALL (rv = mkstemp (c_tmpl));
1383 if (rv == -1)
1384 SCM_SYSERROR;
1385
1386 scm_substring_move_x (scm_from_locale_string (c_tmpl),
1387 SCM_INUM0, scm_string_length (tmpl),
1388 tmpl, SCM_INUM0);
1389
1390 scm_dynwind_end ();
1391 return scm_fdes_to_port (rv, "w+", tmpl);
1392 }
1393 #undef FUNC_NAME
1394
1395 \f
1396 /* Filename manipulation */
1397
1398 SCM scm_dot_string;
1399
1400 #ifdef __MINGW32__
1401 SCM_SYMBOL (sym_file_name_convention, "windows");
1402 #else
1403 SCM_SYMBOL (sym_file_name_convention, "posix");
1404 #endif
1405
1406 SCM_INTERNAL SCM scm_system_file_name_convention (void);
1407
1408 SCM_DEFINE (scm_system_file_name_convention,
1409 "system-file-name-convention", 0, 0, 0, (void),
1410 "Return either @code{posix} or @code{windows}, depending on\n"
1411 "what kind of system this Guile is running on.")
1412 #define FUNC_NAME s_scm_system_file_name_convention
1413 {
1414 return sym_file_name_convention;
1415 }
1416 #undef FUNC_NAME
1417
1418 SCM_DEFINE (scm_dirname, "dirname", 1, 0, 0,
1419 (SCM filename),
1420 "Return the directory name component of the file name\n"
1421 "@var{filename}. If @var{filename} does not contain a directory\n"
1422 "component, @code{.} is returned.")
1423 #define FUNC_NAME s_scm_dirname
1424 {
1425 long int i;
1426 unsigned long int len;
1427
1428 SCM_VALIDATE_STRING (1, filename);
1429
1430 len = scm_i_string_length (filename);
1431
1432 i = len - 1;
1433
1434 while (i >= 0 && is_file_name_separator (scm_c_string_ref (filename, i)))
1435 --i;
1436 while (i >= 0 && !is_file_name_separator (scm_c_string_ref (filename, i)))
1437 --i;
1438 while (i >= 0 && is_file_name_separator (scm_c_string_ref (filename, i)))
1439 --i;
1440
1441 if (i < 0)
1442 {
1443 if (len > 0 && is_file_name_separator (scm_c_string_ref (filename, 0)))
1444 return scm_c_substring (filename, 0, 1);
1445 else
1446 return scm_dot_string;
1447 }
1448 else
1449 return scm_c_substring (filename, 0, i + 1);
1450 }
1451 #undef FUNC_NAME
1452
1453 SCM_DEFINE (scm_basename, "basename", 1, 1, 0,
1454 (SCM filename, SCM suffix),
1455 "Return the base name of the file name @var{filename}. The\n"
1456 "base name is the file name without any directory components.\n"
1457 "If @var{suffix} is provided, and is equal to the end of\n"
1458 "@var{filename}, it is removed also.")
1459 #define FUNC_NAME s_scm_basename
1460 {
1461 int i, j, len, end;
1462
1463 SCM_VALIDATE_STRING (1, filename);
1464 len = scm_i_string_length (filename);
1465
1466 if (SCM_UNBNDP (suffix))
1467 j = -1;
1468 else
1469 {
1470 SCM_VALIDATE_STRING (2, suffix);
1471 j = scm_i_string_length (suffix) - 1;
1472 }
1473 i = len - 1;
1474 while (i >= 0 && is_file_name_separator (scm_c_string_ref (filename, i)))
1475 --i;
1476 end = i;
1477 while (i >= 0 && j >= 0
1478 && (scm_i_string_ref (filename, i)
1479 == scm_i_string_ref (suffix, j)))
1480 {
1481 --i;
1482 --j;
1483 }
1484 if (j == -1)
1485 end = i;
1486 while (i >= 0 && !is_file_name_separator (scm_c_string_ref (filename, i)))
1487 --i;
1488 if (i == end)
1489 {
1490 if (len > 0 && is_file_name_separator (scm_c_string_ref (filename, 0)))
1491 return scm_c_substring (filename, 0, 1);
1492 else
1493 return scm_dot_string;
1494 }
1495 else
1496 return scm_c_substring (filename, i+1, end+1);
1497 }
1498 #undef FUNC_NAME
1499
1500 SCM_DEFINE (scm_canonicalize_path, "canonicalize-path", 1, 0, 0,
1501 (SCM path),
1502 "Return the canonical path of @var{path}. A canonical path has\n"
1503 "no @code{.} or @code{..} components, nor any repeated path\n"
1504 "separators (@code{/}) nor symlinks.\n\n"
1505 "Raises an error if any component of @var{path} does not exist.")
1506 #define FUNC_NAME s_scm_canonicalize_path
1507 {
1508 char *str, *canon;
1509
1510 SCM_VALIDATE_STRING (1, path);
1511
1512 str = scm_to_locale_string (path);
1513 canon = canonicalize_file_name (str);
1514 free (str);
1515
1516 if (canon)
1517 return scm_take_locale_string (canon);
1518 else
1519 SCM_SYSERROR;
1520 }
1521 #undef FUNC_NAME
1522
1523 SCM
1524 scm_i_relativize_path (SCM path, SCM in_path)
1525 {
1526 char *str, *canon;
1527 SCM scanon;
1528
1529 str = scm_to_locale_string (path);
1530 canon = canonicalize_file_name (str);
1531 free (str);
1532
1533 if (!canon)
1534 return SCM_BOOL_F;
1535
1536 scanon = scm_take_locale_string (canon);
1537
1538 for (; scm_is_pair (in_path); in_path = scm_cdr (in_path))
1539 {
1540 SCM dir = scm_car (in_path);
1541 size_t len = scm_c_string_length (dir);
1542
1543 /* When DIR is empty, it means "current working directory". We
1544 could set DIR to (getcwd) in that case, but then the
1545 canonicalization would depend on the current directory, which
1546 is not what we want in the context of `compile-file', for
1547 instance. */
1548 if (len > 0
1549 && scm_is_true (scm_string_prefix_p (dir, scanon,
1550 SCM_UNDEFINED, SCM_UNDEFINED,
1551 SCM_UNDEFINED, SCM_UNDEFINED)))
1552 {
1553 /* DIR either has a trailing delimiter or doesn't. SCANON
1554 will be delimited by single delimiters. When DIR does not
1555 have a trailing delimiter, add one to the length to strip
1556 off the delimiter within SCANON. */
1557 if (!is_file_name_separator (scm_c_string_ref (dir, len - 1)))
1558 len++;
1559
1560 if (scm_c_string_length (scanon) > len)
1561 return scm_substring (scanon, scm_from_size_t (len), SCM_UNDEFINED);
1562 else
1563 return SCM_BOOL_F;
1564 }
1565 }
1566
1567 return SCM_BOOL_F;
1568 }
1569
1570 \f
1571 /* Examining directories. These procedures are used by `check-guile'
1572 and thus compiled unconditionally. */
1573
1574 scm_t_bits scm_tc16_dir;
1575
1576
1577 SCM_DEFINE (scm_directory_stream_p, "directory-stream?", 1, 0, 0,
1578 (SCM obj),
1579 "Return a boolean indicating whether @var{obj} is a directory\n"
1580 "stream as returned by @code{opendir}.")
1581 #define FUNC_NAME s_scm_directory_stream_p
1582 {
1583 return scm_from_bool (SCM_DIRP (obj));
1584 }
1585 #undef FUNC_NAME
1586
1587
1588 SCM_DEFINE (scm_opendir, "opendir", 1, 0, 0,
1589 (SCM dirname),
1590 "Open the directory specified by @var{dirname} and return a directory\n"
1591 "stream.")
1592 #define FUNC_NAME s_scm_opendir
1593 {
1594 DIR *ds;
1595 STRING_SYSCALL (dirname, c_dirname, ds = opendir (c_dirname));
1596 if (ds == NULL)
1597 SCM_SYSERROR;
1598 SCM_RETURN_NEWSMOB (scm_tc16_dir | (SCM_DIR_FLAG_OPEN<<16), ds);
1599 }
1600 #undef FUNC_NAME
1601
1602
1603 /* FIXME: The glibc manual has a portability note that readdir_r may not
1604 null-terminate its return string. The circumstances outlined for this
1605 are not clear, nor is it clear what should be done about it. Lets use
1606 NAMLEN and worry about what else should be done if/when someone can
1607 figure it out. */
1608
1609 SCM_DEFINE (scm_readdir, "readdir", 1, 0, 0,
1610 (SCM port),
1611 "Return (as a string) the next directory entry from the directory stream\n"
1612 "@var{port}. If there is no remaining entry to be read then the\n"
1613 "end of file object is returned.")
1614 #define FUNC_NAME s_scm_readdir
1615 {
1616 struct dirent_or_dirent64 *rdent;
1617
1618 SCM_VALIDATE_DIR (1, port);
1619 if (!SCM_DIR_OPEN_P (port))
1620 SCM_MISC_ERROR ("Directory ~S is not open.", scm_list_1 (port));
1621
1622 #if HAVE_READDIR_R
1623 /* As noted in the glibc manual, on various systems (such as Solaris) the
1624 d_name[] field is only 1 char and you're expected to size the dirent
1625 buffer for readdir_r based on NAME_MAX. The SCM_MAX expressions below
1626 effectively give either sizeof(d_name) or NAME_MAX+1, whichever is
1627 bigger.
1628
1629 On solaris 10 there's no NAME_MAX constant, it's necessary to use
1630 pathconf(). We prefer NAME_MAX though, since it should be a constant
1631 and will therefore save a system call. We also prefer it since dirfd()
1632 is not available everywhere.
1633
1634 An alternative to dirfd() would be to open() the directory and then use
1635 fdopendir(), if the latter is available. That'd let us hold the fd
1636 somewhere in the smob, or just the dirent size calculated once. */
1637 {
1638 struct dirent_or_dirent64 de; /* just for sizeof */
1639 DIR *ds = (DIR *) SCM_SMOB_DATA_1 (port);
1640 #ifdef NAME_MAX
1641 char buf [SCM_MAX (sizeof (de),
1642 sizeof (de) - sizeof (de.d_name) + NAME_MAX + 1)];
1643 #else
1644 char *buf;
1645 long name_max = fpathconf (dirfd (ds), _PC_NAME_MAX);
1646 if (name_max == -1)
1647 SCM_SYSERROR;
1648 buf = alloca (SCM_MAX (sizeof (de),
1649 sizeof (de) - sizeof (de.d_name) + name_max + 1));
1650 #endif
1651
1652 errno = 0;
1653 SCM_SYSCALL (readdir_r_or_readdir64_r (ds, (struct dirent_or_dirent64 *) buf, &rdent));
1654 if (errno != 0)
1655 SCM_SYSERROR;
1656 if (! rdent)
1657 return SCM_EOF_VAL;
1658
1659 return (rdent ? scm_from_locale_stringn (rdent->d_name, NAMLEN (rdent))
1660 : SCM_EOF_VAL);
1661 }
1662 #else
1663 {
1664 SCM ret;
1665 scm_dynwind_begin (0);
1666 scm_i_dynwind_pthread_mutex_lock (&scm_i_misc_mutex);
1667
1668 errno = 0;
1669 SCM_SYSCALL (rdent = readdir_or_readdir64 ((DIR *) SCM_SMOB_DATA_1 (port)));
1670 if (errno != 0)
1671 SCM_SYSERROR;
1672
1673 ret = (rdent ? scm_from_locale_stringn (rdent->d_name, NAMLEN (rdent))
1674 : SCM_EOF_VAL);
1675
1676 scm_dynwind_end ();
1677 return ret;
1678 }
1679 #endif
1680 }
1681 #undef FUNC_NAME
1682
1683
1684 SCM_DEFINE (scm_rewinddir, "rewinddir", 1, 0, 0,
1685 (SCM port),
1686 "Reset the directory port @var{port} so that the next call to\n"
1687 "@code{readdir} will return the first directory entry.")
1688 #define FUNC_NAME s_scm_rewinddir
1689 {
1690 SCM_VALIDATE_DIR (1, port);
1691 if (!SCM_DIR_OPEN_P (port))
1692 SCM_MISC_ERROR ("Directory ~S is not open.", scm_list_1 (port));
1693
1694 rewinddir ((DIR *) SCM_SMOB_DATA_1 (port));
1695
1696 return SCM_UNSPECIFIED;
1697 }
1698 #undef FUNC_NAME
1699
1700
1701 SCM_DEFINE (scm_closedir, "closedir", 1, 0, 0,
1702 (SCM port),
1703 "Close the directory stream @var{port}.\n"
1704 "The return value is unspecified.")
1705 #define FUNC_NAME s_scm_closedir
1706 {
1707 SCM_VALIDATE_DIR (1, port);
1708
1709 if (SCM_DIR_OPEN_P (port))
1710 {
1711 int sts;
1712
1713 SCM_SYSCALL (sts = closedir ((DIR *) SCM_SMOB_DATA_1 (port)));
1714 if (sts != 0)
1715 SCM_SYSERROR;
1716
1717 SCM_SET_SMOB_DATA_0 (port, scm_tc16_dir);
1718 }
1719
1720 return SCM_UNSPECIFIED;
1721 }
1722 #undef FUNC_NAME
1723
1724
1725 #ifdef HAVE_POSIX
1726 static int
1727 scm_dir_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
1728 {
1729 scm_puts ("#<", port);
1730 if (!SCM_DIR_OPEN_P (exp))
1731 scm_puts ("closed: ", port);
1732 scm_puts ("directory stream ", port);
1733 scm_uintprint (SCM_SMOB_DATA_1 (exp), 16, port);
1734 scm_putc ('>', port);
1735 return 1;
1736 }
1737
1738
1739 static size_t
1740 scm_dir_free (SCM p)
1741 {
1742 if (SCM_DIR_OPEN_P (p))
1743 closedir ((DIR *) SCM_SMOB_DATA_1 (p));
1744 return 0;
1745 }
1746 #endif
1747
1748 \f
1749
1750 void
1751 scm_init_filesys ()
1752 {
1753 #ifdef HAVE_POSIX
1754 scm_tc16_dir = scm_make_smob_type ("directory", 0);
1755 scm_set_smob_free (scm_tc16_dir, scm_dir_free);
1756 scm_set_smob_print (scm_tc16_dir, scm_dir_print);
1757
1758 #ifdef O_RDONLY
1759 scm_c_define ("O_RDONLY", scm_from_int (O_RDONLY));
1760 #endif
1761 #ifdef O_WRONLY
1762 scm_c_define ("O_WRONLY", scm_from_int (O_WRONLY));
1763 #endif
1764 #ifdef O_RDWR
1765 scm_c_define ("O_RDWR", scm_from_int (O_RDWR));
1766 #endif
1767 #ifdef O_CREAT
1768 scm_c_define ("O_CREAT", scm_from_int (O_CREAT));
1769 #endif
1770 #ifdef O_EXCL
1771 scm_c_define ("O_EXCL", scm_from_int (O_EXCL));
1772 #endif
1773 #ifdef O_NOCTTY
1774 scm_c_define ("O_NOCTTY", scm_from_int (O_NOCTTY));
1775 #endif
1776 #ifdef O_TRUNC
1777 scm_c_define ("O_TRUNC", scm_from_int (O_TRUNC));
1778 #endif
1779 #ifdef O_APPEND
1780 scm_c_define ("O_APPEND", scm_from_int (O_APPEND));
1781 #endif
1782 #ifdef O_NONBLOCK
1783 scm_c_define ("O_NONBLOCK", scm_from_int (O_NONBLOCK));
1784 #endif
1785 #ifdef O_NDELAY
1786 scm_c_define ("O_NDELAY", scm_from_int (O_NDELAY));
1787 #endif
1788 #ifdef O_SYNC
1789 scm_c_define ("O_SYNC", scm_from_int (O_SYNC));
1790 #endif
1791 #ifdef O_LARGEFILE
1792 scm_c_define ("O_LARGEFILE", scm_from_int (O_LARGEFILE));
1793 #endif
1794 #ifdef O_NOTRANS
1795 scm_c_define ("O_NOTRANS", scm_from_int (O_NOTRANS));
1796 #endif
1797
1798 #ifdef F_DUPFD
1799 scm_c_define ("F_DUPFD", scm_from_int (F_DUPFD));
1800 #endif
1801 #ifdef F_GETFD
1802 scm_c_define ("F_GETFD", scm_from_int (F_GETFD));
1803 #endif
1804 #ifdef F_SETFD
1805 scm_c_define ("F_SETFD", scm_from_int (F_SETFD));
1806 #endif
1807 #ifdef F_GETFL
1808 scm_c_define ("F_GETFL", scm_from_int (F_GETFL));
1809 #endif
1810 #ifdef F_SETFL
1811 scm_c_define ("F_SETFL", scm_from_int (F_SETFL));
1812 #endif
1813 #ifdef F_GETOWN
1814 scm_c_define ("F_GETOWN", scm_from_int (F_GETOWN));
1815 #endif
1816 #ifdef F_SETOWN
1817 scm_c_define ("F_SETOWN", scm_from_int (F_SETOWN));
1818 #endif
1819 #ifdef FD_CLOEXEC
1820 scm_c_define ("FD_CLOEXEC", scm_from_int (FD_CLOEXEC));
1821 #endif
1822 #endif /* HAVE_POSIX */
1823
1824 /* `access' symbols. */
1825 scm_c_define ("R_OK", scm_from_int (R_OK));
1826 scm_c_define ("W_OK", scm_from_int (W_OK));
1827 scm_c_define ("X_OK", scm_from_int (X_OK));
1828 scm_c_define ("F_OK", scm_from_int (F_OK));
1829
1830 scm_dot_string = scm_from_locale_string (".");
1831
1832 #include "libguile/filesys.x"
1833 }
1834
1835 /*
1836 Local Variables:
1837 c-file-style: "gnu"
1838 End:
1839 */