summaryrefslogtreecommitdiffstats
path: root/Lib/test/test_rfc822.py
blob: 8c2b2c6f3edc5ad3aadaffd7d77ba3bf0e2296bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import unittest
from test import test_support

rfc822 = test_support.import_module("rfc822", deprecated=True)

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO


class MessageTestCase(unittest.TestCase):
    def create_message(self, msg):
        return rfc822.Message(StringIO(msg))

    def test_get(self):
        msg = self.create_message(
            'To: "last, first" <userid@foo.net>\n\ntest\n')
        self.assertTrue(msg.get("to") == '"last, first" <userid@foo.net>')
        self.assertTrue(msg.get("TO") == '"last, first" <userid@foo.net>')
        self.assertTrue(msg.get("No-Such-Header") is None)
        self.assertTrue(msg.get("No-Such-Header", "No-Such-Value")
                     == "No-Such-Value")

    def test_setdefault(self):
        msg = self.create_message(
            'To: "last, first" <userid@foo.net>\n\ntest\n')
        self.assertTrue(not msg.has_key("New-Header"))
        self.assertTrue(msg.setdefault("New-Header", "New-Value") == "New-Value")
        self.assertTrue(msg.setdefault("New-Header", "Different-Value")
                     == "New-Value")
        self.assertTrue(msg["new-header"] == "New-Value")

        self.assertTrue(msg.setdefault("Another-Header") == "")
        self.assertTrue(msg["another-header"] == "")

    def check(self, msg, results):
        """Check addresses and the date."""
        m = self.create_message(msg)
        i = 0
        for n, a in m.getaddrlist('to') + m.getaddrlist('cc'):
            try:
                mn, ma = results[i][0], results[i][1]
            except IndexError:
                print 'extra parsed address:', repr(n), repr(a)
                continue
            i = i + 1
            self.assertEqual(mn, n,
                             "Un-expected name: %s != %s" % (`mn`, `n`))
            self.assertEqual(ma, a,
                             "Un-expected address: %s != %s" % (`ma`, `a`))
            if mn == n and ma == a:
                pass
            else:
                print 'not found:', repr(n), repr(a)

        out = m.getdate('date')
        if out:
            self.assertEqual(out,
                             (1999, 1, 13, 23, 57, 35, 0, 1, 0),
                             "date conversion failed")


    # Note: all test cases must have the same date (in various formats),
    # or no date!

    def test_basic(self):
        self.check(
            'Date:    Wed, 13 Jan 1999 23:57:35 -0500\n'
            'From:    Guido van Rossum <guido@CNRI.Reston.VA.US>\n'
            'To:      "Guido van\n'
            '\t : Rossum" <guido@python.org>\n'
            'Subject: test2\n'
            '\n'
            'test2\n',
            [('Guido van\n\t : Rossum', 'guido@python.org')])

        self.check(
            'From: Barry <bwarsaw@python.org\n'
            'To: guido@python.org (Guido: the Barbarian)\n'
            'Subject: nonsense\n'
            'Date: Wednesday, January 13 1999 23:57:35 -0500\n'
            '\n'
            'test',
            [('Guido: the Barbarian', 'guido@python.org')])

        self.check(
            'From: Barry <bwarsaw@python.org\n'
            'To: guido@python.org (Guido: the Barbarian)\n'
            'Cc: "Guido: the Madman" <guido@python.org>\n'
            'Date:  13-Jan-1999 23:57:35 EST\n'
            '\n'
            'test',
            [('Guido: the Barbarian', 'guido@python.org'),
             ('Guido: the Madman', 'guido@python.org')
             ])

        self.check(
            'To: "The monster with\n'
            '     the very long name: Guido" <guido@python.org>\n'
            'Date:    Wed, 13 Jan 1999 23:57:35 -0500\n'
            '\n'
            'test',
            [('The monster with\n     the very long name: Guido',
              'guido@python.org')])

        self.check(
            'To: "Amit J. Patel" <amitp@Theory.Stanford.EDU>\n'
            'CC: Mike Fletcher <mfletch@vrtelecom.com>,\n'
            '        "\'string-sig@python.org\'" <string-sig@python.org>\n'
            'Cc: fooz@bat.com, bart@toof.com\n'
            'Cc: goit@lip.com\n'
            'Date:    Wed, 13 Jan 1999 23:57:35 -0500\n'
            '\n'
            'test',
            [('Amit J. Patel', 'amitp@Theory.Stanford.EDU'),
             ('Mike Fletcher', 'mfletch@vrtelecom.com'),
             ("'string-sig@python.org'", 'string-sig@python.org'),
             ('', 'fooz@bat.com'),
             ('', 'bart@toof.com'),
             ('', 'goit@lip.com'),
             ])

        self.check(
            'To: Some One <someone@dom.ain>\n'
            'From: Anudder Persin <subuddy.else@dom.ain>\n'
            'Date:\n'
            '\n'
            'test',
            [('Some One', 'someone@dom.ain')])

        self.check(
            'To: person@dom.ain (User J. Person)\n\n',
            [('User J. Person', 'person@dom.ain')])

    def test_doublecomment(self):
        # The RFC allows comments within comments in an email addr
        self.check(
            'To: person@dom.ain ((User J. Person)), John Doe <foo@bar.com>\n\n',
            [('User J. Person', 'person@dom.ain'), ('John Doe', 'foo@bar.com')])

    def test_twisted(self):
        # This one is just twisted.  I don't know what the proper
        # result should be, but it shouldn't be to infloop, which is
        # what used to happen!
        self.check(
            'To: <[smtp:dd47@mail.xxx.edu]_at_hmhq@hdq-mdm1-imgout.companay.com>\n'
            'Date:    Wed, 13 Jan 1999 23:57:35 -0500\n'
            '\n'
            'test',
            [('', ''),
             ('', 'dd47@mail.xxx.edu'),
             ('', '_at_hmhq@hdq-mdm1-imgout.companay.com'),
             ])

    def test_commas_in_full_name(self):
        # This exercises the old commas-in-a-full-name bug, which
        # should be doing the right thing in recent versions of the
        # module.
        self.check(
            'To: "last, first" <userid@foo.net>\n'
            '\n'
            'test',
            [('last, first', 'userid@foo.net')])

    def test_quoted_name(self):
        self.check(
            'To: (Comment stuff) "Quoted name"@somewhere.com\n'
            '\n'
            'test',
            [('Comment stuff', '"Quoted name"@somewhere.com')])

    def test_bogus_to_header(self):
        self.check(
            'To: :\n'
            'Cc: goit@lip.com\n'
            'Date:    Wed, 13 Jan 1999 23:57:35 -0500\n'
            '\n'
            'test',
            [('', 'goit@lip.com')])

    def test_addr_ipquad(self):
        self.check(
            'To: guido@[132.151.1.21]\n'
            '\n'
            'foo',
            [('', 'guido@[132.151.1.21]')])

    def test_iter(self):
        m = rfc822.Message(StringIO(
            'Date:    Wed, 13 Jan 1999 23:57:35 -0500\n'
            'From:    Guido van Rossum <guido@CNRI.Reston.VA.US>\n'
            'To:      "Guido van\n'
            '\t : Rossum" <guido@python.org>\n'
            'Subject: test2\n'
            '\n'
            'test2\n' ))
        self.assertEqual(sorted(m), ['date', 'from', 'subject', 'to'])

    def test_rfc2822_phrases(self):
        # RFC 2822 (the update to RFC 822) specifies that dots in phrases are
        # obsolete syntax, which conforming programs MUST recognize but NEVER
        # generate (see $4.1 Miscellaneous obsolete tokens).  This is a
        # departure from RFC 822 which did not allow dots in non-quoted
        # phrases.
        self.check('To: User J. Person <person@dom.ain>\n\n',
                   [('User J. Person', 'person@dom.ain')])

    # This takes too long to add to the test suite
##    def test_an_excrutiatingly_long_address_field(self):
##        OBSCENELY_LONG_HEADER_MULTIPLIER = 10000
##        oneaddr = ('Person' * 10) + '@' + ('.'.join(['dom']*10)) + '.com'
##        addr = ', '.join([oneaddr] * OBSCENELY_LONG_HEADER_MULTIPLIER)
##        lst = rfc822.AddrlistClass(addr).getaddrlist()
##        self.assertEqual(len(lst), OBSCENELY_LONG_HEADER_MULTIPLIER)

    def test_2getaddrlist(self):
        eq = self.assertEqual
        msg = self.create_message("""\
To: aperson@dom.ain
Cc: bperson@dom.ain
Cc: cperson@dom.ain
Cc: dperson@dom.ain

A test message.
""")
        ccs = [('', a) for a in
               ['bperson@dom.ain', 'cperson@dom.ain', 'dperson@dom.ain']]
        addrs = msg.getaddrlist('cc')
        addrs.sort()
        eq(addrs, ccs)
        # Try again, this one used to fail
        addrs = msg.getaddrlist('cc')
        addrs.sort()
        eq(addrs, ccs)

    def test_parseaddr(self):
        eq = self.assertEqual
        eq(rfc822.parseaddr('<>'), ('', ''))
        eq(rfc822.parseaddr('aperson@dom.ain'), ('', 'aperson@dom.ain'))
        eq(rfc822.parseaddr('bperson@dom.ain (Bea A. Person)'),
           ('Bea A. Person', 'bperson@dom.ain'))
        eq(rfc822.parseaddr('Cynthia Person <cperson@dom.ain>'),
           ('Cynthia Person', 'cperson@dom.ain'))

    def test_quote_unquote(self):
        eq = self.assertEqual
        eq(rfc822.quote('foo\\wacky"name'), 'foo\\\\wacky\\"name')
        eq(rfc822.unquote('"foo\\\\wacky\\"name"'), 'foo\\wacky"name')


def test_main():
    test_support.run_unittest(MessageTestCase)


if __name__ == "__main__":
    test_main()
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
/*
 * tclMacOSXFCmd.c
 *
 *	This file implements the MacOSX specific portion of file manipulation
 *	subcommands of the "file" command.
 *
 * Copyright (c) 2003-2007 Daniel A. Steffen <das@users.sourceforge.net>
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tclInt.h"

#ifdef HAVE_GETATTRLIST
#include <sys/attr.h>
#include <sys/paths.h>
#include <libkern/OSByteOrder.h>
#endif

/* Darwin 8 copyfile API. */
#ifdef HAVE_COPYFILE
#ifdef HAVE_COPYFILE_H
#include <copyfile.h>
#if defined(HAVE_WEAK_IMPORT) && (MAC_OS_X_VERSION_MIN_REQUIRED < 1040)
/* Support for weakly importing copyfile. */
#define WEAK_IMPORT_COPYFILE
extern int		copyfile(const char *from, const char *to,
			    copyfile_state_t state, copyfile_flags_t flags)
			    WEAK_IMPORT_ATTRIBUTE;
#endif /* HAVE_WEAK_IMPORT */
#else /* HAVE_COPYFILE_H */
int			copyfile(const char *from, const char *to,
			    void *state, uint32_t flags);
#define COPYFILE_ACL		(1<<0)
#define COPYFILE_XATTR		(1<<2)
#define COPYFILE_NOFOLLOW_SRC	(1<<18)
#if defined(HAVE_WEAK_IMPORT) && (MAC_OS_X_VERSION_MIN_REQUIRED < 1040)
/* Support for weakly importing copyfile. */
#define WEAK_IMPORT_COPYFILE
extern int		copyfile(const char *from, const char *to,
			    void *state, uint32_t flags)
			    WEAK_IMPORT_ATTRIBUTE;
#endif /* HAVE_WEAK_IMPORT */
#endif /* HAVE_COPYFILE_H */
#endif /* HAVE_COPYFILE */

#ifdef WEAK_IMPORT_COPYFILE
#define MayUseCopyFile()	(copyfile != NULL)
#elif defined(HAVE_COPYFILE)
#define MayUseCopyFile()	(1)
#else
#define MayUseCopyFile()	(0)
#endif

#include <libkern/OSByteOrder.h>

/*
 * Constants for file attributes subcommand. Need to be kept in sync with
 * tclUnixFCmd.c !
 */

enum {
    UNIX_GROUP_ATTRIBUTE,
    UNIX_OWNER_ATTRIBUTE,
    UNIX_PERMISSIONS_ATTRIBUTE,
#ifdef HAVE_CHFLAGS
    UNIX_READONLY_ATTRIBUTE,
#endif
#ifdef MAC_OSX_TCL
    MACOSX_CREATOR_ATTRIBUTE,
    MACOSX_TYPE_ATTRIBUTE,
    MACOSX_HIDDEN_ATTRIBUTE,
    MACOSX_RSRCLENGTH_ATTRIBUTE,
#endif
};

typedef u_int32_t OSType;

static int		GetOSTypeFromObj(Tcl_Interp *interp,
			    Tcl_Obj *objPtr, OSType *osTypePtr);
static Tcl_Obj *	NewOSTypeObj(const OSType newOSType);
static int		SetOSTypeFromAny(Tcl_Interp *interp, Tcl_Obj *objPtr);
static void		UpdateStringOfOSType(Tcl_Obj *objPtr);

static const Tcl_ObjType tclOSTypeType = {
    "osType",				/* name */
    NULL,				/* freeIntRepProc */
    NULL,				/* dupIntRepProc */
    UpdateStringOfOSType,		/* updateStringProc */
    SetOSTypeFromAny			/* setFromAnyProc */
};

enum {
    kIsInvisible = 0x4000,
};

#define kFinfoIsInvisible	(OSSwapHostToBigConstInt16(kIsInvisible))

typedef	struct finderinfo {
    u_int32_t type;
    u_int32_t creator;
    u_int16_t fdFlags;
    u_int32_t location;
    u_int16_t reserved;
    u_int32_t extendedFileInfo[4];
} __attribute__ ((__packed__)) finderinfo;

typedef struct fileinfobuf {
    u_int32_t info_length;
    u_int32_t data[8];
} fileinfobuf;

/*
 *----------------------------------------------------------------------
 *
 * TclMacOSXGetFileAttribute
 *
 *	Gets a MacOSX attribute of a file. Which attribute is controlled by
 *	objIndex. The object will have ref count 0.
 *
 * Results:
 *	Standard TCL result. Returns a new Tcl_Obj in attributePtrPtr if there
 *	is no error.
 *
 * Side effects:
 *	A new object is allocated.
 *
 *----------------------------------------------------------------------
 */

int
TclMacOSXGetFileAttribute(
    Tcl_Interp *interp,		 /* The interp we are using for errors. */
    int objIndex,		 /* The index of the attribute. */
    Tcl_Obj *fileName,		 /* The name of the file (UTF-8). */
    Tcl_Obj **attributePtrPtr)	 /* A pointer to return the object with. */
{
#ifdef HAVE_GETATTRLIST
    int result;
    Tcl_StatBuf statBuf;
    struct attrlist alist;
    fileinfobuf finfo;
    finderinfo *finder = (finderinfo *) &finfo.data;
    off_t *rsrcForkSize = (off_t *) &finfo.data;
    const char *native;

    result = TclpObjStat(fileName, &statBuf);

    if (result != 0) {
	Tcl_AppendResult(interp, "could not read \"", TclGetString(fileName),
		"\": ", Tcl_PosixError(interp), NULL);
	return TCL_ERROR;
    }

    if (S_ISDIR(statBuf.st_mode) && objIndex != MACOSX_HIDDEN_ATTRIBUTE) {
	/*
	 * Directories only support attribute "-hidden".
	 */

	errno = EISDIR;
	Tcl_AppendResult(interp, "invalid attribute: ",
		Tcl_PosixError(interp), NULL);
	return TCL_ERROR;
    }

    bzero(&alist, sizeof(struct attrlist));
    alist.bitmapcount = ATTR_BIT_MAP_COUNT;
    if (objIndex == MACOSX_RSRCLENGTH_ATTRIBUTE) {
	alist.fileattr = ATTR_FILE_RSRCLENGTH;
    } else {
	alist.commonattr = ATTR_CMN_FNDRINFO;
    }
    native = Tcl_FSGetNativePath(fileName);
    result = getattrlist(native, &alist, &finfo, sizeof(fileinfobuf), 0);

    if (result != 0) {
	Tcl_AppendResult(interp, "could not read attributes of \"",
		TclGetString(fileName), "\": ", Tcl_PosixError(interp), NULL);
	return TCL_ERROR;
    }

    switch (objIndex) {
    case MACOSX_CREATOR_ATTRIBUTE:
	*attributePtrPtr = NewOSTypeObj(
		OSSwapBigToHostInt32(finder->creator));
	break;
    case MACOSX_TYPE_ATTRIBUTE:
	*attributePtrPtr = NewOSTypeObj(
		OSSwapBigToHostInt32(finder->type));
	break;
    case MACOSX_HIDDEN_ATTRIBUTE:
	*attributePtrPtr = Tcl_NewBooleanObj(
		(finder->fdFlags & kFinfoIsInvisible) != 0);
	break;
    case MACOSX_RSRCLENGTH_ATTRIBUTE:
	*attributePtrPtr = Tcl_NewWideIntObj(*rsrcForkSize);
	break;
    }
    return TCL_OK;
#else
    Tcl_AppendResult(interp, "Mac OS X file attributes not supported", NULL);
    Tcl_SetErrorCode(interp, "TCL", "UNSUPPORTED", NULL);
    return TCL_ERROR;
#endif
}

/*
 *---------------------------------------------------------------------------
 *
 * TclMacOSXSetFileAttribute --
 *
 *	Sets a MacOSX attribute of a file. Which attribute is controlled by
 *	objIndex.
 *
 * Results:
 *	Standard TCL result.
 *
 * Side effects:
 *	As above.
 *
 *---------------------------------------------------------------------------
 */

int
TclMacOSXSetFileAttribute(
    Tcl_Interp *interp,		/* The interp for error reporting. */
    int objIndex,		/* The index of the attribute. */
    Tcl_Obj *fileName,		/* The name of the file (UTF-8). */
    Tcl_Obj *attributePtr)	/* New owner for file. */
{
#ifdef HAVE_GETATTRLIST
    int result;
    Tcl_StatBuf statBuf;
    struct attrlist alist;
    fileinfobuf finfo;
    finderinfo *finder = (finderinfo *) &finfo.data;
    off_t *rsrcForkSize = (off_t *) &finfo.data;
    const char *native;

    result = TclpObjStat(fileName, &statBuf);

    if (result != 0) {
	Tcl_AppendResult(interp, "could not read \"", TclGetString(fileName),
		"\": ", Tcl_PosixError(interp), NULL);
	return TCL_ERROR;
    }

    if (S_ISDIR(statBuf.st_mode) && objIndex != MACOSX_HIDDEN_ATTRIBUTE) {
	/*
	 * Directories only support attribute "-hidden".
	 */

	errno = EISDIR;
	Tcl_AppendResult(interp, "invalid attribute: ",
		Tcl_PosixError(interp), NULL);
	return TCL_ERROR;
    }

    bzero(&alist, sizeof(struct attrlist));
    alist.bitmapcount = ATTR_BIT_MAP_COUNT;
    if (objIndex == MACOSX_RSRCLENGTH_ATTRIBUTE) {
	alist.fileattr = ATTR_FILE_RSRCLENGTH;
    } else {
	alist.commonattr = ATTR_CMN_FNDRINFO;
    }
    native = Tcl_FSGetNativePath(fileName);
    result = getattrlist(native, &alist, &finfo, sizeof(fileinfobuf), 0);

    if (result != 0) {
	Tcl_AppendResult(interp, "could not read attributes of \"",
		TclGetString(fileName), "\": ", Tcl_PosixError(interp), NULL);
	return TCL_ERROR;
    }

    if (objIndex != MACOSX_RSRCLENGTH_ATTRIBUTE) {
	OSType t;
	int h;

	switch (objIndex) {
	case MACOSX_CREATOR_ATTRIBUTE:
	    if (GetOSTypeFromObj(interp, attributePtr, &t) != TCL_OK) {
		return TCL_ERROR;
	    }
	    finder->creator = OSSwapHostToBigInt32(t);
	    break;
	case MACOSX_TYPE_ATTRIBUTE:
	    if (GetOSTypeFromObj(interp, attributePtr, &t) != TCL_OK) {
		return TCL_ERROR;
	    }
	    finder->type = OSSwapHostToBigInt32(t);
	    break;
	case MACOSX_HIDDEN_ATTRIBUTE:
	    if (Tcl_GetBooleanFromObj(interp, attributePtr, &h) != TCL_OK) {
		return TCL_ERROR;
	    }
	    if (h) {
		finder->fdFlags |= kFinfoIsInvisible;
	    } else {
		finder->fdFlags &= ~kFinfoIsInvisible;
	    }
	    break;
	}

	result = setattrlist(native, &alist,
		&finfo.data, sizeof(finfo.data), 0);

	if (result != 0) {
	    Tcl_AppendResult(interp, "could not set attributes of \"",
		    TclGetString(fileName), "\": ", Tcl_PosixError(interp),
		    NULL);
	    return TCL_ERROR;
	}
    } else {
	Tcl_WideInt newRsrcForkSize;

	if (Tcl_GetWideIntFromObj(interp, attributePtr,
		&newRsrcForkSize) != TCL_OK) {
	    return TCL_ERROR;
	}

	if (newRsrcForkSize != *rsrcForkSize) {
	    Tcl_DString ds;

	    /*
	     * Only setting rsrclength to 0 to strip a file's resource fork is
	     * supported.
	     */

	    if (newRsrcForkSize != 0) {
		Tcl_AppendResult(interp,
			"setting nonzero rsrclength not supported", NULL);
		Tcl_SetErrorCode(interp, "TCL", "UNSUPPORTED", NULL);
		return TCL_ERROR;
	    }

	    /*
	     * Construct path to resource fork.
	     */

	    Tcl_DStringInit(&ds);
	    Tcl_DStringAppend(&ds, native, -1);
	    Tcl_DStringAppend(&ds, _PATH_RSRCFORKSPEC, -1);

	    result = truncate(Tcl_DStringValue(&ds), (off_t)0);
	    if (result != 0) {
		/*
		 * truncate() on a valid resource fork path may fail with a
		 * permission error in some OS releases, try truncating with
		 * open() instead:
		 */

		int fd = open(Tcl_DStringValue(&ds), O_WRONLY | O_TRUNC);

		if (fd > 0) {
		    result = close(fd);
		}
	    }

	    Tcl_DStringFree(&ds);

	    if (result != 0) {
		Tcl_AppendResult(interp,
			"could not truncate resource fork of \"",
			TclGetString(fileName), "\": ",
			Tcl_PosixError(interp), NULL);
		return TCL_ERROR;
	    }
	}
    }
    return TCL_OK;
#else
    Tcl_AppendResult(interp, "Mac OS X file attributes not supported", NULL);
    Tcl_SetErrorCode(interp, "TCL", "UNSUPPORTED", NULL);
    return TCL_ERROR;
#endif
}

/*
 *---------------------------------------------------------------------------
 *
 * TclMacOSXCopyFileAttributes --
 *
 *	Copy the MacOSX attributes and resource fork (if present) from one
 *	file to another.
 *
 * Results:
 *	Standard Tcl result.
 *
 * Side effects:
 *	MacOSX attributes and resource fork are updated in the new file to
 *	reflect the old file.
 *
 *---------------------------------------------------------------------------
 */

int
TclMacOSXCopyFileAttributes(
    const char *src,		/* Path name of source file (native). */
    const char *dst,		/* Path name of target file (native). */
    const Tcl_StatBuf *statBufPtr)
				/* Stat info for source file */
{
    if (MayUseCopyFile()) {
#ifdef HAVE_COPYFILE
	if (0 == copyfile(src, dst, NULL, (S_ISLNK(statBufPtr->st_mode)
		? COPYFILE_XATTR | COPYFILE_NOFOLLOW_SRC
		: COPYFILE_XATTR | COPYFILE_ACL))) {
	    return TCL_OK;
	}
#endif /* HAVE_COPYFILE */
    } else {
#if (!defined(HAVE_COPYFILE) || defined(WEAK_IMPORT_COPYFILE)) && defined(HAVE_GETATTRLIST)
	struct attrlist alist;
	fileinfobuf finfo;
	off_t *rsrcForkSize = (off_t *) &finfo.data;
	Tcl_DString srcBuf, dstBuf;
	int result;

	bzero(&alist, sizeof(struct attrlist));
	alist.bitmapcount = ATTR_BIT_MAP_COUNT;
	alist.commonattr = ATTR_CMN_FNDRINFO;

	if (getattrlist(src, &alist, &finfo, sizeof(fileinfobuf), 0)) {
	    return TCL_ERROR;
	}
	if (setattrlist(dst, &alist, &finfo.data, sizeof(finfo.data), 0)) {
	    return TCL_ERROR;
	}

	/*
	 * If we're a directory, we're done as they never have resource forks.
	 */

	if (S_ISDIR(statBufPtr->st_mode)) {
	    return TCL_OK;
	}

	/*
	 * We only copy a non-empty resource fork, so determine if that's the
	 * case first.
	 */

	alist.commonattr = 0;
	alist.fileattr = ATTR_FILE_RSRCLENGTH;
	if (getattrlist(src, &alist, &finfo, sizeof(fileinfobuf), 0)) {
	    return TCL_ERROR;
	} else if (*rsrcForkSize == 0) {
	    return TCL_OK;
	}

	/*
	 * Construct paths to resource forks.
	 */

	Tcl_DStringInit(&srcBuf);
	Tcl_DStringAppend(&srcBuf, src, -1);
	Tcl_DStringAppend(&srcBuf, _PATH_RSRCFORKSPEC, -1);
	Tcl_DStringInit(&dstBuf);
	Tcl_DStringAppend(&dstBuf, dst, -1);
	Tcl_DStringAppend(&dstBuf, _PATH_RSRCFORKSPEC, -1);

	/*
	 * Do the copy.
	 */

	result = TclUnixCopyFile(Tcl_DStringValue(&srcBuf),
		Tcl_DStringValue(&dstBuf), statBufPtr, 1);
	Tcl_DStringFree(&srcBuf);
	Tcl_DStringFree(&dstBuf);
	if (result == 0) {
	    return TCL_OK;
	}
#endif /* (!HAVE_COPYFILE || WEAK_IMPORT_COPYFILE) && HAVE_GETATTRLIST */
    }
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * TclMacOSXMatchType --
 *
 *	This routine is used by the globbing code to check if a file matches a
 *	given mac type and/or creator code.
 *
 * Results:
 *	The return value is 1, 0 or -1 indicating whether the file matches the
 *	given criteria, does not match them, or an error occurred (in wich
 *	case an error is left in interp).
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TclMacOSXMatchType(
    Tcl_Interp *interp,		/* Interpreter to receive errors. */
    const char *pathName,	/* Native path to check. */
    const char *fileName,	/* Native filename to check. */
    Tcl_StatBuf *statBufPtr,	/* Stat info for file to check */
    Tcl_GlobTypeData *types)	/* Type description to match against. */
{
#ifdef HAVE_GETATTRLIST
    struct attrlist alist;
    fileinfobuf finfo;
    finderinfo *finder = (finderinfo *) &finfo.data;
    OSType osType;

    bzero(&alist, sizeof(struct attrlist));
    alist.bitmapcount = ATTR_BIT_MAP_COUNT;
    alist.commonattr = ATTR_CMN_FNDRINFO;
    if (getattrlist(pathName, &alist, &finfo, sizeof(fileinfobuf), 0) != 0) {
	return 0;
    }
    if ((types->perm & TCL_GLOB_PERM_HIDDEN) &&
	    !((finder->fdFlags & kFinfoIsInvisible) || (*fileName == '.'))) {
	return 0;
    }
    if (S_ISDIR(statBufPtr->st_mode)
	    && (types->macType || types->macCreator)) {
	/*
	 * Directories don't support types or creators.
	 */

	return 0;
    }
    if (types->macType) {
	if (GetOSTypeFromObj(interp, types->macType, &osType) != TCL_OK) {
	    return -1;
	}
	if (osType != OSSwapBigToHostInt32(finder->type)) {
	    return 0;
	}
    }
    if (types->macCreator) {
	if (GetOSTypeFromObj(interp, types->macCreator, &osType) != TCL_OK) {
	    return -1;
	}
	if (osType != OSSwapBigToHostInt32(finder->creator)) {
	    return 0;
	}
    }
#endif
    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * GetOSTypeFromObj --
 *
 *	Attempt to return an OSType from the Tcl object "objPtr".
 *
 * Results:
 *	Standard TCL result. If an error occurs during conversion, an error
 *	message is left in interp->objResult.
 *
 * Side effects:
 *	The string representation of objPtr will be updated if necessary.
 *
 *----------------------------------------------------------------------
 */

static int
GetOSTypeFromObj(
    Tcl_Interp *interp,		/* Used for error reporting if not NULL. */
    Tcl_Obj *objPtr,		/* The object from which to get an OSType. */
    OSType *osTypePtr)		/* Place to store resulting OSType. */
{
    int result = TCL_OK;

    if (objPtr->typePtr != &tclOSTypeType) {
	result = tclOSTypeType.setFromAnyProc(interp, objPtr);
    }
    *osTypePtr = (OSType) objPtr->internalRep.longValue;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * NewOSTypeObj --
 *
 *	Create a new OSType object.
 *
 * Results:
 *	The newly created OSType object is returned, it has ref count 0.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static Tcl_Obj *
NewOSTypeObj(
    const OSType osType)	/* OSType used to initialize the new
				 * object. */
{
    Tcl_Obj *objPtr;

    TclNewObj(objPtr);
    Tcl_InvalidateStringRep(objPtr);
    objPtr->internalRep.longValue = (long) osType;
    objPtr->typePtr = &tclOSTypeType;
    return objPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * SetOSTypeFromAny --
 *
 *	Attempts to force the internal representation for a Tcl object to
 *	tclOSTypeType, specifically.
 *
 * Results:
 *	The return value is a standard object Tcl result. If an error occurs
 *	during conversion, an error message is left in the interpreter's
 *	result unless "interp" is NULL.
 *
 *----------------------------------------------------------------------
 */

static int
SetOSTypeFromAny(
    Tcl_Interp *interp,		/* Tcl interpreter */
    Tcl_Obj *objPtr)		/* Pointer to the object to convert */
{
    const char *string;
    int length, result = TCL_OK;
    Tcl_DString ds;
    Tcl_Encoding encoding = Tcl_GetEncoding(NULL, "macRoman");

    string = Tcl_GetStringFromObj(objPtr, &length);
    Tcl_UtfToExternalDString(encoding, string, length, &ds);

    if (Tcl_DStringLength(&ds) > 4) {
	if (interp) {
	    Tcl_AppendResult(interp, "expected Macintosh OS type but got \"",
		    string, "\": ", NULL);
	    Tcl_SetErrorCode(interp, "TCL", "VALUE", "MAC_OSTYPE", NULL);
	}
	result = TCL_ERROR;
    } else {
	OSType osType;
	char bytes[4] = {'\0','\0','\0','\0'};

	memcpy(bytes, Tcl_DStringValue(&ds), (size_t)Tcl_DStringLength(&ds));
	osType = (OSType) bytes[0] << 24 |
		 (OSType) bytes[1] << 16 |
		 (OSType) bytes[2] <<  8 |
		 (OSType) bytes[3];
	TclFreeIntRep(objPtr);
	objPtr->internalRep.longValue = (long) osType;
	objPtr->typePtr = &tclOSTypeType;
    }
    Tcl_DStringFree(&ds);
    Tcl_FreeEncoding(encoding);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * UpdateStringOfOSType --
 *
 *	Update the string representation for an OSType object. Note: This
 *	function does not free an existing old string rep so storage will be
 *	lost if this has not already been done.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The object's string is set to a valid string that results from the
 *	OSType-to-string conversion.
 *
 *----------------------------------------------------------------------
 */

static void
UpdateStringOfOSType(
    register Tcl_Obj *objPtr)	/* OSType object whose string rep to
				 * update. */
{
    char string[5];
    OSType osType = (OSType) objPtr->internalRep.longValue;
    Tcl_DString ds;
    Tcl_Encoding encoding = Tcl_GetEncoding(NULL, "macRoman");
    unsigned len;

    string[0] = (char) (osType >> 24);
    string[1] = (char) (osType >> 16);
    string[2] = (char) (osType >>  8);
    string[3] = (char) (osType);
    string[4] = '\0';
    Tcl_ExternalToUtfDString(encoding, string, -1, &ds);
    len = (unsigned) Tcl_DStringLength(&ds) + 1;
    objPtr->bytes = ckalloc(len);
    memcpy(objPtr->bytes, Tcl_DStringValue(&ds), len);
    objPtr->length = Tcl_DStringLength(&ds);
    Tcl_DStringFree(&ds);
    Tcl_FreeEncoding(encoding);
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */