Debian Codegraph @

unix/tclUnixFCmd.c

raw
1 /*
2 * tclUnixFCmd.c
3 *
4 * This file implements the Unix specific portion of file manipulation
5 * subcommands of the "file" command. All filename arguments should
6 * already be translated to native format.
7 *
8 * Copyright (c) 1996-1998 Sun Microsystems, Inc.
9 *
10 * See the file "license.terms" for information on usage and redistribution of
11 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
12 *
13 * Portions of this code were derived from NetBSD source code which has the
14 * following copyright notice:
15 *
16 * Copyright (c) 1988, 1993, 1994
17 * The Regents of the University of California. All rights reserved.
18 *
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions are met:
21 * 1. Redistributions of source code must retain the above copyright notice,
22 * this list of conditions and the following disclaimer.
23 * 2. Redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution.
26 * 3. Neither the name of the University nor the names of its contributors may
27 * be used to endorse or promote products derived from this software
28 * without specific prior written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
31 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
32 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
33 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
34 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
35 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
36 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
37 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
40 * DAMAGE.
41 */
42
43 #include "tclInt.h"
44 #include <utime.h>
45 #include <grp.h>
46 #ifndef HAVE_STRUCT_STAT_ST_BLKSIZE
47 #ifndef NO_FSTATFS
48 #include <sys/statfs.h>
49 #endif
50 #endif /* !HAVE_STRUCT_STAT_ST_BLKSIZE */
51 #ifdef HAVE_FTS
52 #include <fts.h>
53 #endif
54
55 /*
56 * The following constants specify the type of callback when
57 * TraverseUnixTree() calls the traverseProc()
58 */
59
60 #define DOTREE_PRED 1 /* pre-order directory */
61 #define DOTREE_POSTD 2 /* post-order directory */
62 #define DOTREE_F 3 /* regular file */
63
64 /*
65 * Fallback temporary file location the temporary file generation code. Can be
66 * overridden at compile time for when it is known that temp files can't be
67 * written to /tmp (hello, iOS!).
68 */
69
70 #ifndef TCL_TEMPORARY_FILE_DIRECTORY
71 #define TCL_TEMPORARY_FILE_DIRECTORY "/tmp"
72 #endif
73
74 /*
75 * Callbacks for file attributes code.
76 */
77
78 static int GetGroupAttribute(Tcl_Interp *interp, int objIndex,
79 Tcl_Obj *fileName, Tcl_Obj **attributePtrPtr);
80 static int GetOwnerAttribute(Tcl_Interp *interp, int objIndex,
81 Tcl_Obj *fileName, Tcl_Obj **attributePtrPtr);
82 static int GetPermissionsAttribute(Tcl_Interp *interp,
83 int objIndex, Tcl_Obj *fileName,
84 Tcl_Obj **attributePtrPtr);
85 static int SetGroupAttribute(Tcl_Interp *interp, int objIndex,
86 Tcl_Obj *fileName, Tcl_Obj *attributePtr);
87 static int SetOwnerAttribute(Tcl_Interp *interp, int objIndex,
88 Tcl_Obj *fileName, Tcl_Obj *attributePtr);
89 static int SetPermissionsAttribute(Tcl_Interp *interp,
90 int objIndex, Tcl_Obj *fileName,
91 Tcl_Obj *attributePtr);
92 static int GetModeFromPermString(Tcl_Interp *interp,
93 const char *modeStringPtr, mode_t *modePtr);
94 #if defined(HAVE_CHFLAGS) && defined(UF_IMMUTABLE) || defined(__CYGWIN__)
95 static int GetUnixFileAttributes(Tcl_Interp *interp, int objIndex,
96 Tcl_Obj *fileName, Tcl_Obj **attributePtrPtr);
97 static int SetUnixFileAttributes(Tcl_Interp *interp, int objIndex,
98 Tcl_Obj *fileName, Tcl_Obj *attributePtr);
99 #endif
100
101 /*
102 * Prototype for the TraverseUnixTree callback function.
103 */
104
105 typedef int (TraversalProc)(Tcl_DString *srcPtr, Tcl_DString *dstPtr,
106 const Tcl_StatBuf *statBufPtr, int type, Tcl_DString *errorPtr);
107
108 /*
109 * Constants and variables necessary for file attributes subcommand.
110 *
111 * IMPORTANT: The permissions attribute is assumed to be the third item (i.e.
112 * to be indexed with '2' in arrays) in code in tclIOUtil.c and possibly
113 * elsewhere in Tcl's core.
114 */
115
116 #ifdef DJGPP
117
118 /*
119 * See contrib/djgpp/tclDjgppFCmd.c for definition.
120 */
121
122 extern TclFileAttrProcs tclpFileAttrProcs[];
123 extern const char *const tclpFileAttrStrings[];
124
125 #else /* !DJGPP */
126 enum {
127 #if defined(__CYGWIN__)
128 UNIX_ARCHIVE_ATTRIBUTE,
129 #endif
130 UNIX_GROUP_ATTRIBUTE,
131 #if defined(__CYGWIN__)
132 UNIX_HIDDEN_ATTRIBUTE,
133 #endif
134 UNIX_OWNER_ATTRIBUTE, UNIX_PERMISSIONS_ATTRIBUTE,
135 #if defined(HAVE_CHFLAGS) && defined(UF_IMMUTABLE) || defined(__CYGWIN__)
136 UNIX_READONLY_ATTRIBUTE,
137 #endif
138 #if defined(__CYGWIN__)
139 UNIX_SYSTEM_ATTRIBUTE,
140 #endif
141 #ifdef MAC_OSX_TCL
142 MACOSX_CREATOR_ATTRIBUTE, MACOSX_TYPE_ATTRIBUTE, MACOSX_HIDDEN_ATTRIBUTE,
143 MACOSX_RSRCLENGTH_ATTRIBUTE,
144 #endif
145 UNIX_INVALID_ATTRIBUTE /* lint - last enum value needs no trailing , */
146 };
147
148 MODULE_SCOPE const char *const tclpFileAttrStrings[];
149 const char *const tclpFileAttrStrings[] = {
150 #if defined(__CYGWIN__)
151 "-archive",
152 #endif
153 "-group",
154 #if defined(__CYGWIN__)
155 "-hidden",
156 #endif
157 "-owner", "-permissions",
158 #if defined(HAVE_CHFLAGS) && defined(UF_IMMUTABLE) || defined(__CYGWIN__)
159 "-readonly",
160 #endif
161 #if defined(__CYGWIN__)
162 "-system",
163 #endif
164 #ifdef MAC_OSX_TCL
165 "-creator", "-type", "-hidden", "-rsrclength",
166 #endif
167 NULL
168 };
169
170 MODULE_SCOPE const TclFileAttrProcs tclpFileAttrProcs[];
171 const TclFileAttrProcs tclpFileAttrProcs[] = {
172 #if defined(__CYGWIN__)
173 {GetUnixFileAttributes, SetUnixFileAttributes},
174 #endif
175 {GetGroupAttribute, SetGroupAttribute},
176 #if defined(__CYGWIN__)
177 {GetUnixFileAttributes, SetUnixFileAttributes},
178 #endif
179 {GetOwnerAttribute, SetOwnerAttribute},
180 {GetPermissionsAttribute, SetPermissionsAttribute},
181 #if defined(HAVE_CHFLAGS) && defined(UF_IMMUTABLE) || defined(__CYGWIN__)
182 {GetUnixFileAttributes, SetUnixFileAttributes},
183 #endif
184 #if defined(__CYGWIN__)
185 {GetUnixFileAttributes, SetUnixFileAttributes},
186 #endif
187 #ifdef MAC_OSX_TCL
188 {TclMacOSXGetFileAttribute, TclMacOSXSetFileAttribute},
189 {TclMacOSXGetFileAttribute, TclMacOSXSetFileAttribute},
190 {TclMacOSXGetFileAttribute, TclMacOSXSetFileAttribute},
191 {TclMacOSXGetFileAttribute, TclMacOSXSetFileAttribute},
192 #endif
193 };
194 #endif /* DJGPP */
195
196 /*
197 * This is the maximum number of consecutive readdir/unlink calls that can be
198 * made (with no intervening rewinddir or closedir/opendir) before triggering
199 * a bug that makes readdir return NULL even though some directory entries
200 * have not been processed. The bug afflicts SunOS's readdir when applied to
201 * ufs file systems and Darwin 6.5's (and OSX v.10.3.8's) HFS+. JH found the
202 * Darwin readdir to reset at 147, so 130 is chosen to be conservative. We
203 * can't do a general rewind on failure as NFS can create special files that
204 * recreate themselves when you try and delete them. 8.4.8 added a solution
205 * that was affected by a single such NFS file, this solution should not be
206 * affected by less than THRESHOLD such files. [Bug 1034337]
207 */
208
209 #define MAX_READDIR_UNLINK_THRESHOLD 130
210
211 /*
212 * Declarations for local procedures defined in this file:
213 */
214
215 static int CopyFileAtts(const char *src,
216 const char *dst, const Tcl_StatBuf *statBufPtr);
217 static const char * DefaultTempDir(void);
218 static int DoCopyFile(const char *srcPtr, const char *dstPtr,
219 const Tcl_StatBuf *statBufPtr);
220 static int DoCreateDirectory(const char *pathPtr);
221 static int DoRemoveDirectory(Tcl_DString *pathPtr,
222 int recursive, Tcl_DString *errorPtr);
223 static int DoRenameFile(const char *src, const char *dst);
224 static int TraversalCopy(Tcl_DString *srcPtr,
225 Tcl_DString *dstPtr,
226 const Tcl_StatBuf *statBufPtr, int type,
227 Tcl_DString *errorPtr);
228 static int TraversalDelete(Tcl_DString *srcPtr,
229 Tcl_DString *dstPtr,
230 const Tcl_StatBuf *statBufPtr, int type,
231 Tcl_DString *errorPtr);
232 static int TraverseUnixTree(TraversalProc *traversalProc,
233 Tcl_DString *sourcePtr, Tcl_DString *destPtr,
234 Tcl_DString *errorPtr, int doRewind);
235
236 #ifdef PURIFY
237 /*
238 * realpath and purify don't mix happily. It has been noted that realpath
239 * should not be used with purify because of bogus warnings, but just
240 * memset'ing the resolved path will squelch those. This assumes we are
241 * passing the standard MAXPATHLEN size resolved arg.
242 */
243
244 static char * Realpath(const char *path, char *resolved);
245
246 char *
247 Realpath(
248 const char *path,
249 char *resolved)
250 {
251 memset(resolved, 0, MAXPATHLEN);
252 return realpath(path, resolved);
253 }
254 #else
255 # define Realpath realpath
256 #endif /* PURIFY */
257
258 #ifndef NO_REALPATH
259 #if defined(__APPLE__) && defined(TCL_THREADS) && \
260 defined(MAC_OS_X_VERSION_MIN_REQUIRED) && \
261 MAC_OS_X_VERSION_MIN_REQUIRED < 1030
262 /*
263 * Prior to Darwin 7, realpath is not thread-safe, c.f. Bug 711232; if we
264 * might potentially be running on pre-10.3 OSX, check Darwin release at
265 * runtime before using realpath.
266 */
267
268 MODULE_SCOPE long tclMacOSXDarwinRelease;
269 # define haveRealpath (tclMacOSXDarwinRelease >= 7)
270 #else
271 # define haveRealpath 1
272 #endif
273 #endif /* NO_REALPATH */
274
275 #ifdef HAVE_FTS
276 #if defined(HAVE_STRUCT_STAT64) && !defined(__APPLE__)
277 /* fts doesn't do stat64 */
278 # define noFtsStat 1
279 #elif defined(__APPLE__) && defined(__LP64__) && \
280 defined(MAC_OS_X_VERSION_MIN_REQUIRED) && \
281 MAC_OS_X_VERSION_MIN_REQUIRED < 1050
282 /*
283 * Prior to Darwin 9, 64bit fts_open() without FTS_NOSTAT may crash (due to a
284 * 64bit-unsafe ALIGN macro); if we could be running on pre-10.5 OSX, check
285 * Darwin release at runtime and do a separate stat() if necessary.
286 */
287
288 MODULE_SCOPE long tclMacOSXDarwinRelease;
289 # define noFtsStat (tclMacOSXDarwinRelease < 9)
290 #else
291 # define noFtsStat 0
292 #endif
293 #endif /* HAVE_FTS */
294
295 /*
296 *---------------------------------------------------------------------------
297 *
298 * TclpObjRenameFile, DoRenameFile --
299 *
300 * Changes the name of an existing file or directory, from src to dst. If
301 * src and dst refer to the same file or directory, does nothing and
302 * returns success. Otherwise if dst already exists, it will be deleted
303 * and replaced by src subject to the following conditions:
304 * If src is a directory, dst may be an empty directory.
305 * If src is a file, dst may be a file.
306 * In any other situation where dst already exists, the rename will fail.
307 *
308 * Results:
309 * If the directory was successfully created, returns TCL_OK. Otherwise
310 * the return value is TCL_ERROR and errno is set to indicate the error.
311 * Some possible values for errno are:
312 *
313 * EACCES: src or dst parent directory can't be read and/or written.
314 * EEXIST: dst is a non-empty directory.
315 * EINVAL: src is a root directory or dst is a subdirectory of src.
316 * EISDIR: dst is a directory, but src is not.
317 * ENOENT: src doesn't exist, or src or dst is "".
318 * ENOTDIR: src is a directory, but dst is not.
319 * EXDEV: src and dst are on different filesystems.
320 *
321 * Side effects:
322 * The implementation of rename may allow cross-filesystem renames, but
323 * the caller should be prepared to emulate it with copy and delete if
324 * errno is EXDEV.
325 *
326 *---------------------------------------------------------------------------
327 */
328
329 int
330 TclpObjRenameFile(
331 Tcl_Obj *srcPathPtr,
332 Tcl_Obj *destPathPtr)
333 {
334 return DoRenameFile(Tcl_FSGetNativePath(srcPathPtr),
335 Tcl_FSGetNativePath(destPathPtr));
336 }
337
338 static int
339 DoRenameFile(
340 const char *src, /* Pathname of file or dir to be renamed
341 * (native). */
342 const char *dst) /* New pathname of file or directory
343 * (native). */
344 {
345 if (rename(src, dst) == 0) { /* INTL: Native. */
346 return TCL_OK;
347 }
348 if (errno == ENOTEMPTY) {
349 errno = EEXIST;
350 }
351
352 /*
353 * IRIX returns EIO when you attempt to move a directory into itself. We
354 * just map EIO to EINVAL get the right message on SGI. Most platforms
355 * don't return EIO except in really strange cases.
356 */
357
358 if (errno == EIO) {
359 errno = EINVAL;
360 }
361
362 #ifndef NO_REALPATH
363 /*
364 * SunOS 4.1.4 reports overwriting a non-empty directory with a directory
365 * as EINVAL instead of EEXIST (first rule out the correct EINVAL result
366 * code for moving a directory into itself). Must be conditionally
367 * compiled because realpath() not defined on all systems.
368 */
369
370 if (errno == EINVAL && haveRealpath) {
371 char srcPath[MAXPATHLEN], dstPath[MAXPATHLEN];
372 TclDIR *dirPtr;
373 Tcl_DirEntry *dirEntPtr;
374
375 if ((Realpath((char *) src, srcPath) != NULL) /* INTL: Native. */
376 && (Realpath((char *) dst, dstPath) != NULL) /* INTL: Native */
377 && (strncmp(srcPath, dstPath, strlen(srcPath)) != 0)) {
378 dirPtr = TclOSopendir(dst); /* INTL: Native. */
379 if (dirPtr != NULL) {
380 while (1) {
381 dirEntPtr = TclOSreaddir(dirPtr); /* INTL: Native. */
382 if (dirEntPtr == NULL) {
383 break;
384 }
385 if ((strcmp(dirEntPtr->d_name, ".") != 0) &&
386 (strcmp(dirEntPtr->d_name, "..") != 0)) {
387 errno = EEXIST;
388 TclOSclosedir(dirPtr);
389 return TCL_ERROR;
390 }
391 }
392 TclOSclosedir(dirPtr);
393 }
394 }
395 errno = EINVAL;
396 }
397 #endif /* !NO_REALPATH */
398
399 if (strcmp(src, "/") == 0) {
400 /*
401 * Alpha reports renaming / as EBUSY and Linux reports it as EACCES,
402 * instead of EINVAL.
403 */
404
405 errno = EINVAL;
406 }
407
408 /*
409 * DEC Alpha OSF1 V3.0 returns EACCES when attempting to move a file
410 * across filesystems and the parent directory of that file is not
411 * writable. Most other systems return EXDEV. Does nothing to correct this
412 * behavior.
413 */
414
415 return TCL_ERROR;
416 }
417
418 /*
419 *---------------------------------------------------------------------------
420 *
421 * TclpObjCopyFile, DoCopyFile --
422 *
423 * Copy a single file (not a directory). If dst already exists and is not
424 * a directory, it is removed.
425 *
426 * Results:
427 * If the file was successfully copied, returns TCL_OK. Otherwise the
428 * return value is TCL_ERROR and errno is set to indicate the error. Some
429 * possible values for errno are:
430 *
431 * EACCES: src or dst parent directory can't be read and/or written.
432 * EISDIR: src or dst is a directory.
433 * ENOENT: src doesn't exist. src or dst is "".
434 *
435 * Side effects:
436 * This procedure will also copy symbolic links, block, and character
437 * devices, and fifos. For symbolic links, the links themselves will be
438 * copied and not what they point to. For the other special file types,
439 * the directory entry will be copied and not the contents of the device
440 * that it refers to.
441 *
442 *---------------------------------------------------------------------------
443 */
444
445 int
446 TclpObjCopyFile(
447 Tcl_Obj *srcPathPtr,
448 Tcl_Obj *destPathPtr)
449 {
450 const char *src = Tcl_FSGetNativePath(srcPathPtr);
451 Tcl_StatBuf srcStatBuf;
452
453 if (TclOSlstat(src, &srcStatBuf) != 0) { /* INTL: Native. */
454 return TCL_ERROR;
455 }
456
457 return DoCopyFile(src, Tcl_FSGetNativePath(destPathPtr), &srcStatBuf);
458 }
459
460 static int
461 DoCopyFile(
462 const char *src, /* Pathname of file to be copied (native). */
463 const char *dst, /* Pathname of file to copy to (native). */
464 const Tcl_StatBuf *statBufPtr)
465 /* Used to determine filetype. */
466 {
467 Tcl_StatBuf dstStatBuf;
468
469 if (S_ISDIR(statBufPtr->st_mode)) {
470 errno = EISDIR;
471 return TCL_ERROR;
472 }
473
474 /*
475 * Symlink, and some of the other calls will fail if the target exists, so
476 * we remove it first.
477 */
478
479 if (TclOSlstat(dst, &dstStatBuf) == 0) { /* INTL: Native. */
480 if (S_ISDIR(dstStatBuf.st_mode)) {
481 errno = EISDIR;
482 return TCL_ERROR;
483 }
484 }
485 if (unlink(dst) != 0) { /* INTL: Native. */
486 if (errno != ENOENT) {
487 return TCL_ERROR;
488 }
489 }
490
491 switch ((int) (statBufPtr->st_mode & S_IFMT)) {
492 #ifndef DJGPP
493 case S_IFLNK: {
494 char linkBuf[MAXPATHLEN+1];
495 int length;
496
497 length = readlink(src, linkBuf, MAXPATHLEN);
498 /* INTL: Native. */
499 if (length == -1) {
500 return TCL_ERROR;
501 }
502 linkBuf[length] = '\0';
503 if (symlink(linkBuf, dst) < 0) { /* INTL: Native. */
504 return TCL_ERROR;
505 }
506 #ifdef MAC_OSX_TCL
507 TclMacOSXCopyFileAttributes(src, dst, statBufPtr);
508 #endif
509 break;
510 }
511 #endif /* !DJGPP */
512 case S_IFBLK:
513 case S_IFCHR:
514 if (mknod(dst, statBufPtr->st_mode, /* INTL: Native. */
515 statBufPtr->st_rdev) < 0) {
516 return TCL_ERROR;
517 }
518 return CopyFileAtts(src, dst, statBufPtr);
519 case S_IFIFO:
520 if (mkfifo(dst, statBufPtr->st_mode) < 0) { /* INTL: Native. */
521 return TCL_ERROR;
522 }
523 return CopyFileAtts(src, dst, statBufPtr);
524 default:
525 return TclUnixCopyFile(src, dst, statBufPtr, 0);
526 }
527 return TCL_OK;
528 }
529
530 /*
531 *----------------------------------------------------------------------
532 *
533 * TclUnixCopyFile -
534 *
535 * Helper function for TclpCopyFile. Copies one regular file, using
536 * read() and write().
537 *
538 * Results:
539 * A standard Tcl result.
540 *
541 * Side effects:
542 * A file is copied. Dst will be overwritten if it exists.
543 *
544 *----------------------------------------------------------------------
545 */
546
547 int
548 TclUnixCopyFile(
549 const char *src, /* Pathname of file to copy (native). */
550 const char *dst, /* Pathname of file to create/overwrite
551 * (native). */
552 const Tcl_StatBuf *statBufPtr,
553 /* Used to determine mode and blocksize. */
554 int dontCopyAtts) /* If flag set, don't copy attributes. */
555 {
556 int srcFd, dstFd;
557 unsigned blockSize; /* Optimal I/O blocksize for filesystem */
558 char *buffer; /* Data buffer for copy */
559 size_t nread;
560
561 #ifdef DJGPP
562 #define BINMODE |O_BINARY
563 #else
564 #define BINMODE
565 #endif /* DJGPP */
566
567 #define DEFAULT_COPY_BLOCK_SIZE 4096
568
569 if ((srcFd = TclOSopen(src, O_RDONLY BINMODE, 0)) < 0) { /* INTL: Native */
570 return TCL_ERROR;
571 }
572
573 dstFd = TclOSopen(dst, O_CREAT|O_TRUNC|O_WRONLY BINMODE, /* INTL: Native */
574 statBufPtr->st_mode);
575 if (dstFd < 0) {
576 close(srcFd);
577 return TCL_ERROR;
578 }
579
580 /*
581 * Try to work out the best size of buffer to use for copying. If we
582 * can't, it's no big deal as we can just use a (32-bit) page, since
583 * that's likely to be fairly efficient anyway.
584 */
585
586 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
587 blockSize = statBufPtr->st_blksize;
588 #elif !defined(NO_FSTATFS)
589 {
590 struct statfs fs;
591
592 if (fstatfs(srcFd, &fs) == 0) {
593 blockSize = fs.f_bsize;
594 } else {
595 blockSize = DEFAULT_COPY_BLOCK_SIZE;
596 }
597 }
598 #else
599 blockSize = DEFAULT_COPY_BLOCK_SIZE;
600 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
601
602 /*
603 * [SF Tcl Bug 1586470] Even if we HAVE_STRUCT_STAT_ST_BLKSIZE, there are
604 * filesystems which report a bogus value for the blocksize. An example
605 * is the Andrew Filesystem (afs), reporting a blocksize of 0. When
606 * detecting such a situation we now simply fall back to a hardwired
607 * default size.
608 */
609
610 if (blockSize <= 0) {
611 blockSize = DEFAULT_COPY_BLOCK_SIZE;
612 }
613 buffer = ckalloc(blockSize);
614 while (1) {
615 nread = (size_t) read(srcFd, buffer, blockSize);
616 if ((nread == (size_t) -1) || (nread == 0)) {
617 break;
618 }
619 if ((size_t) write(dstFd, buffer, nread) != nread) {
620 nread = (size_t) -1;
621 break;
622 }
623 }
624
625 ckfree(buffer);
626 close(srcFd);
627 if ((close(dstFd) != 0) || (nread == (size_t) -1)) {
628 unlink(dst); /* INTL: Native. */
629 return TCL_ERROR;
630 }
631 if (!dontCopyAtts && CopyFileAtts(src, dst, statBufPtr) == TCL_ERROR) {
632 /*
633 * The copy succeeded, but setting the permissions failed, so be in a
634 * consistent state, we remove the file that was created by the copy.
635 */
636
637 unlink(dst); /* INTL: Native. */
638 return TCL_ERROR;
639 }
640 return TCL_OK;
641 }
642
643 /*
644 *---------------------------------------------------------------------------
645 *
646 * TclpObjDeleteFile, TclpDeleteFile --
647 *
648 * Removes a single file (not a directory).
649 *
650 * Results:
651 * If the file was successfully deleted, returns TCL_OK. Otherwise the
652 * return value is TCL_ERROR and errno is set to indicate the error. Some
653 * possible values for errno are:
654 *
655 * EACCES: a parent directory can't be read and/or written.
656 * EISDIR: path is a directory.
657 * ENOENT: path doesn't exist or is "".
658 *
659 * Side effects:
660 * The file is deleted, even if it is read-only.
661 *
662 *---------------------------------------------------------------------------
663 */
664
665 int
666 TclpObjDeleteFile(
667 Tcl_Obj *pathPtr)
668 {
669 return TclpDeleteFile(Tcl_FSGetNativePath(pathPtr));
670 }
671
672 int
673 TclpDeleteFile(
674 const void *path) /* Pathname of file to be removed (native). */
675 {
676 if (unlink((const char *)path) != 0) {
677 return TCL_ERROR;
678 }
679 return TCL_OK;
680 }
681
682 /*
683 *---------------------------------------------------------------------------
684 *
685 * TclpCreateDirectory, DoCreateDirectory --
686 *
687 * Creates the specified directory. All parent directories of the
688 * specified directory must already exist. The directory is automatically
689 * created with permissions so that user can access the new directory and
690 * create new files or subdirectories in it.
691 *
692 * Results:
693 * If the directory was successfully created, returns TCL_OK. Otherwise
694 * the return value is TCL_ERROR and errno is set to indicate the error.
695 * Some possible values for errno are:
696 *
697 * EACCES: a parent directory can't be read and/or written.
698 * EEXIST: path already exists.
699 * ENOENT: a parent directory doesn't exist.
700 *
701 * Side effects:
702 * A directory is created with the current umask, except that permission
703 * for u+rwx will always be added.
704 *
705 *---------------------------------------------------------------------------
706 */
707
708 int
709 TclpObjCreateDirectory(
710 Tcl_Obj *pathPtr)
711 {
712 return DoCreateDirectory(Tcl_FSGetNativePath(pathPtr));
713 }
714
715 static int
716 DoCreateDirectory(
717 const char *path) /* Pathname of directory to create (native). */
718 {
719 mode_t mode;
720
721 mode = umask(0);
722 umask(mode);
723
724 /*
725 * umask return value is actually the inverse of the permissions.
726 */
727
728 mode = (0777 & ~mode) | S_IRUSR | S_IWUSR | S_IXUSR;
729
730 if (mkdir(path, mode) != 0) { /* INTL: Native. */
731 return TCL_ERROR;
732 }
733 return TCL_OK;
734 }
735
736 /*
737 *---------------------------------------------------------------------------
738 *
739 * TclpObjCopyDirectory --
740 *
741 * Recursively copies a directory. The target directory dst must not
742 * already exist. Note that this function does not merge two directory
743 * hierarchies, even if the target directory is an empty directory.
744 *
745 * Results:
746 * If the directory was successfully copied, returns TCL_OK. Otherwise
747 * the return value is TCL_ERROR, errno is set to indicate the error, and
748 * the pathname of the file that caused the error is stored in errorPtr.
749 * See TclpObjCreateDirectory and TclpObjCopyFile for a description of
750 * possible values for errno.
751 *
752 * Side effects:
753 * An exact copy of the directory hierarchy src will be created with the
754 * name dst. If an error occurs, the error will be returned immediately,
755 * and remaining files will not be processed.
756 *
757 *---------------------------------------------------------------------------
758 */
759
760 int
761 TclpObjCopyDirectory(
762 Tcl_Obj *srcPathPtr,
763 Tcl_Obj *destPathPtr,
764 Tcl_Obj **errorPtr)
765 {
766 Tcl_DString ds;
767 Tcl_DString srcString, dstString;
768 int ret;
769 Tcl_Obj *transPtr;
770
771 transPtr = Tcl_FSGetTranslatedPath(NULL,srcPathPtr);
772 Tcl_UtfToExternalDString(NULL,
773 (transPtr != NULL ? TclGetString(transPtr) : NULL),
774 -1, &srcString);
775 if (transPtr != NULL) {
776 Tcl_DecrRefCount(transPtr);
777 }
778 transPtr = Tcl_FSGetTranslatedPath(NULL,destPathPtr);
779 Tcl_UtfToExternalDString(NULL,
780 (transPtr != NULL ? TclGetString(transPtr) : NULL),
781 -1, &dstString);
782 if (transPtr != NULL) {
783 Tcl_DecrRefCount(transPtr);
784 }
785
786 ret = TraverseUnixTree(TraversalCopy, &srcString, &dstString, &ds, 0);
787
788 Tcl_DStringFree(&srcString);
789 Tcl_DStringFree(&dstString);
790
791 if (ret != TCL_OK) {
792 *errorPtr = TclDStringToObj(&ds);
793 Tcl_IncrRefCount(*errorPtr);
794 }
795 return ret;
796 }
797
798 /*
799 *---------------------------------------------------------------------------
800 *
801 * TclpRemoveDirectory, DoRemoveDirectory --
802 *
803 * Removes directory (and its contents, if the recursive flag is set).
804 *
805 * Results:
806 * If the directory was successfully removed, returns TCL_OK. Otherwise
807 * the return value is TCL_ERROR, errno is set to indicate the error, and
808 * the pathname of the file that caused the error is stored in errorPtr.
809 * Some possible values for errno are:
810 *
811 * EACCES: path directory can't be read and/or written.
812 * EEXIST: path is a non-empty directory.
813 * EINVAL: path is a root directory.
814 * ENOENT: path doesn't exist or is "".
815 * ENOTDIR: path is not a directory.
816 *
817 * Side effects:
818 * Directory removed. If an error occurs, the error will be returned
819 * immediately, and remaining files will not be deleted.
820 *
821 *---------------------------------------------------------------------------
822 */
823
824 int
825 TclpObjRemoveDirectory(
826 Tcl_Obj *pathPtr,
827 int recursive,
828 Tcl_Obj **errorPtr)
829 {
830 Tcl_DString ds;
831 Tcl_DString pathString;
832 int ret;
833 Tcl_Obj *transPtr = Tcl_FSGetTranslatedPath(NULL, pathPtr);
834
835 Tcl_UtfToExternalDString(NULL,
836 (transPtr != NULL ? TclGetString(transPtr) : NULL),
837 -1, &pathString);
838 if (transPtr != NULL) {
839 Tcl_DecrRefCount(transPtr);
840 }
841 ret = DoRemoveDirectory(&pathString, recursive, &ds);
842 Tcl_DStringFree(&pathString);
843
844 if (ret != TCL_OK) {
845 *errorPtr = TclDStringToObj(&ds);
846 Tcl_IncrRefCount(*errorPtr);
847 }
848 return ret;
849 }
850
851 static int
852 DoRemoveDirectory(
853 Tcl_DString *pathPtr, /* Pathname of directory to be removed
854 * (native). */
855 int recursive, /* If non-zero, removes directories that are
856 * nonempty. Otherwise, will only remove empty
857 * directories. */
858 Tcl_DString *errorPtr) /* If non-NULL, uninitialized or free DString
859 * filled with UTF-8 name of file causing
860 * error. */
861 {
862 const char *path;
863 mode_t oldPerm = 0;
864 int result;
865
866 path = Tcl_DStringValue(pathPtr);
867
868 if (recursive != 0) {
869 /*
870 * We should try to change permissions so this can be deleted.
871 */
872
873 Tcl_StatBuf statBuf;
874 int newPerm;
875
876 if (TclOSstat(path, &statBuf) == 0) {
877 oldPerm = (mode_t) (statBuf.st_mode & 0x00007FFF);
878 }
879
880 newPerm = oldPerm | (64+128+256);
881 chmod(path, (mode_t) newPerm);
882 }
883
884 if (rmdir(path) == 0) { /* INTL: Native. */
885 return TCL_OK;
886 }
887 if (errno == ENOTEMPTY) {
888 errno = EEXIST;
889 }
890
891 result = TCL_OK;
892 if ((errno != EEXIST) || (recursive == 0)) {
893 if (errorPtr != NULL) {
894 Tcl_ExternalToUtfDString(NULL, path, -1, errorPtr);
895 }
896 result = TCL_ERROR;
897 }
898
899 /*
900 * The directory is nonempty, but the recursive flag has been specified,
901 * so we recursively remove all the files in the directory.
902 */
903
904 if (result == TCL_OK) {
905 result = TraverseUnixTree(TraversalDelete, pathPtr, NULL, errorPtr, 1);
906 }
907
908 if ((result != TCL_OK) && (recursive != 0)) {
909 /*
910 * Try to restore permissions.
911 */
912
913 chmod(path, oldPerm);
914 }
915 return result;
916 }
917
918 /*
919 *---------------------------------------------------------------------------
920 *
921 * TraverseUnixTree --
922 *
923 * Traverse directory tree specified by sourcePtr, calling the function
924 * traverseProc for each file and directory encountered. If destPtr is
925 * non-null, each of name in the sourcePtr directory is appended to the
926 * directory specified by destPtr and passed as the second argument to
927 * traverseProc().
928 *
929 * Results:
930 * Standard Tcl result.
931 *
932 * Side effects:
933 * None caused by TraverseUnixTree, however the user specified
934 * traverseProc() may change state. If an error occurs, the error will be
935 * returned immediately, and remaining files will not be processed.
936 *
937 *---------------------------------------------------------------------------
938 */
939
940 static int
941 TraverseUnixTree(
942 TraversalProc *traverseProc,/* Function to call for every file and
943 * directory in source hierarchy. */
944 Tcl_DString *sourcePtr, /* Pathname of source directory to be
945 * traversed (native). */
946 Tcl_DString *targetPtr, /* Pathname of directory to traverse in
947 * parallel with source directory (native). */
948 Tcl_DString *errorPtr, /* If non-NULL, uninitialized or free DString
949 * filled with UTF-8 name of file causing
950 * error. */
951 int doRewind) /* Flag indicating that to ensure complete
952 * traversal of source hierarchy, the readdir
953 * loop should be rewound whenever
954 * traverseProc has returned TCL_OK; this is
955 * required when traverseProc modifies the
956 * source hierarchy, e.g. by deleting
957 * files. */
958 {
959 Tcl_StatBuf statBuf;
960 const char *source, *errfile;
961 int result, sourceLen;
962 int targetLen;
963 #ifndef HAVE_FTS
964 int numProcessed = 0;
965 Tcl_DirEntry *dirEntPtr;
966 TclDIR *dirPtr;
967 #else
968 const char *paths[2] = {NULL, NULL};
969 FTS *fts = NULL;
970 FTSENT *ent;
971 #endif
972
973 errfile = NULL;
974 result = TCL_OK;
975 targetLen = 0; /* lint. */
976
977 source = Tcl_DStringValue(sourcePtr);
978 if (TclOSlstat(source, &statBuf) != 0) { /* INTL: Native. */
979 errfile = source;
980 goto end;
981 }
982 if (!S_ISDIR(statBuf.st_mode)) {
983 /*
984 * Process the regular file
985 */
986
987 return traverseProc(sourcePtr, targetPtr, &statBuf, DOTREE_F,
988 errorPtr);
989 }
990 #ifndef HAVE_FTS
991 dirPtr = TclOSopendir(source); /* INTL: Native. */
992 if (dirPtr == NULL) {
993 /*
994 * Can't read directory
995 */
996
997 errfile = source;
998 goto end;
999 }
1000 result = traverseProc(sourcePtr, targetPtr, &statBuf, DOTREE_PRED,
1001 errorPtr);
1002 if (result != TCL_OK) {
1003 TclOSclosedir(dirPtr);
1004 return result;
1005 }
1006
1007 TclDStringAppendLiteral(sourcePtr, "/");
1008 sourceLen = Tcl_DStringLength(sourcePtr);
1009
1010 if (targetPtr != NULL) {
1011 TclDStringAppendLiteral(targetPtr, "/");
1012 targetLen = Tcl_DStringLength(targetPtr);
1013 }
1014
1015 while ((dirEntPtr = TclOSreaddir(dirPtr)) != NULL) { /* INTL: Native. */
1016 if ((dirEntPtr->d_name[0] == '.')
1017 && ((dirEntPtr->d_name[1] == '\0')
1018 || (strcmp(dirEntPtr->d_name, "..") == 0))) {
1019 continue;
1020 }
1021
1022 /*
1023 * Append name after slash, and recurse on the file.
1024 */
1025
1026 Tcl_DStringAppend(sourcePtr, dirEntPtr->d_name, -1);
1027 if (targetPtr != NULL) {
1028 Tcl_DStringAppend(targetPtr, dirEntPtr->d_name, -1);
1029 }
1030 result = TraverseUnixTree(traverseProc, sourcePtr, targetPtr,
1031 errorPtr, doRewind);
1032 if (result != TCL_OK) {
1033 break;
1034 } else {
1035 numProcessed++;
1036 }
1037
1038 /*
1039 * Remove name after slash.
1040 */
1041
1042 Tcl_DStringSetLength(sourcePtr, sourceLen);
1043 if (targetPtr != NULL) {
1044 Tcl_DStringSetLength(targetPtr, targetLen);
1045 }
1046 if (doRewind && (numProcessed > MAX_READDIR_UNLINK_THRESHOLD)) {
1047 /*
1048 * Call rewinddir if we've called unlink or rmdir so many times
1049 * (since the opendir or the previous rewinddir), to avoid a
1050 * NULL-return that may a symptom of a buggy readdir.
1051 */
1052
1053 TclOSrewinddir(dirPtr);
1054 numProcessed = 0;
1055 }
1056 }
1057 TclOSclosedir(dirPtr);
1058
1059 /*
1060 * Strip off the trailing slash we added
1061 */
1062
1063 Tcl_DStringSetLength(sourcePtr, sourceLen - 1);
1064 if (targetPtr != NULL) {
1065 Tcl_DStringSetLength(targetPtr, targetLen - 1);
1066 }
1067
1068 if (result == TCL_OK) {
1069 /*
1070 * Call traverseProc() on a directory after visiting all the files in
1071 * that directory.
1072 */
1073
1074 result = traverseProc(sourcePtr, targetPtr, &statBuf, DOTREE_POSTD,
1075 errorPtr);
1076 }
1077 #else /* HAVE_FTS */
1078 paths[0] = source;
1079 fts = fts_open((char **) paths, FTS_PHYSICAL | FTS_NOCHDIR |
1080 (noFtsStat || doRewind ? FTS_NOSTAT : 0), NULL);
1081 if (fts == NULL) {
1082 errfile = source;
1083 goto end;
1084 }
1085
1086 sourceLen = Tcl_DStringLength(sourcePtr);
1087 if (targetPtr != NULL) {
1088 targetLen = Tcl_DStringLength(targetPtr);
1089 }
1090
1091 while ((ent = fts_read(fts)) != NULL) {
1092 unsigned short info = ent->fts_info;
1093 char *path = ent->fts_path + sourceLen;
1094 unsigned short pathlen = ent->fts_pathlen - sourceLen;
1095 int type;
1096 Tcl_StatBuf *statBufPtr = NULL;
1097
1098 if (info == FTS_DNR || info == FTS_ERR || info == FTS_NS) {
1099 errfile = ent->fts_path;
1100 break;
1101 }
1102 Tcl_DStringAppend(sourcePtr, path, pathlen);
1103 if (targetPtr != NULL) {
1104 Tcl_DStringAppend(targetPtr, path, pathlen);
1105 }
1106 switch (info) {
1107 case FTS_D:
1108 type = DOTREE_PRED;
1109 break;
1110 case FTS_DP:
1111 type = DOTREE_POSTD;
1112 break;
1113 default:
1114 type = DOTREE_F;
1115 break;
1116 }
1117 if (!doRewind) { /* no need to stat for delete */
1118 if (noFtsStat) {
1119 statBufPtr = &statBuf;
1120 if (TclOSlstat(ent->fts_path, statBufPtr) != 0) {
1121 errfile = ent->fts_path;
1122 break;
1123 }
1124 } else {
1125 statBufPtr = (Tcl_StatBuf *) ent->fts_statp;
1126 }
1127 }
1128 result = traverseProc(sourcePtr, targetPtr, statBufPtr, type,
1129 errorPtr);
1130 if (result != TCL_OK) {
1131 break;
1132 }
1133 Tcl_DStringSetLength(sourcePtr, sourceLen);
1134 if (targetPtr != NULL) {
1135 Tcl_DStringSetLength(targetPtr, targetLen);
1136 }
1137 }
1138 #endif /* !HAVE_FTS */
1139
1140 end:
1141 if (errfile != NULL) {
1142 if (errorPtr != NULL) {
1143 Tcl_ExternalToUtfDString(NULL, errfile, -1, errorPtr);
1144 }
1145 result = TCL_ERROR;
1146 }
1147 #ifdef HAVE_FTS
1148 if (fts != NULL) {
1149 fts_close(fts);
1150 }
1151 #endif
1152
1153 return result;
1154 }
1155
1156 /*
1157 *----------------------------------------------------------------------
1158 *
1159 * TraversalCopy
1160 *
1161 * Called from TraverseUnixTree in order to execute a recursive copy of a
1162 * directory.
1163 *
1164 * Results:
1165 * Standard Tcl result.
1166 *
1167 * Side effects:
1168 * The file or directory src may be copied to dst, depending on the value
1169 * of type.
1170 *
1171 *----------------------------------------------------------------------
1172 */
1173
1174 static int
1175 TraversalCopy(
1176 Tcl_DString *srcPtr, /* Source pathname to copy (native). */
1177 Tcl_DString *dstPtr, /* Destination pathname of copy (native). */
1178 const Tcl_StatBuf *statBufPtr,
1179 /* Stat info for file specified by srcPtr. */
1180 int type, /* Reason for call - see TraverseUnixTree(). */
1181 Tcl_DString *errorPtr) /* If non-NULL, uninitialized or free DString
1182 * filled with UTF-8 name of file causing
1183 * error. */
1184 {
1185 switch (type) {
1186 case DOTREE_F:
1187 if (DoCopyFile(Tcl_DStringValue(srcPtr), Tcl_DStringValue(dstPtr),
1188 statBufPtr) == TCL_OK) {
1189 return TCL_OK;
1190 }
1191 break;
1192
1193 case DOTREE_PRED:
1194 if (DoCreateDirectory(Tcl_DStringValue(dstPtr)) == TCL_OK) {
1195 return TCL_OK;
1196 }
1197 break;
1198
1199 case DOTREE_POSTD:
1200 if (CopyFileAtts(Tcl_DStringValue(srcPtr),
1201 Tcl_DStringValue(dstPtr), statBufPtr) == TCL_OK) {
1202 return TCL_OK;
1203 }
1204 break;
1205 }
1206
1207 /*
1208 * There shouldn't be a problem with src, because we already checked it to
1209 * get here.
1210 */
1211
1212 if (errorPtr != NULL) {
1213 Tcl_ExternalToUtfDString(NULL, Tcl_DStringValue(dstPtr),
1214 Tcl_DStringLength(dstPtr), errorPtr);
1215 }
1216 return TCL_ERROR;
1217 }
1218
1219 /*
1220 *---------------------------------------------------------------------------
1221 *
1222 * TraversalDelete --
1223 *
1224 * Called by procedure TraverseUnixTree for every file and directory that
1225 * it encounters in a directory hierarchy. This procedure unlinks files,
1226 * and removes directories after all the containing files have been
1227 * processed.
1228 *
1229 * Results:
1230 * Standard Tcl result.
1231 *
1232 * Side effects:
1233 * Files or directory specified by src will be deleted.
1234 *
1235 *----------------------------------------------------------------------
1236 */
1237
1238 static int
1239 TraversalDelete(
1240 Tcl_DString *srcPtr, /* Source pathname (native). */
1241 Tcl_DString *ignore, /* Destination pathname (not used). */
1242 const Tcl_StatBuf *statBufPtr,
1243 /* Stat info for file specified by srcPtr. */
1244 int type, /* Reason for call - see TraverseUnixTree(). */
1245 Tcl_DString *errorPtr) /* If non-NULL, uninitialized or free DString
1246 * filled with UTF-8 name of file causing
1247 * error. */
1248 {
1249 switch (type) {
1250 case DOTREE_F:
1251 if (TclpDeleteFile(Tcl_DStringValue(srcPtr)) == 0) {
1252 return TCL_OK;
1253 }
1254 break;
1255 case DOTREE_PRED:
1256 return TCL_OK;
1257 case DOTREE_POSTD:
1258 if (DoRemoveDirectory(srcPtr, 0, NULL) == 0) {
1259 return TCL_OK;
1260 }
1261 break;
1262 }
1263 if (errorPtr != NULL) {
1264 Tcl_ExternalToUtfDString(NULL, Tcl_DStringValue(srcPtr),
1265 Tcl_DStringLength(srcPtr), errorPtr);
1266 }
1267 return TCL_ERROR;
1268 }
1269
1270 /*
1271 *---------------------------------------------------------------------------
1272 *
1273 * CopyFileAtts --
1274 *
1275 * Copy the file attributes such as owner, group, permissions, and
1276 * modification date from one file to another.
1277 *
1278 * Results:
1279 * Standard Tcl result.
1280 *
1281 * Side effects:
1282 * User id, group id, permission bits, last modification time, and last
1283 * access time are updated in the new file to reflect the old file.
1284 *
1285 *---------------------------------------------------------------------------
1286 */
1287
1288 static int
1289 CopyFileAtts(
1290 const char *src, /* Path name of source file (native). */
1291 const char *dst, /* Path name of target file (native). */
1292 const Tcl_StatBuf *statBufPtr)
1293 /* Stat info for source file */
1294 {
1295 struct utimbuf tval;
1296 mode_t newMode;
1297
1298 newMode = statBufPtr->st_mode
1299 & (S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO);
1300
1301 /*
1302 * Note that if you copy a setuid file that is owned by someone else, and
1303 * you are not root, then the copy will be setuid to you. The most correct
1304 * implementation would probably be to have the copy not setuid to anyone
1305 * if the original file was owned by someone else, but this corner case
1306 * isn't currently handled. It would require another lstat(), or getuid().
1307 */
1308
1309 if (chmod(dst, newMode)) { /* INTL: Native. */
1310 newMode &= ~(S_ISUID | S_ISGID);
1311 if (chmod(dst, newMode)) { /* INTL: Native. */
1312 return TCL_ERROR;
1313 }
1314 }
1315
1316 tval.actime = statBufPtr->st_atime;
1317 tval.modtime = statBufPtr->st_mtime;
1318
1319 if (utime(dst, &tval)) { /* INTL: Native. */
1320 return TCL_ERROR;
1321 }
1322 #ifdef MAC_OSX_TCL
1323 TclMacOSXCopyFileAttributes(src, dst, statBufPtr);
1324 #endif
1325 return TCL_OK;
1326 }
1327
1328 /*
1329 *----------------------------------------------------------------------
1330 *
1331 * GetGroupAttribute
1332 *
1333 * Gets the group attribute of a file.
1334 *
1335 * Results:
1336 * Standard TCL result. Returns a new Tcl_Obj in attributePtrPtr if there
1337 * is no error.
1338 *
1339 * Side effects:
1340 * A new object is allocated.
1341 *
1342 *----------------------------------------------------------------------
1343 */
1344
1345 static int
1346 GetGroupAttribute(
1347 Tcl_Interp *interp, /* The interp we are using for errors. */
1348 int objIndex, /* The index of the attribute. */
1349 Tcl_Obj *fileName, /* The name of the file (UTF-8). */
1350 Tcl_Obj **attributePtrPtr) /* A pointer to return the object with. */
1351 {
1352 Tcl_StatBuf statBuf;
1353 struct group *groupPtr;
1354 int result;
1355
1356 result = TclpObjStat(fileName, &statBuf);
1357
1358 if (result != 0) {
1359 if (interp != NULL) {
1360 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1361 "could not read \"%s\": %s",
1362 TclGetString(fileName), Tcl_PosixError(interp)));
1363 }
1364 return TCL_ERROR;
1365 }
1366
1367 groupPtr = TclpGetGrGid(statBuf.st_gid);
1368
1369 if (groupPtr == NULL) {
1370 TclNewIntObj(*attributePtrPtr, (int) statBuf.st_gid);
1371 } else {
1372 Tcl_DString ds;
1373 const char *utf;
1374
1375 utf = Tcl_ExternalToUtfDString(NULL, groupPtr->gr_name, -1, &ds);
1376 *attributePtrPtr = Tcl_NewStringObj(utf, -1);
1377 Tcl_DStringFree(&ds);
1378 }
1379 return TCL_OK;
1380 }
1381
1382 /*
1383 *----------------------------------------------------------------------
1384 *
1385 * GetOwnerAttribute
1386 *
1387 * Gets the owner attribute of a file.
1388 *
1389 * Results:
1390 * Standard TCL result. Returns a new Tcl_Obj in attributePtrPtr if there
1391 * is no error.
1392 *
1393 * Side effects:
1394 * A new object is allocated.
1395 *
1396 *----------------------------------------------------------------------
1397 */
1398
1399 static int
1400 GetOwnerAttribute(
1401 Tcl_Interp *interp, /* The interp we are using for errors. */
1402 int objIndex, /* The index of the attribute. */
1403 Tcl_Obj *fileName, /* The name of the file (UTF-8). */
1404 Tcl_Obj **attributePtrPtr) /* A pointer to return the object with. */
1405 {
1406 Tcl_StatBuf statBuf;
1407 struct passwd *pwPtr;
1408 int result;
1409
1410 result = TclpObjStat(fileName, &statBuf);
1411
1412 if (result != 0) {
1413 if (interp != NULL) {
1414 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1415 "could not read \"%s\": %s",
1416 TclGetString(fileName), Tcl_PosixError(interp)));
1417 }
1418 return TCL_ERROR;
1419 }
1420
1421 pwPtr = TclpGetPwUid(statBuf.st_uid);
1422
1423 if (pwPtr == NULL) {
1424 TclNewIntObj(*attributePtrPtr, (int) statBuf.st_uid);
1425 } else {
1426 Tcl_DString ds;
1427
1428 (void) Tcl_ExternalToUtfDString(NULL, pwPtr->pw_name, -1, &ds);
1429 *attributePtrPtr = TclDStringToObj(&ds);
1430 }
1431 return TCL_OK;
1432 }
1433
1434 /*
1435 *----------------------------------------------------------------------
1436 *
1437 * GetPermissionsAttribute
1438 *
1439 * Gets the group attribute of a file.
1440 *
1441 * Results:
1442 * Standard TCL result. Returns a new Tcl_Obj in attributePtrPtr if there
1443 * is no error. The object will have ref count 0.
1444 *
1445 * Side effects:
1446 * A new object is allocated.
1447 *
1448 *----------------------------------------------------------------------
1449 */
1450
1451 static int
1452 GetPermissionsAttribute(
1453 Tcl_Interp *interp, /* The interp we are using for errors. */
1454 int objIndex, /* The index of the attribute. */
1455 Tcl_Obj *fileName, /* The name of the file (UTF-8). */
1456 Tcl_Obj **attributePtrPtr) /* A pointer to return the object with. */
1457 {
1458 Tcl_StatBuf statBuf;
1459 int result;
1460
1461 result = TclpObjStat(fileName, &statBuf);
1462
1463 if (result != 0) {
1464 if (interp != NULL) {
1465 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1466 "could not read \"%s\": %s",
1467 TclGetString(fileName), Tcl_PosixError(interp)));
1468 }
1469 return TCL_ERROR;
1470 }
1471
1472 *attributePtrPtr = Tcl_ObjPrintf(
1473 "%0#5lo", (long) (statBuf.st_mode & 0x00007FFF));
1474 return TCL_OK;
1475 }
1476
1477 /*
1478 *---------------------------------------------------------------------------
1479 *
1480 * SetGroupAttribute --
1481 *
1482 * Sets the group of the file to the specified group.
1483 *
1484 * Results:
1485 * Standard TCL result.
1486 *
1487 * Side effects:
1488 * As above.
1489 *
1490 *---------------------------------------------------------------------------
1491 */
1492
1493 static int
1494 SetGroupAttribute(
1495 Tcl_Interp *interp, /* The interp for error reporting. */
1496 int objIndex, /* The index of the attribute. */
1497 Tcl_Obj *fileName, /* The name of the file (UTF-8). */
1498 Tcl_Obj *attributePtr) /* New group for file. */
1499 {
1500 long gid;
1501 int result;
1502 const char *native;
1503
1504 if (Tcl_GetLongFromObj(NULL, attributePtr, &gid) != TCL_OK) {
1505 Tcl_DString ds;
1506 struct group *groupPtr = NULL;
1507 const char *string;
1508 int length;
1509
1510 string = Tcl_GetStringFromObj(attributePtr, &length);
1511
1512 native = Tcl_UtfToExternalDString(NULL, string, length, &ds);
1513 groupPtr = TclpGetGrNam(native); /* INTL: Native. */
1514 Tcl_DStringFree(&ds);
1515
1516 if (groupPtr == NULL) {
1517 if (interp != NULL) {
1518 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1519 "could not set group for file \"%s\":"
1520 " group \"%s\" does not exist",
1521 TclGetString(fileName), string));
1522 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "SETGRP",
1523 "NO_GROUP", NULL);
1524 }
1525 return TCL_ERROR;
1526 }
1527 gid = groupPtr->gr_gid;
1528 }
1529
1530 native = Tcl_FSGetNativePath(fileName);
1531 result = chown(native, (uid_t) -1, (gid_t) gid); /* INTL: Native. */
1532
1533 if (result != 0) {
1534 if (interp != NULL) {
1535 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1536 "could not set group for file \"%s\": %s",
1537 TclGetString(fileName), Tcl_PosixError(interp)));
1538 }
1539 return TCL_ERROR;
1540 }
1541 return TCL_OK;
1542 }
1543
1544 /*
1545 *---------------------------------------------------------------------------
1546 *
1547 * SetOwnerAttribute --
1548 *
1549 * Sets the owner of the file to the specified owner.
1550 *
1551 * Results:
1552 * Standard TCL result.
1553 *
1554 * Side effects:
1555 * As above.
1556 *
1557 *---------------------------------------------------------------------------
1558 */
1559
1560 static int
1561 SetOwnerAttribute(
1562 Tcl_Interp *interp, /* The interp for error reporting. */
1563 int objIndex, /* The index of the attribute. */
1564 Tcl_Obj *fileName, /* The name of the file (UTF-8). */
1565 Tcl_Obj *attributePtr) /* New owner for file. */
1566 {
1567 long uid;
1568 int result;
1569 const char *native;
1570
1571 if (Tcl_GetLongFromObj(NULL, attributePtr, &uid) != TCL_OK) {
1572 Tcl_DString ds;
1573 struct passwd *pwPtr = NULL;
1574 const char *string;
1575 int length;
1576
1577 string = Tcl_GetStringFromObj(attributePtr, &length);
1578
1579 native = Tcl_UtfToExternalDString(NULL, string, length, &ds);
1580 pwPtr = TclpGetPwNam(native); /* INTL: Native. */
1581 Tcl_DStringFree(&ds);
1582
1583 if (pwPtr == NULL) {
1584 if (interp != NULL) {
1585 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1586 "could not set owner for file \"%s\":"
1587 " user \"%s\" does not exist",
1588 TclGetString(fileName), string));
1589 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "SETOWN",
1590 "NO_USER", NULL);
1591 }
1592 return TCL_ERROR;
1593 }
1594 uid = pwPtr->pw_uid;
1595 }
1596
1597 native = Tcl_FSGetNativePath(fileName);
1598 result = chown(native, (uid_t) uid, (gid_t) -1); /* INTL: Native. */
1599
1600 if (result != 0) {
1601 if (interp != NULL) {
1602 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1603 "could not set owner for file \"%s\": %s",
1604 TclGetString(fileName), Tcl_PosixError(interp)));
1605 }
1606 return TCL_ERROR;
1607 }
1608 return TCL_OK;
1609 }
1610
1611 /*
1612 *---------------------------------------------------------------------------
1613 *
1614 * SetPermissionsAttribute
1615 *
1616 * Sets the file to the given permission.
1617 *
1618 * Results:
1619 * Standard TCL result.
1620 *
1621 * Side effects:
1622 * The permission of the file is changed.
1623 *
1624 *---------------------------------------------------------------------------
1625 */
1626
1627 static int
1628 SetPermissionsAttribute(
1629 Tcl_Interp *interp, /* The interp we are using for errors. */
1630 int objIndex, /* The index of the attribute. */
1631 Tcl_Obj *fileName, /* The name of the file (UTF-8). */
1632 Tcl_Obj *attributePtr) /* The attribute to set. */
1633 {
1634 long mode;
1635 mode_t newMode;
1636 int result = TCL_ERROR;
1637 const char *native;
1638 const char *modeStringPtr = TclGetString(attributePtr);
1639 int scanned = TclParseAllWhiteSpace(modeStringPtr, -1);
1640
1641 /*
1642 * First supply support for octal number format
1643 */
1644
1645 if ((modeStringPtr[scanned] == '0')
1646 && (modeStringPtr[scanned+1] >= '0')
1647 && (modeStringPtr[scanned+1] <= '7')) {
1648 /* Leading zero - attempt octal interpretation */
1649 Tcl_Obj *modeObj;
1650
1651 TclNewLiteralStringObj(modeObj, "0o");
1652 Tcl_AppendToObj(modeObj, modeStringPtr+scanned+1, -1);
1653 result = Tcl_GetLongFromObj(NULL, modeObj, &mode);
1654 Tcl_DecrRefCount(modeObj);
1655 }
1656 if (result == TCL_OK
1657 || Tcl_GetLongFromObj(NULL, attributePtr, &mode) == TCL_OK) {
1658 newMode = (mode_t) (mode & 0x00007FFF);
1659 } else {
1660 Tcl_StatBuf buf;
1661
1662 /*
1663 * Try the forms "rwxrwxrwx" and "ugo=rwx"
1664 *
1665 * We get the current mode of the file, in order to allow for ug+-=rwx
1666 * style chmod strings.
1667 */
1668
1669 result = TclpObjStat(fileName, &buf);
1670 if (result != 0) {
1671 if (interp != NULL) {
1672 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1673 "could not read \"%s\": %s",
1674 TclGetString(fileName), Tcl_PosixError(interp)));
1675 }
1676 return TCL_ERROR;
1677 }
1678 newMode = (mode_t) (buf.st_mode & 0x00007FFF);
1679
1680 if (GetModeFromPermString(NULL, modeStringPtr, &newMode) != TCL_OK) {
1681 if (interp != NULL) {
1682 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1683 "unknown permission string format \"%s\"",
1684 modeStringPtr));
1685 Tcl_SetErrorCode(interp, "TCL", "VALUE", "PERMISSION", NULL);
1686 }
1687 return TCL_ERROR;
1688 }
1689 }
1690
1691 native = Tcl_FSGetNativePath(fileName);
1692 result = chmod(native, newMode); /* INTL: Native. */
1693 if (result != 0) {
1694 if (interp != NULL) {
1695 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1696 "could not set permissions for file \"%s\": %s",
1697 TclGetString(fileName), Tcl_PosixError(interp)));
1698 }
1699 return TCL_ERROR;
1700 }
1701 return TCL_OK;
1702 }
1703
1704 #ifndef DJGPP
1705 /*
1706 *---------------------------------------------------------------------------
1707 *
1708 * TclpObjListVolumes --
1709 *
1710 * Lists the currently mounted volumes, which on UNIX is just /.
1711 *
1712 * Results:
1713 * The list of volumes.
1714 *
1715 * Side effects:
1716 * None.
1717 *
1718 *---------------------------------------------------------------------------
1719 */
1720
1721 Tcl_Obj *
1722 TclpObjListVolumes(void)
1723 {
1724 Tcl_Obj *resultPtr;
1725 TclNewLiteralStringObj(resultPtr, "/");
1726
1727 Tcl_IncrRefCount(resultPtr);
1728 return resultPtr;
1729 }
1730 #endif
1731
1732 /*
1733 *----------------------------------------------------------------------
1734 *
1735 * GetModeFromPermString --
1736 *
1737 * This procedure is invoked to process the "file permissions" Tcl
1738 * command, to check for a "rwxrwxrwx" or "ugoa+-=rwxst" string. See the
1739 * user documentation for details on what it does.
1740 *
1741 * Results:
1742 * A standard Tcl result.
1743 *
1744 * Side effects:
1745 * See the user documentation.
1746 *
1747 *----------------------------------------------------------------------
1748 */
1749
1750 static int
1751 GetModeFromPermString(
1752 Tcl_Interp *interp, /* The interp we are using for errors. */
1753 const char *modeStringPtr, /* Permissions string */
1754 mode_t *modePtr) /* pointer to the mode value */
1755 {
1756 mode_t newMode;
1757 mode_t oldMode; /* Storage for the value of the old mode (that
1758 * is passed in), to allow for the chmod style
1759 * manipulation. */
1760 int i,n, who, op, what, op_found, who_found;
1761
1762 /*
1763 * We start off checking for an "rwxrwxrwx" style permissions string
1764 */
1765
1766 if (strlen(modeStringPtr) != 9) {
1767 goto chmodStyleCheck;
1768 }
1769
1770 newMode = 0;
1771 for (i = 0; i < 9; i++) {
1772 switch (*(modeStringPtr+i)) {
1773 case 'r':
1774 if ((i%3) != 0) {
1775 goto chmodStyleCheck;
1776 }
1777 newMode |= (1<<(8-i));
1778 break;
1779 case 'w':
1780 if ((i%3) != 1) {
1781 goto chmodStyleCheck;
1782 }
1783 newMode |= (1<<(8-i));
1784 break;
1785 case 'x':
1786 if ((i%3) != 2) {
1787 goto chmodStyleCheck;
1788 }
1789 newMode |= (1<<(8-i));
1790 break;
1791 case 's':
1792 if (((i%3) != 2) || (i > 5)) {
1793 goto chmodStyleCheck;
1794 }
1795 newMode |= (1<<(8-i));
1796 newMode |= (1<<(11-(i/3)));
1797 break;
1798 case 'S':
1799 if (((i%3) != 2) || (i > 5)) {
1800 goto chmodStyleCheck;
1801 }
1802 newMode |= (1<<(11-(i/3)));
1803 break;
1804 case 't':
1805 if (i != 8) {
1806 goto chmodStyleCheck;
1807 }
1808 newMode |= (1<<(8-i));
1809 newMode |= (1<<9);
1810 break;
1811 case 'T':
1812 if (i != 8) {
1813 goto chmodStyleCheck;
1814 }
1815 newMode |= (1<<9);
1816 break;
1817 case '-':
1818 break;
1819 default:
1820 /*
1821 * Oops, not what we thought it was, so go on
1822 */
1823 goto chmodStyleCheck;
1824 }
1825 }
1826 *modePtr = newMode;
1827 return TCL_OK;
1828
1829 chmodStyleCheck:
1830 /*
1831 * We now check for an "ugoa+-=rwxst" style permissions string
1832 */
1833
1834 for (n = 0 ; *(modeStringPtr+n) != '\0' ; n = n + i) {
1835 oldMode = *modePtr;
1836 who = op = what = op_found = who_found = 0;
1837 for (i = 0 ; *(modeStringPtr+n+i) != '\0' ; i++ ) {
1838 if (!who_found) {
1839 /* who */
1840 switch (*(modeStringPtr+n+i)) {
1841 case 'u':
1842 who |= 0x9C0;
1843 continue;
1844 case 'g':
1845 who |= 0x438;
1846 continue;
1847 case 'o':
1848 who |= 0x207;
1849 continue;
1850 case 'a':
1851 who |= 0xFFF;
1852 continue;
1853 }
1854 }
1855 who_found = 1;
1856 if (who == 0) {
1857 who = 0xFFF;
1858 }
1859 if (!op_found) {
1860 /* op */
1861 switch (*(modeStringPtr+n+i)) {
1862 case '+':
1863 op = 1;
1864 op_found = 1;
1865 continue;
1866 case '-':
1867 op = 2;
1868 op_found = 1;
1869 continue;
1870 case '=':
1871 op = 3;
1872 op_found = 1;
1873 continue;
1874 default:
1875 return TCL_ERROR;
1876 }
1877 }
1878 /* what */
1879 switch (*(modeStringPtr+n+i)) {
1880 case 'r':
1881 what |= 0x124;
1882 continue;
1883 case 'w':
1884 what |= 0x92;
1885 continue;
1886 case 'x':
1887 what |= 0x49;
1888 continue;
1889 case 's':
1890 what |= 0xC00;
1891 continue;
1892 case 't':
1893 what |= 0x200;
1894 continue;
1895 case ',':
1896 break;
1897 default:
1898 return TCL_ERROR;
1899 }
1900 if (*(modeStringPtr+n+i) == ',') {
1901 i++;
1902 break;
1903 }
1904 }
1905 switch (op) {
1906 case 1:
1907 *modePtr = oldMode | (who & what);
1908 continue;
1909 case 2:
1910 *modePtr = oldMode & ~(who & what);
1911 continue;
1912 case 3:
1913 *modePtr = (oldMode & ~who) | (who & what);
1914 continue;
1915 }
1916 }
1917 return TCL_OK;
1918 }
1919
1920 /*
1921 *---------------------------------------------------------------------------
1922 *
1923 * TclpObjNormalizePath --
1924 *
1925 * This function scans through a path specification and replaces it, in
1926 * place, with a normalized version. A normalized version is one in which
1927 * all symlinks in the path are replaced with their expanded form (except
1928 * a symlink at the very end of the path).
1929 *
1930 * Results:
1931 * The new 'nextCheckpoint' value, giving as far as we could understand
1932 * in the path.
1933 *
1934 * Side effects:
1935 * The pathPtr string, is modified.
1936 *
1937 *---------------------------------------------------------------------------
1938 */
1939
1940 int
1941 TclpObjNormalizePath(
1942 Tcl_Interp *interp,
1943 Tcl_Obj *pathPtr,
1944 int nextCheckpoint)
1945 {
1946 const char *currentPathEndPosition;
1947 int pathLen;
1948 char cur;
1949 const char *path = Tcl_GetStringFromObj(pathPtr, &pathLen);
1950 Tcl_DString ds;
1951 const char *nativePath;
1952 #ifndef NO_REALPATH
1953 char normPath[MAXPATHLEN];
1954 #endif
1955
1956 /*
1957 * We add '1' here because if nextCheckpoint is zero we know that '/'
1958 * exists, and if it isn't zero, it must point at a directory separator
1959 * which we also know exists.
1960 */
1961
1962 currentPathEndPosition = path + nextCheckpoint;
1963 if (*currentPathEndPosition == '/') {
1964 currentPathEndPosition++;
1965 }
1966
1967 #ifndef NO_REALPATH
1968 /*
1969 * For speed, try to get the entire path in one go.
1970 */
1971
1972 if (nextCheckpoint == 0 && haveRealpath) {
1973 char *lastDir = strrchr(currentPathEndPosition, '/');
1974
1975 if (lastDir != NULL) {
1976 nativePath = Tcl_UtfToExternalDString(NULL, path,
1977 lastDir-path, &ds);
1978 if (Realpath(nativePath, normPath) != NULL) {
1979 if (*nativePath != '/' && *normPath == '/') {
1980 /*
1981 * realpath has transformed a relative path into an
1982 * absolute path, we do not know how to handle this.
1983 */
1984 } else {
1985 nextCheckpoint = lastDir - path;
1986 goto wholeStringOk;
1987 }
1988 }
1989 Tcl_DStringFree(&ds);
1990 }
1991 }
1992
1993 /*
1994 * Else do it the slow way.
1995 */
1996 #endif
1997
1998 while (1) {
1999 cur = *currentPathEndPosition;
2000 if ((cur == '/') && (path != currentPathEndPosition)) {
2001 /*
2002 * Reached directory separator.
2003 */
2004
2005 int accessOk;
2006
2007 nativePath = Tcl_UtfToExternalDString(NULL, path,
2008 currentPathEndPosition - path, &ds);
2009 accessOk = access(nativePath, F_OK);
2010 Tcl_DStringFree(&ds);
2011
2012 if (accessOk != 0) {
2013 /*
2014 * File doesn't exist.
2015 */
2016
2017 break;
2018 }
2019
2020 /*
2021 * Update the acceptable point.
2022 */
2023
2024 nextCheckpoint = currentPathEndPosition - path;
2025 } else if (cur == 0) {
2026 /*
2027 * Reached end of string.
2028 */
2029
2030 break;
2031 }
2032 currentPathEndPosition++;
2033 }
2034
2035 /*
2036 * We should really now convert this to a canonical path. We do that with
2037 * 'realpath' if we have it available. Otherwise we could step through
2038 * every single path component, checking whether it is a symlink, but that
2039 * would be a lot of work, and most modern OSes have 'realpath'.
2040 */
2041
2042 #ifndef NO_REALPATH
2043 if (haveRealpath) {
2044 /*
2045 * If we only had '/foo' or '/' then we never increment nextCheckpoint
2046 * and we don't need or want to go through 'Realpath'. Also, on some
2047 * platforms, passing an empty string to 'Realpath' will give us the
2048 * normalized pwd, which is not what we want at all!
2049 */
2050
2051 if (nextCheckpoint == 0) {
2052 return 0;
2053 }
2054
2055 nativePath = Tcl_UtfToExternalDString(NULL, path,nextCheckpoint, &ds);
2056 if (Realpath(nativePath, normPath) != NULL) {
2057 int newNormLen;
2058
2059 wholeStringOk:
2060 newNormLen = strlen(normPath);
2061 if ((newNormLen == Tcl_DStringLength(&ds))
2062 && (strcmp(normPath, nativePath) == 0)) {
2063 /*
2064 * String is unchanged.
2065 */
2066
2067 Tcl_DStringFree(&ds);
2068
2069 /*
2070 * Enable this to have the native FS claim normalization of
2071 * the whole path for existing files. That would permit the
2072 * caller to declare normalization complete without calls to
2073 * additional filesystems. Saving lots of calls is probably
2074 * worth the extra access() time here. When no other FS's are
2075 * registered though, things are less clear.
2076 *
2077 if (0 == access(normPath, F_OK)) {
2078 return pathLen;
2079 }
2080 */
2081
2082 return nextCheckpoint;
2083 }
2084
2085 /*
2086 * Free up the native path and put in its place the converted,
2087 * normalized path.
2088 */
2089
2090 Tcl_DStringFree(&ds);
2091 Tcl_ExternalToUtfDString(NULL, normPath, (int) newNormLen, &ds);
2092
2093 if (path[nextCheckpoint] != '\0') {
2094 /*
2095 * Not at end, append remaining path.
2096 */
2097
2098 int normLen = Tcl_DStringLength(&ds);
2099
2100 Tcl_DStringAppend(&ds, path + nextCheckpoint,
2101 pathLen - nextCheckpoint);
2102
2103 /*
2104 * We recognise up to and including the directory separator.
2105 */
2106
2107 nextCheckpoint = normLen + 1;
2108 } else {
2109 /*
2110 * We recognise the whole string.
2111 */
2112
2113 nextCheckpoint = Tcl_DStringLength(&ds);
2114 }
2115
2116 /*
2117 * Overwrite with the normalized path.
2118 */
2119
2120 Tcl_SetStringObj(pathPtr, Tcl_DStringValue(&ds),
2121 Tcl_DStringLength(&ds));
2122 }
2123 Tcl_DStringFree(&ds);
2124 }
2125 #endif /* !NO_REALPATH */
2126
2127 return nextCheckpoint;
2128 }
2129
2130 /*
2131 *----------------------------------------------------------------------
2132 *
2133 * TclpOpenTemporaryFile, TclUnixOpenTemporaryFile --
2134 *
2135 * Creates a temporary file, possibly based on the supplied bits and
2136 * pieces of template supplied in the first three arguments. If the
2137 * fourth argument is non-NULL, it contains a Tcl_Obj to store the name
2138 * of the temporary file in (and it is caller's responsibility to clean
2139 * up). If the fourth argument is NULL, try to arrange for the temporary
2140 * file to go away once it is no longer needed.
2141 *
2142 * Results:
2143 * A read-write Tcl Channel open on the file for TclpOpenTemporaryFile,
2144 * or a file descriptor (or -1 on failure) for TclUnixOpenTemporaryFile.
2145 *
2146 * Side effects:
2147 * Accesses the filesystem. Will set the contents of the Tcl_Obj fourth
2148 * argument (if that is non-NULL).
2149 *
2150 *----------------------------------------------------------------------
2151 */
2152
2153 Tcl_Channel
2154 TclpOpenTemporaryFile(
2155 Tcl_Obj *dirObj,
2156 Tcl_Obj *basenameObj,
2157 Tcl_Obj *extensionObj,
2158 Tcl_Obj *resultingNameObj)
2159 {
2160 int fd = TclUnixOpenTemporaryFile(dirObj, basenameObj, extensionObj,
2161 resultingNameObj);
2162
2163 if (fd == -1) {
2164 return NULL;
2165 }
2166 return Tcl_MakeFileChannel(INT2PTR(fd), TCL_READABLE|TCL_WRITABLE);
2167 }
2168
2169 int
2170 TclUnixOpenTemporaryFile(
2171 Tcl_Obj *dirObj,
2172 Tcl_Obj *basenameObj,
2173 Tcl_Obj *extensionObj,
2174 Tcl_Obj *resultingNameObj)
2175 {
2176 Tcl_DString template, tmp;
2177 const char *string;
2178 int len, fd;
2179
2180 /*
2181 * We should also check against making more then TMP_MAX of these.
2182 */
2183
2184 if (dirObj) {
2185 string = Tcl_GetStringFromObj(dirObj, &len);
2186 Tcl_UtfToExternalDString(NULL, string, len, &template);
2187 } else {
2188 Tcl_DStringInit(&template);
2189 Tcl_DStringAppend(&template, DefaultTempDir(), -1); /* INTL: native */
2190 }
2191
2192 TclDStringAppendLiteral(&template, "/");
2193
2194 if (basenameObj) {
2195 string = Tcl_GetStringFromObj(basenameObj, &len);
2196 Tcl_UtfToExternalDString(NULL, string, len, &tmp);
2197 TclDStringAppendDString(&template, &tmp);
2198 Tcl_DStringFree(&tmp);
2199 } else {
2200 TclDStringAppendLiteral(&template, "tcl");
2201 }
2202
2203 TclDStringAppendLiteral(&template, "_XXXXXX");
2204
2205 #ifdef HAVE_MKSTEMPS
2206 if (extensionObj) {
2207 string = Tcl_GetStringFromObj(extensionObj, &len);
2208 Tcl_UtfToExternalDString(NULL, string, len, &tmp);
2209 TclDStringAppendDString(&template, &tmp);
2210 fd = mkstemps(Tcl_DStringValue(&template), Tcl_DStringLength(&tmp));
2211 Tcl_DStringFree(&tmp);
2212 } else
2213 #endif
2214 {
2215 fd = mkstemp(Tcl_DStringValue(&template));
2216 }
2217
2218 if (fd == -1) {
2219 Tcl_DStringFree(&template);
2220 return -1;
2221 }
2222
2223 if (resultingNameObj) {
2224 Tcl_ExternalToUtfDString(NULL, Tcl_DStringValue(&template),
2225 Tcl_DStringLength(&template), &tmp);
2226 Tcl_SetStringObj(resultingNameObj, Tcl_DStringValue(&tmp),
2227 Tcl_DStringLength(&tmp));
2228 Tcl_DStringFree(&tmp);
2229 } else {
2230 /*
2231 * Try to delete the file immediately since we're not reporting the
2232 * name to anyone. Note that we're *not* handling any errors from
2233 * this!
2234 */
2235
2236 unlink(Tcl_DStringValue(&template));
2237 errno = 0;
2238 }
2239 Tcl_DStringFree(&template);
2240
2241 return fd;
2242 }
2243
2244 /*
2245 * Helper that does *part* of what tempnam() does.
2246 */
2247
2248 static const char *
2249 DefaultTempDir(void)
2250 {
2251 const char *dir;
2252 struct stat buf;
2253
2254 dir = getenv("TMPDIR");
2255 if (dir && dir[0] && stat(dir, &buf) == 0 && S_ISDIR(buf.st_mode)
2256 && access(dir, W_OK) == 0) {
2257 return dir;
2258 }
2259
2260 #ifdef P_tmpdir
2261 dir = P_tmpdir;
2262 if (stat(dir, &buf)==0 && S_ISDIR(buf.st_mode) && access(dir, W_OK)==0) {
2263 return dir;
2264 }
2265 #endif
2266
2267 /*
2268 * Assume that the default location ("/tmp" if not overridden) is always
2269 * an existing writable directory; we've no recovery mechanism if it
2270 * isn't.
2271 */
2272
2273 return TCL_TEMPORARY_FILE_DIRECTORY;
2274 }
2275
2276 #if defined(__CYGWIN__)
2277
2278 static void
2279 StatError(
2280 Tcl_Interp *interp, /* The interp that has the error */
2281 Tcl_Obj *fileName) /* The name of the file which caused the
2282 * error. */
2283 {
2284 TclWinConvertError(GetLastError());
2285 Tcl_SetObjResult(interp, Tcl_ObjPrintf("could not read \"%s\": %s",
2286 TclGetString(fileName), Tcl_PosixError(interp)));
2287 }
2288
2289 static WCHAR *
2290 winPathFromObj(
2291 Tcl_Obj *fileName)
2292 {
2293 int size;
2294 const char *native = Tcl_FSGetNativePath(fileName);
2295 WCHAR *winPath;
2296
2297 size = cygwin_conv_path(1, native, NULL, 0);
2298 winPath = ckalloc(size);
2299 cygwin_conv_path(1, native, winPath, size);
2300
2301 return winPath;
2302 }
2303
2304 static const int attributeArray[] = {
2305 0x20, 0, 2, 0, 0, 1, 4};
2306
2307 /*
2308 *----------------------------------------------------------------------
2309 *
2310 * GetUnixFileAttributes
2311 *
2312 * Gets the readonly attribute of a file.
2313 *
2314 * Results:
2315 * Standard TCL result. Returns a new Tcl_Obj in attributePtrPtr if there
2316 * is no error. The object will have ref count 0.
2317 *
2318 * Side effects:
2319 * A new object is allocated.
2320 *
2321 *----------------------------------------------------------------------
2322 */
2323
2324 static int
2325 GetUnixFileAttributes(
2326 Tcl_Interp *interp, /* The interp we are using for errors. */
2327 int objIndex, /* The index of the attribute. */
2328 Tcl_Obj *fileName, /* The name of the file (UTF-8). */
2329 Tcl_Obj **attributePtrPtr) /* A pointer to return the object with. */
2330 {
2331 int fileAttributes;
2332 WCHAR *winPath = winPathFromObj(fileName);
2333
2334 fileAttributes = GetFileAttributesW(winPath);
2335 ckfree(winPath);
2336
2337 if (fileAttributes == -1) {
2338 StatError(interp, fileName);
2339 return TCL_ERROR;
2340 }
2341
2342 TclNewIntObj(*attributePtrPtr, (fileAttributes&attributeArray[objIndex])!=0);
2343
2344 return TCL_OK;
2345 }
2346
2347 /*
2348 *---------------------------------------------------------------------------
2349 *
2350 * SetUnixFileAttributes
2351 *
2352 * Sets the readonly attribute of a file.
2353 *
2354 * Results:
2355 * Standard TCL result.
2356 *
2357 * Side effects:
2358 * The readonly attribute of the file is changed.
2359 *
2360 *---------------------------------------------------------------------------
2361 */
2362
2363 static int
2364 SetUnixFileAttributes(
2365 Tcl_Interp *interp, /* The interp we are using for errors. */
2366 int objIndex, /* The index of the attribute. */
2367 Tcl_Obj *fileName, /* The name of the file (UTF-8). */
2368 Tcl_Obj *attributePtr) /* The attribute to set. */
2369 {
2370 int yesNo, fileAttributes, old;
2371 WCHAR *winPath;
2372
2373 if (Tcl_GetBooleanFromObj(interp, attributePtr, &yesNo) != TCL_OK) {
2374 return TCL_ERROR;
2375 }
2376
2377 winPath = winPathFromObj(fileName);
2378
2379 fileAttributes = old = GetFileAttributesW(winPath);
2380
2381 if (fileAttributes == -1) {
2382 ckfree(winPath);
2383 StatError(interp, fileName);
2384 return TCL_ERROR;
2385 }
2386
2387 if (yesNo) {
2388 fileAttributes |= attributeArray[objIndex];
2389 } else {
2390 fileAttributes &= ~attributeArray[objIndex];
2391 }
2392
2393 if ((fileAttributes != old)
2394 && !SetFileAttributesW(winPath, fileAttributes)) {
2395 ckfree(winPath);
2396 StatError(interp, fileName);
2397 return TCL_ERROR;
2398 }
2399
2400 ckfree(winPath);
2401 return TCL_OK;
2402 }
2403 #elif defined(HAVE_CHFLAGS) && defined(UF_IMMUTABLE)
2404 /*
2405 *----------------------------------------------------------------------
2406 *
2407 * GetUnixFileAttributes
2408 *
2409 * Gets the readonly attribute (user immutable flag) of a file.
2410 *
2411 * Results:
2412 * Standard TCL result. Returns a new Tcl_Obj in attributePtrPtr if there
2413 * is no error. The object will have ref count 0.
2414 *
2415 * Side effects:
2416 * A new object is allocated.
2417 *
2418 *----------------------------------------------------------------------
2419 */
2420
2421 static int
2422 GetUnixFileAttributes(
2423 Tcl_Interp *interp, /* The interp we are using for errors. */
2424 int objIndex, /* The index of the attribute. */
2425 Tcl_Obj *fileName, /* The name of the file (UTF-8). */
2426 Tcl_Obj **attributePtrPtr) /* A pointer to return the object with. */
2427 {
2428 Tcl_StatBuf statBuf;
2429 int result;
2430
2431 result = TclpObjStat(fileName, &statBuf);
2432
2433 if (result != 0) {
2434 if (interp != NULL) {
2435 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2436 "could not read \"%s\": %s",
2437 TclGetString(fileName), Tcl_PosixError(interp)));
2438 }
2439 return TCL_ERROR;
2440 }
2441
2442 *attributePtrPtr = Tcl_NewBooleanObj(statBuf.st_flags&UF_IMMUTABLE);
2443
2444 return TCL_OK;
2445 }
2446
2447 /*
2448 *---------------------------------------------------------------------------
2449 *
2450 * SetUnixFileAttributes
2451 *
2452 * Sets the readonly attribute (user immutable flag) of a file.
2453 *
2454 * Results:
2455 * Standard TCL result.
2456 *
2457 * Side effects:
2458 * The readonly attribute of the file is changed.
2459 *
2460 *---------------------------------------------------------------------------
2461 */
2462
2463 static int
2464 SetUnixFileAttributes(
2465 Tcl_Interp *interp, /* The interp we are using for errors. */
2466 int objIndex, /* The index of the attribute. */
2467 Tcl_Obj *fileName, /* The name of the file (UTF-8). */
2468 Tcl_Obj *attributePtr) /* The attribute to set. */
2469 {
2470 Tcl_StatBuf statBuf;
2471 int result, readonly;
2472 const char *native;
2473
2474 if (Tcl_GetBooleanFromObj(interp, attributePtr, &readonly) != TCL_OK) {
2475 return TCL_ERROR;
2476 }
2477
2478 result = TclpObjStat(fileName, &statBuf);
2479
2480 if (result != 0) {
2481 if (interp != NULL) {
2482 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2483 "could not read \"%s\": %s",
2484 TclGetString(fileName), Tcl_PosixError(interp)));
2485 }
2486 return TCL_ERROR;
2487 }
2488
2489 if (readonly) {
2490 statBuf.st_flags |= UF_IMMUTABLE;
2491 } else {
2492 statBuf.st_flags &= ~UF_IMMUTABLE;
2493 }
2494
2495 native = Tcl_FSGetNativePath(fileName);
2496 result = chflags(native, statBuf.st_flags); /* INTL: Native. */
2497 if (result != 0) {
2498 if (interp != NULL) {
2499 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2500 "could not set flags for file \"%s\": %s",
2501 TclGetString(fileName), Tcl_PosixError(interp)));
2502 }
2503 return TCL_ERROR;
2504 }
2505 return TCL_OK;
2506 }
2507 #endif /* defined(HAVE_CHFLAGS) && defined(UF_IMMUTABLE) */
2508
2509 /*
2510 * Local Variables:
2511 * mode: c
2512 * c-basic-offset: 4
2513 * fill-column: 78
2514 * End:
2515 */