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