Tcl Library Source Code

Check-in [a9488befa9]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:mime: Internal rewrite plus API redesign. ncgi: Use mime module instead of bespoke routines. New modules: ego chan.
Timelines: family | ancestors | descendants | both | pooryorick
Files: files | file ages | folders
SHA3-256: a9488befa9bdb1cad39ae119389f4d5fcd768ea0cbd779e72511b5c3f31c3023
User & Date: pooryorick 2018-11-20 07:32:57
Original Comment: mime: Internal rewrite plus API redesign. ncgi: Use mime module instea of bespoke routines. New modules: ego chan.
References
2018-12-05
07:30 Pending ticket [1213545fff]: mime: Provide getheaders and getbody (enhancement) plus 6 other changes artifact: 76c31b0804 user: pooryorick
Context
2021-05-01
10:50
mime: Internal rewrite plus API redesign. ncgi: Use mime module instead of bespoke routines. New modules: ego chan. check-in: f9f98e681e user: pooryorick tags: mime
2018-11-20
15:13
Make {chan getslimit} a routine that specializes an existing channel command rather than a channel command itself. check-in: 5440f0b939 user: pooryorick tags: pooryorick
07:32
mime: Internal rewrite plus API redesign. ncgi: Use mime module instead of bespoke routines. New modules: ego chan. check-in: a9488befa9 user: pooryorick tags: pooryorick
2018-11-05
08:09
ncgi use the mime module to generate the response headers mime add -addmimeversion and -addcontentid options check-in: 37008172d9 user: pooryorick tags: pooryorick
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Added modules/chan/base.tcl.

































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#! /usr/bin/env tclsh

# # ## ### ##### ######## #############
# copyright
#
#     2018
#
#     Poor Yorick
# # ## ### ##### ######## #############


proc .init {_ channame args} {
    $_ .vars chan close
    set chan $channame
    $_ .ondelete [list ::apply {{_ channame} {
	$_ .vars close
	if {$close} {
	    ::close $channame
	}
    }} $_ $channame]
    set close 1
    if {[llength $args]} {
	$_ configure {*}$args
    }
    return $_
}
.my .method .init


proc configure {_ args} {
    $_ .vars chan
    if {[llength $args] == 1} {
	lassign $args key
	switch $key {
	    -chan {
		return $chan
	    }
	}
	set res [::chan configure $chan {*}$args]
    } elseif {[llength $args]} {
	dict size $args
	foreach {key val} $args[set args {}] {
	    switch $key {
		-chan {
		    set chan $val
		}
		-close {
		    $_ $ close [expr {!!$val}]
		}
		default {
		    lappend args $key $val
		}
	    }
	}
	if {[llength $args]} {
	    ::chan configure $chan {*}$args
	}
	set res {}
    } else {
	set res [list {*}[::chan configure $chan {*}$args] -chan $chan]
    }
    return $res
}
.my .method configure


proc copy {_ target} {
    ::chan copy [$_ $ chan] $target
}
.my .method copy


proc gets {_ args} {
    uplevel 1 [list ::gets [$_ $ chan] {*}$args]
}
.my .method gets


proc pending {_ args} {
    uplevel 1 [list ::pending {*}$args [$_ $ chan]]
}
.my .method pending


proc puts {_ args} {
    uplevel 1 [list ::puts {*}[lrange $args 0 end-1] [$_ $ chan] {*}[
	lrange $args end end]]
}
.my .method puts


proc read {_ args} {
    uplevel 1 [list ::read {*}[lrange $args 0 end-1] [$_ $ chan] {*}[
	lrange $args end end]]
}
.my .method read


apply [list {} {
    foreach name {
	blocked close eof event flush names pop posteven push seek tell
	truncate
    } {
	proc $name {_ args} [string map [
	    list @name@ [list $name]] {
	    ::chan @name@ [$_ $ chan] {*}$args
	}]
	.my .method $name
    }
} [namespace current]]


Added modules/chan/base.test.



































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#! /usr/bin/env tclsh

source [file join \
	[file dirname [file dirname [file dirname [
	    file normalize [info script]/...]]]]/devtools/testutilities.tcl]

testsNeedTcl     8.5
testsNeedTcltest 1.0-

package require tcl::chan::string 
package require {chan base}
namespace import ::tcllib::chan::base

proc main {} {
    variable done

    set data1 abcdefghijklmnopqrstuvwxyz

    test chan-object-closeondelete {
    } -body {
	base .new chan1 [::tcl::chan::string $data1]
	set name [chan1 $ chan]
	lappend res [expr {$name in [chan names]}]
	chan1 close
	lappend res [expr {$name in [chan names]}]
    } -result {1 0} 

    testsuiteCleanup
    set done 1 
}

after 0 coroutine [info cmdcount]_main main  
vwait [namespace current]::done

Added modules/chan/getslimit.tcl.



















































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#! /usr/bin/env tclsh

# # ## ### ##### ######## #############
# copyright
#
#     2018
#
#     Poor Yorick
# # ## ### ##### ######## #############


variable buf bufcount eof getslimit

proc .init {_ args} {
    $_ .vars eof buf bufcount getslimit
    set eof 0
    set buf {}
    set bufcount 0
    set getslimit -1
    uplevel 1 [list $_ .prototype .init {*}$args]
}
.my .method .init


proc configure {_ args} {
    $_ .vars getslimit
    if {[llength $args] == 1} {
	switch [lindex $args 0] {
	    -getslimit {
		set res $getslimit
	    } default {
		set res [uplevel 1 [list $_ .prototype configure {*}$args]]
	    }
	}
    } elseif {[llength $args]} {
	dict size $args
	foreach {key val} $args[set args {}] {
	    if {$key eq {-getslimit}} {
		set getslimit $val
	    } else {    
		lappend args $key $val
	    }
	}
	if {[llength $args]} {
	    uplevel 1 [list $_ .prototype configure {*}$args]
	}
	set res {}
    } else {
	set res [list {*}[uplevel 1 [
	    list $_ .prototype configure {*}$args]] -getslimit $getslimit]
    }
    return $res
}
.my .method configure


proc  eof _ {
    $_ .vars bufcount eof
    return [expr {$eof || ( [$_ .prototype eof] && $bufcount == 0 )}]
}
.my .method eof


proc gets {_ args} {
    $_ .vars buf bufcount chan eof getslimit 
    switch [llength $args] {
	1 {
	    lassign $args varname
	    upvar 1 $varname resvar
	}
	0 {}
	default {
	    #this is just to generate the error message
	    ::gets [$_ $ chan] {*}$args
	}
    }

    if {$eof} {
	if {[info exists varname]} {
	    set resvar {}
	    return -1
	}
	return {}
    }

    if {[string first \n $buf] < 0 && ![::eof $chan]} {
	if {$getslimit >= 0} {
	    append buf [$_ read $getslimit]
	} else {
	    append buf [$_ read]
	}
    }

    if {[regexp {^(.*?)\n(.*)$} $buf -> res remainder]} {
	set buf $remainder
	set bufcount [expr {$bufcount - [string length $res] - 1}]
    } else {
	# must be at eof
	set res $buf
	set buf {}
	set bufcount 0
	if {[::eof $chan]} {
	    set eof 1
	}
    }

    if {[llength $args]} {
	set args [lassign $args[set args {}] varname]
	set resvar $res

	if {$res eq {} && $eof} {
	    return -1
	} else {
	    return [string length $res]
	}
    } else {
	return $res
    }
}
.my .method gets



proc read {_ args} {
    $_ .vars buf eof bufcount 
    if {$eof} {
	return {}
    }
    if {$bufcount} {
	if {[llength $args]} {
	    lassign $args size
	    if {$size <= $bufcount} {
		set res [string range $buf 0 [expr {$size - 1}]]
		set buf [string range $buf $size end]
		incr bufcount -[string length $res]
	    } else {
		set readsize [expr {$size - $bufcount}]
		set res $buf[set buf {}][$_ .prototype read $readsize]
		set bufcount 0
	    }
	} else {
	    set bufcount 0
	    set res $buf[set buf {}][$_ .prototype read {*}$args]
	}
    } else {
	set res [$_ .prototype read {*}$args]
    }
    return $res
}
.my .method read


package provide tcllib::chan::getslimit 1

Added modules/chan/getslimit.test.











































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#! /usr/bin/tclsh

source [file join \
	[file dirname [file dirname [file dirname [
	    file normalize [info script]/...]]]]/devtools/testutilities.tcl]

testsNeedTcl     8.5
testsNeedTcltest 1.0-

package require {chan getslimit}

package require tcl::chan::memchan 
package require tcl::chan::string 
namespace import ::tcllib::chan::getslimit

proc main {} {
    variable done
    set data1 abcdefghijklmnopqrstuvwxyz


    test getslimit-configure {} -body {
	getslimit .new chan1 [::tcl::chan::memchan]
	chan1 configure -getslimit 33
	chan1 configure -getslimit
    } -cleanup {
	rename chan1 {}
    } -result 33


    test getslimit-under {
    } -body {
	getslimit .new chan1 [::tcl::chan::string $data1] -getslimit 1000
	chan1 gets
    } -cleanup {
	rename chan1 {}
    } -result $data1


    test getslimit-exceeded {
    } -body {
	getslimit .new chan1 [::tcl::chan::string [
	    string repeat $data1 100]] -getslimit 10
	chan1 gets
    } -cleanup {
	rename chan1 {}
    } -result {abcdefghij}

    test getslimit-read {
	read is unaffacted by the limit
    } -body {
	getslimit .new chan1 [::tcl::chan::string $data1]
	chan1 configure -getslimit 10
	lappend res [chan1 read 15]
	lappend res [chan1 read 3]
	lappend res [chan1 read 1]
	lappend res [chan1 read]
	lappend res [chan1 eof]
	lappend res [chan1 read]
	lappend res [chan1 eof]
    } -cleanup {
	rename chan1 {}
    } -result {abcdefghijklmno pqr s tuvwxyz 1 {} 1}

    testsuiteCleanup
    set done 1 
}

after 0 coroutine [info cmdcount]_main main  
vwait [namespace current]::done

Added modules/chan/pkgIndex.tcl.

















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#! /usr/bin/env tclsh


package ifneeded {chan getslimit} 0.1 [list ::apply {dir {
    package require {chan base}
    ::tcllib::chan::base .new ::tcllib::chan::getslimit
    ::tcllib::chan::getslimit .specialize
    ::tcllib::chan::getslimit .eval [list ::source $dir/getslimit.tcl]
    namespace eval ::tcllib::chan {
	namespace export getslimit
    }
    package provide {chan getslimit} 0.1
}} $dir]


package ifneeded {chan base} 0.1 [list ::apply {dir {
    package require ego
    tcllib::ego .new ::tcllib::chan::base 
    ::tcllib::chan::base .eval [list ::source  $dir/base.tcl]
    namespace eval ::tcllib::chan {
	namespace export base
    }
    package provide {chan base} 0.1
}} $dir]

Added modules/ego/ego.tcl.



































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#! /bin/env tclsh

# # ## ### ##### ######## #############
# copyright
#
#     2018
#
#     Poor Yorick
# # ## ### ##### ######## #############

namespace ensemble create
namespace export *

proc .method {_ name args} {
	if {![llength $args]} {
		lappend args $name
	}
	set args [linsert $args[set args {}] 1 $_]
	set map [namespace ensemble configure $_ -map]
	dict set map $name $args 
	uplevel 1 [list ::namespace ensemble configure $_ -map $map]
	return
}
.method [namespace current] .method


proc $ {_ name args} {
	namespace upvar [$_ .namespace] $name var
	if {[llength $args]} {
		if {[llength $args] > 1} {
			error [list {wrong # args}]
		}
		set var [lindex $args 0]
	}
	return $var
}
.method [namespace current] $


proc .as {_ other name args} {
	set map [namespace ensemble configure $_ -map]
	set cmd [dict get $map $name]
	if {[lindex $name 1] ne $_} {
		error [list {not a method} $name]
	}
	set cmd [lreplace $cmd 1 1 $other]
	::tailcall {*}$cmd
}
.method [namespace current] .as


proc .eval {_ args} {
	::tailcall ::namespace eval [$_ .namespace] {*}$args
}
.method [namespace current] .eval 


proc .insert {_ name} {
	set unknown1 [namespace ensemble configure $_ -unknown]
	set prototype1 [namespace ensemble configure $_ -prototype]

	if {[llength $unknown1]} {
		namespace ensemble configure $name -prototype $prototype1 \
			-unknown $unknown1 
	}

	namespace enemble configure $_ -prototype [list ::lindex $name] -unknown $unknown1
	return
}


proc .name _ {
	return $_
}
.method [namespace current] .name 


proc .namespace _ {
	namespace ensemble configure $_ -namespace
}
.method [namespace current] .namespace 


proc .new {_ name args} {
	global env
	set ns [uplevel 1 [list ::namespace eval $name {
		::namespace ensemble create
		::variable configured 0
		::namespace current
	}]]
	::trace add command $ns delete [list ::apply {{ns oldname newname op} {
		if {[namespace exists $ns]} {
			namespace delete $ns
		}
	}} $ns]

	set prototype $_
	set map [namespace ensemble configure $_ -map]

	set prototypes {}
	while {[dict exists $map .prototype]} {
		set prototypes [list $map {*}$prototypes[set prototypes {}]]
		lassign [dict get $map .prototype] prototype 
		set map [namespace ensemble configure $prototype -map]
	}

	set map {}
	foreach {key val} [namespace ensemble configure $prototype -map] { 
		if {$key ne {.prototype}} {
			if {[lindex $val 1] eq $_} {
				set val [lreplace $val[set val {}] 1 1 $ns]
			}
		} else {
			error [list {how did we get to here?}]
		}
		lappend map $key $val 
	}

	namespace ensemble configure $ns -map $map

	set prototype $ns
	foreach map $prototypes {
		$ns .specialize
		dict unset map .prototype
		dict for {name cmd} $map {
			if {[lindex $cmd 1] eq $_} {
				# remove the original name from index 1 because .method is
				# going to add it back 
				$ns .method $name {*}[lreplace $cmd[set cmd {}] 1 1]
			} else {
				$ns .routine $name {*}$cmd
			}
		}
	}

	interp alias {} ${ns}::.my {} $ns 

	if {[llength $args]} {
		tailcall $ns .init {*}$args
	} else {
		return $ns
	}
}
.method [namespace current] .new 


proc .ondelete {_ trace args} {
    if {[llength $args] == 1} {
	lassign $args script
	trace remove command $_ delete $trace
	set trace {}
	if {$script ne {}} {
	    set trace [list apply {{script args} {
		try $script
	    }} $script]
	    trace add command $_ delete $trace
	}
	$_ .method .ondelete $trace
    } elseif {[llength $args]} {
	error [list {wrong # args}]
    }
    return $trace
}
.method [namespace current] .ondelete .ondelete {}


proc .routine {_ name args} {
	if {![llength $args]} {
		lappend args $name
	}
	set map [namespace ensemble configure $_ -map]
	dict set map $name $args
	uplevel 1 [list ::namespace ensemble configure $_ -map $map]
	return
}
.method [namespace current] .routine 


proc .specialize {_ args} {
	set ns [$_ .namespace] 
	while {[namespace which [set name ${ns}::[
		info cmdcount]_prototype]] ne {}} {}
	rename $_ $name
	
	set new [namespace eval ${ns} [
		list namespace ensemble create -command $_ -map [list \
			.prototype [list $name]
		] -unknown [
			list ::apply {{_ name args} {

			set prototype [lindex [dict get [namespace ensemble configure $_ -map] .prototype] 0]
			list $prototype $name
		}}]]]

	::trace add command $new delete [list ::apply {{ns oldname newname op} {
		if {[namespace exists $ns]} {
			namespace delete $ns
		}
	}} $ns]
	return
}
.method [namespace current] .specialize 


proc .vars {_ args} {
	set vars {}
	foreach arg $args {
		lassign $arg source target
		if {[llength $arg] == 1} {
			set target $source
		}
		lappend vars $source $target
	}
	uplevel 1 [list ::namespace upvar $_ {*}$vars]
}
.method [namespace current] .vars 


proc = {_ name val} {
	set [$_ .namespace]::$name $val
}
.method [namespace current] = 



Added modules/ego/pkgIndex.tcl.













>
>
>
>
>
>
1
2
3
4
5
6
#! /usr/bin/env tclsh

package ifneeded ego 0.1 [list ::apply {dir {
    namespace eval ::tcllib::ego [list ::source $dir/ego.tcl]
    package provide ego 0.1
}} $dir]

Changes to modules/mime/mime.man.

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
[para]

Provides commands to create and manipulate Internet messages.

[list_begin definitions]


[call [cmd ::mime::initialize] [
    opt "[option -canonical] [arg type/subtype]"] [
    opt "[option -params] [arg dictionary]"] [
    opt "[option -encoding] [arg value]"] [
    opt "[option -headers] [arg dictionary]"] [
    opt "[option -addcontentid] [arg boolean]"] [
    opt "[option -addmimeversion] [arg boolean]"] [
    opt "([option -chan] [arg name] | [option -file] [arg name] | [
	option -string] [arg value] | [option -parts] [arg parts])"]]

Parses a message and returns a token for the message.  One of [

    option -chan

], [

    option -file

], or [

    option -string
    
] must be provided as the source of the input.  If [
















    option -canonical
    

] is provided the input is the body only and is already formatted according to

the provided [

    arg type/subtype
    
], and therefore should not be parsed.  If [

    arg parts
    
] is provided it is a list of tokens for messages that comprise a [

    const multipart/mixed

    
] message body.  [


    option -params

] is a multidict (a dictionary where the keys may not be unique)
of parameters for the [



    const Content-Type

    

] header.  [








    option -headers
    
] is a multidict of headers.  If [

    arg addcontentid
] is provided, it is a boolean value indicating whether a [
    const Content-Id
] header field should be added to the message.  By default, this

header is added to non-canonical messages.  If [

    arg addmimeversion

] is provided, it is a boolean value indicating whether a [
    const MIME-Version
] header should be added to non-canonical messages.  By default, this header is
added to non-canonical messages.




[para]

[option -encoding] sets the [const Content-Transfer-Encoding].



[call [cmd ::mime::body] [arg token] [opt [option -decode]] [opt "[option -blocksize] [arg octets]"]"]

Returns as a string in canonical form the body of the message corresponding to 
[arg token].



[para]

If [option -blocksize] is provided, returns a command that itself returns up to
the next [arg octets] of the message each time it's called, and returns a code
of [const break] when finished, deleting itself as well.  If [arg octets] is
the empty string, a default value is used.  Pauses the current coroutine as
needed to wait for input.


[para]


[option -decode] converts the message body from the character set it is encoded
in.







|
<
<
<
<
<
<
<
<

|











|
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
|
|
>
|
>
|

|
|
|

|
|
|

<
>

<
>

|

<
<
>

>
|
>
|
>
|
>
>
>
>
>
>
>
|
|
|
|
>
|
<
|
|
>
|
>
|
>
|
|
|
|

>
>

<

<
>




|
|
>







|
<







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
[para]

Provides commands to create and manipulate Internet messages.

[list_begin definitions]


[call [cmd ::mime::initialize] [opt [arg options]]]









Parses a message and returns a token for the message.  One and only one of [

    option -chan

], [

    option -file

], or [

    option -string
    
] must be provided as the source of the input.  Optional arguments are
processed such that later arguments override earlier arguments.  For example,
provide [option -addcontentid] [const 1] after [option "-spec [const http]"]  has disabled
that option.  The optional arguments are

[list_begin definitions]

    [def "[option -addcontentid] [arg boolean]"]
   
	Indicates whether a [const Content-ID] header field should be added to
	the message.  By default, this header is added to non-canonical
	messages.

    [def "[option -addmimeversion] [arg boolean]"]
    
	Indicates whether a [const MIME-Version] header should be added to
	non-canonical messages.  By default, this header is added to
	non-canonical messages.

    [def "[option -canonical] [arg type/subtype]"]

	The input message is the body only and is in the format
	specified by the provided [

	    arg type/subtype
	    
	], and therefore should not be parsed.

    [def "[option -chan] [arg channel]"]

	The name of an ensemble command providing the standard channel commands.


    [def "[option -encoding] [arg encoding]"]
    

	sets the [const Content-Transfer-Encoding].

    [def "[option -file] [arg string]"]



	The file providing the input message.

    [def "[option -headers] [arg headers]"]

	[arg headers] is a multidict of headers.

    [def "[option -spec] [arg spec]"]

	[arg spec] is one of [const mime] (the default) or [const http],
	indicating what specification to conform to.  For [const mime], the
	default [const Content-Type] is [const text/plain] and the character
	set is assumed to be [const US-ASCII].  For [const http], the default
	[const Content-Type] is [const text/html], the [const charset] is
	[const utf-8], and  [const MIME-Version] and [const Content-ID] headers
	are by default not automatically added.
   
    [def "[option -params] [arg params]"]

	[arg params] is a multidict (a dictionary where the keys may not be
	unique) of parameters for the [


	    const Content-Type
    
	] header. 

    [def "[option -parts] [arg parts]"]

	[arg parts] is  list of tokens for messages that comprise a [

	    const multipart/mixed
	    
	] message body.

    [def "[option -string] [arg string]"]
	The string providing the input message.




[list_end]


[call [cmd ::mime::body] [arg token] [opt [option -decode]] [opt "[option -blocksize] [arg octets]"]"]

Sets to [const 0] the cursor for the channel hodling the body of the message
corresponding to [arg token] and returns the name of a channel command for
that channel.


[para]

If [option -blocksize] is provided, returns a command that itself returns up to
the next [arg octets] of the message each time it's called, and returns a code
of [const break] when finished, deleting itself as well.  If [arg octets] is
the empty string, a default value is used. 



[para]


[option -decode] converts the message body from the character set it is encoded
in.
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
[call [cmd ::mime::serialize] [arg token] [opt [option -level]] [
    opt "[option -chan] [arg channel]"]]

Returns the serialization of the message corresponding to [arg token].  If
[option -chan] is provided, writes the serialization to [arg channel] and returns the
empty string.  [option -level], if provided, indicates the level of the part
in the message hierarchy.  The [const MIME-Version] header is only included at
level [const 0].  Yields from the current coroutine as needed to wait for input to
become available.


[call [cmd ::mime::parseaddress] [arg addresses]]

Returns a list describing the comma-separated 822-style [arg addresses].









|
<







333
334
335
336
337
338
339
340

341
342
343
344
345
346
347
[call [cmd ::mime::serialize] [arg token] [opt [option -level]] [
    opt "[option -chan] [arg channel]"]]

Returns the serialization of the message corresponding to [arg token].  If
[option -chan] is provided, writes the serialization to [arg channel] and returns the
empty string.  [option -level], if provided, indicates the level of the part
in the message hierarchy.  The [const MIME-Version] header is only included at
level [const 0].



[call [cmd ::mime::parseaddress] [arg addresses]]

Returns a list describing the comma-separated 822-style [arg addresses].


Changes to modules/mime/mime.tcl.

17
18
19
20
21
22
23
24
25
26

27
28
29
30
31
32
33
34
35
36
37
38
39
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# Influenced by Borenstein's/Rose's safe-tcl (circa 1993) and Darren New's
# unpublished package of 1999.
#

# new string features and inline scan are used, requiring 8.3.
package require Tcl 8.6



package require tcl::chan::memchan
package require tcl::chan::string
package require coroutine
namespace eval ::mime {
    namespace path ::coroutine::util {*}[namespace path]
}
package require sha256

package provide mime 1.7

if {[catch {package require Trf 2.0}]} {

    # Fall-back to tcl-based procedures of base64 and quoted-printable encoders







|

|
>


|
|
<
<







17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


32
33
34
35
36
37
38
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# Influenced by Borenstein's/Rose's safe-tcl (circa 1993) and Darren New's
# unpublished package of 1999.
#

# new string features and inline scan are used, requiring 8.3.
package require Tcl 8.6.9

package require namespacex
package require tcl::chan::cat
package require tcl::chan::memchan
package require tcl::chan::string
package require {chan base}
package require {chan getslimit}


package require sha256

package provide mime 1.7

if {[catch {package require Trf 2.0}]} {

    # Fall-back to tcl-based procedures of base64 and quoted-printable encoders
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
#
# state variables:
#
#     canonicalP: input is in its canonical form
#     encoding: transfer encoding
#     version: MIME-version
#     header: dictionary (keys are lower-case)
#     value: either "file", "parts", or "string"
#
#     file: input file
#     fd: cached file-descriptor, typically for root
#     root: token for top-level part, for (distant) subordinates
#     offset: number of octets from beginning of file/string
#     count: length in octets of (encoded) content
#
#     parts: list of bodies (tokens)
#
#     string: input string
#
#     cid: last child-id assigned
#


namespace eval ::mime {

    variable mime
    array set mime {uid 0 cid 0}








|




<




<
<

<







73
74
75
76
77
78
79
80
81
82
83
84

85
86
87
88


89

90
91
92
93
94
95
96
#
# state variables:
#
#     canonicalP: input is in its canonical form
#     encoding: transfer encoding
#     version: MIME-version
#     header: dictionary (keys are lower-case)
#     value: either "chan" or  "parts"
#
#     file: input file
#     fd: cached file-descriptor, typically for root
#     root: token for top-level part, for (distant) subordinates

#     count: length in octets of (encoded) content
#
#     parts: list of bodies (tokens)
#


#     cid: last child-id assigned



namespace eval ::mime {

    variable mime
    array set mime {uid 0 cid 0}

323
324
325
326
327
328
329
330
331
332

333
334
335
336




337
338
339
340
341
342
343
    namespace export {*}{
	datetime finalize getbody header initialize mapencoding parseaddress
	property reversemapencoding serialize setheader uniqueID
    }
}


proc ::mime::addchan {token fd} {
    variable channels
    upvar 0 $token state

    if {[info exists state(fd)]} {
	error [list {a channel is already present}]
    }
    set state(fd) $fd




    incr channels($fd)
    return
}


# ::mime::addr_next --
#







|


>
|


|
>
>
>
>







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
    namespace export {*}{
	datetime finalize getbody header initialize mapencoding parseaddress
	property reversemapencoding serialize setheader uniqueID
    }
}


proc ::mime::addchan {token chan} {
    variable channels
    upvar 0 $token state
    upvar 0 state(fd) fd
    if {[info exists fd]} {
	error [list {a channel is already present}]
    }

    if {[$chan configure -encoding] ne {binary}} {
	$chan configure -translation auto
    }
    set fd $chan
    incr channels($fd)
    return
}


# ::mime::addr_next --
#
907
908
909
910
911
912
913
914
915

916
917
918
919
920
921


922
923
924
925
926

927
928



929
930




931
932

933
934
935

936
937
938

939
940
941

942
943
944
945
946
947
948


949
950

951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208




1209








1210
1211
1212
1213
1214
1215
1216
        set mbox [string range $mbox 0 [expr {$x - 1}]]
    }

    return [string trim $mbox \"]
}


# ::mime::body --
#

#    mime::body returns the body of a leaf MIME part in canonical form.
#
#    If the -command option is present, then it is repeatedly invoked
#    with a fragment of the body as this:
#
#        uplevel #0 $callback [list "data" $fragment]


#
#    (The -blocksize option, if present, specifies the maximum size of
#    each fragment passed to the callback.)
#    When the end of the body is reached, the callback is invoked as:
#

#        uplevel #0 $callback "end"
#



#    Alternatively, if an error occurs, the callback is invoked as:
#




#        uplevel #0 $callback [list "error" reason]
#

#    Regardless, the return value of the final invocation of the callback
#    is propagated upwards by mime::body.
#

#    If the -command option is absent, then the return value of
#    mime::body is a string containing the MIME part's entire body.
#

# Arguments:
#       token      The MIME token to parse.
#       args       Optional arguments of the form:

#                  ?-decode? ?-command callback ?-blocksize octets? ?
#
# Results:
#       Returns a string containing the MIME part's entire body, or
#       if '-command' is specified, the return value of the command
#       is returned.



proc ::mime::body {token args} {
    # FRINK: nocheck

    parsepart $token

    set decode 0
    if {[set pos [lsearch -exact $args -decode]] >= 0} {
        set decode 1
        set args [lreplace $args $pos $pos]
    }

    array set options $args

    if {[info exists options(-blocksize)]} {
	set collect 1
	if {$options(-blocksize) eq {}]} {
	    set options(-blocksize) 8192
	}
	if {$options(-blocksize) < 1} {
	    error [list -blocksize $options(-blocksize) {not a positive integer}]
	}
    } else {
	set options(-blocksize) 8192
	set collect 0
    }

    set coro [coroutine [info cmdcount]_body body2 $token $decode [array get options]]
    set command [list ::apply [list coro {
	return {*}[yieldto $coro [info coroutine]]
    } [namespace current]] $coro]

    if {$collect} {
	return $command
    } else {
	set res {}
	while 1 {
	    append res [{*}$command]
	}
	return $res
    }
}


proc ::mime::body2 {token decode optdict} {
    set caller [yield [info coroutine]]

    set yield [list ::apply [list args {
	upvar 1 caller caller decode decode dread dread dwrite dwrite
	if {[llength $args] == 1 && [info exists decode] && $decode} {
	    lassign $args[set args {}] fragment
	    puts -nonewline $dwrite $fragment 
	    set arg {}
	    # not using a coroutine::util::read here because there isn't much
	    # data on the channel and if no characters are currently available,
	    # the current routine must continue to put more data into the
	    # channel.

	    # $dread must be nonblocking even though it is read in a tight loop
	    # here.
	    while {[set data [::read $dread]] ne {}} {
		append arg $data
	    }
	    if {$arg ne {}} {
		lappend args $arg 
		set caller [yieldto $caller {*}$args]
	    }
	} else {
	    set caller [yieldto $caller {*}$args]
	}
    } [namespace current]]]

    set return [list ::apply [list args {
	upvar 1 caller caller yield yield
	if {[info exists dread]} {
	    close $dread
	    close $dwrite
	}
	rename [info coroutine] {}
	uplevel 1 [list {*}$yield {*}$args] 
    } [namespace current]]]

    try {
	upvar 0 $token state

	array set options $optdict 

	set code 0
	set ecode {}
	set einfo {}

	switch $state(value) {
	    file {
		upvar 0 state(fd) fd
		set offset $state(offset)
		set count $state(count)
	    }
	    string {
		set offset 0
		set fd [tcl::chan::string $state(string)]
		seek $fd 0 end
		set count [tell $fd]
		seek $fd 0
	    }
	}

	switch $state(value) {
	    parts {
		error [list {MIME part isn't a leaf}]
	    }
	}


	if {$decode} {
	    lassign [chan pipe] dread dwrite
	    chan configure $dread -blocking 0
	    chan configure $dwrite -blocking 0 -encoding binary -buffering none
	    set params [mime::property $token params]

	    if {[dict exists $params charset]} {
		set charset [dict get $params charset]
	    } else {
		set charset US-ASCII
	    }

	    set enc [reversemapencoding $charset]
	    if {$enc ne {}} {
		chan configure $dread -encoding $enc
	    } else {
		{*}$return -code error [
		    list {-decode cannot reversemap charset} $charset]
	    }
	}



	if {$state(canonicalP)} {
	    seek $fd [set pos $offset] start
	    fconfigure $fd -translation binary
	    set code [catch {
		while {[string length [
		    set fragment [read $fd $options(-blocksize)]]] > 0} {
			{*}$yield $fragment
		    }
	    } result copts]
	} else {
	    set code [catch {
		seek $fd [set pos $offset] start
		set last [expr {$offset + $count - 1}]

		set fragment {}
		while {$pos <= $last} {
		    if {[set cc [
			expr {($last - $pos) + 1}]] > $options(-blocksize)} {
			set cc $options(-blocksize)
		    }
		    incr pos [set len [
			string length [set chunk [read $fd $cc]]]]
		    switch -exact $state(encoding) {
			base64
			    -
			quoted-printable {
			    if {([set x [string last \n $chunk]] > 0) \
				    && ($x + 1 != $len)} {
				set chunk [string range $chunk 0 $x]
				seek $fd [incr pos [expr {($x + 1) - $len}]] start
			    }
			    set chunk [
				$state(encoding) -mode decode -- $chunk]
			}
			7bit - 8bit - binary - {} {
			    # Bugfix for [#477088]
			    # Go ahead, leave chunk alone
			}
			default {
			    error "Can't handle content encoding \"$state(encoding)\""
			}
		    }
		    append fragment $chunk

		    set cc [expr {$options(-blocksize) - 1}]
		    while {[string length $fragment] > $options(-blocksize)} {
			{*}$yield [string range $fragment 0 $cc]

			set fragment [
			    string range $fragment $options(-blocksize) end]
		    }
		}
		if {[string length $fragment] > 0} {
		    {*}$yield $fragment
		}
	    } result copts]
	}

	if {$code} {
	    {*}$yield -options $copts $result
	}

	{*}$return -code break
    } on error {tres topts} {
	{*}$return -options $topts $tres
    }
}

# ::mime::bodyaux --
#
#    Builds up the body of the message, fragment by fragment.  When
#    the entire message has been retrieved, it is returned.
#
# Arguments:
#       token      The MIME token to parse.
#       reason     One of 'data', 'end', or 'error'.
#       fragment   The section of data data fragment to extract a
#                  string from.
#
# Results:
#       Returns nothing, except when called with the 'end' argument
#       in which case it returns a string that contains all of the
#       data that 'bodyaux' has been called with.  Will throw an
#       error if it is called with the reason of 'error'.

proc ::mime::bodyaux {token reason {fragment {}}} {
    # FRINK: nocheck
    upvar 0 $token state

    switch $reason {
        data {
            append state(getbody) $fragment
            return {}
        }

        end {
            if {[info exists state(getbody)]} {
                set result $state(getbody)
                unset state(getbody)
            } else {
                set result {}
            }

            return $result
        }

        error {
            catch {unset state(getbody)}
            error $reason
        }

        default {
            error "Unknown reason \"$reason\""
        }
    }
}


proc ::mime::contenttype token {
    upvar 0 $token state
    try {
	header get $token content-type
    } on error {} {
	# rfc 2045 5.2
	try {
	    header get $token MIME-Version




	    return {text/plain {charset us-ascii}}








	} on error {} {
	    return application/octet-stream
	}
    }
}









|
<
>
|
<
<
<
<
|
>
>
|
<
<
<
|
>
|
<
>
>
>
|
<
>
>
>
>
|
<
>
|
|
<
>
|
|
<
>
|
|
|
>
|
<
<
<
<
|
|
>
>
|
<
>

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
|
<
<
|
<
|
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
|
|
|
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
|
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
|
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







|


|
>
>
>
>
|
>
>
>
>
>
>
>
>







907
908
909
910
911
912
913
914

915
916




917
918
919
920



921
922
923

924
925
926
927

928
929
930
931
932

933
934
935

936
937
938

939
940
941
942
943
944




945
946
947
948
949

950
951





































































952






953


954

955






956












957





















958




959
960
961







962














































963

964











965















966



967





968




















969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
        set mbox [string range $mbox 0 [expr {$x - 1}]]
    }

    return [string trim $mbox \"]
}


proc ::mime::checkinputs {} {

    upvar 1 inputs inputs
    if {[incr inputs] > 1} {




	error [list {more than one input source provided}]
    }
}





proc ::mime::body_decoded token {
    upvar 0 $token state

    upvar 0 state(bodychandecoded) bodychandecoded
    parsepart $token
    if {[info exists state(parts)]} {
	error [list {not a leaf part} $token]

    }
    if {$state(canonicalP)} { 
	$state(fd) seek 0 
	return $state(fd)
    } else {

	if {![info exists bodychandecoded]} {
	    set bodychandecoded [::tcllib::chan::base .new [
		info cmdcount]_bodydecoded [file tempfile]]

	    $bodychandecoded configure -translation binary
	    $state(bodychan) seek 0
	    $state(bodychan) copy [$bodychandecoded $ chan]

	    $bodychandecoded seek 0
	    $state(bodychan) seek 0
	    setencoding $token $bodychandecoded
	    setcharset $token $bodychandecoded
	}
	$bodychandecoded seek 0




	return $bodychandecoded
    }
}

proc ::mime::body_raw token {

    upvar 0 $token state
    parsepart $token





































































    if {[info exists state(parts)]} {






	error [list {not a leaf part} $token]


    }

    if {$state(canonicalP)} { 






	$state(fd) seek 0












	return $state(fd)





















    } else {




	$state(bodychan) seek 0 
	return $state(bodychan)
    }







}




























































namespace eval ::mime::body {















    namespace ensemble create



    namespace export *





    namespacex import [namespace parent] body_decoded decoded body_raw raw




















}


proc ::mime::contenttype token {
    upvar 0 $token state
    try {
	header get $token content-type
    } on error {cres copts} {
	# rfc 2045 5.2
	try {
	    if {header exists $token MIME-Version} {
		    return text/plain
	    } else {
		switch $state(spec) {
		    http {
			return {text/html {charset UTF-8}}
		    }
		    mime {
			# do not specify US-ASCII here as it is the default
			return text/plain
		    }
		    
		}
	    }
	} on error {} {
	    return application/octet-stream
	}
    }
}


1442
1443
1444
1445
1446
1447
1448
1449

1450
1451
1452
1453
1454
1455
1456
1457
1458
1459



1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480



1481





1482



1483
1484
1485


1486
1487
1488
1489

1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573







1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610

1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622














1623









1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644


# ::mime::encoding --
#
#     Determines how a token is encoded.
#
# Arguments:
#       token      The MIME token to parse.

#
# Results:
#       Returns the encoding of the message (the null string, base64,
#       or quoted-printable).

proc ::mime::encoding token {
    # FRINK: nocheck
    upvar 0 $token state
    upvar 0 state(params) params




    lassign [contenttype $token] content

    switch -glob $content {
        audio/*
            -
        image/*
            -
        video/* {
            return base64
        }

        message/*
            -
        multipart/* {
            return {}
        }
        default {# Skip}
    }

    set asciiP 1
    set lineP 1



    switch $state(value) {





        file {



	    if {$state(file) eq {}} {
		# choose a workable all-purpose encoding 
		set asciiP 0


		set lineP 0
	    } else {
		set fd [open $state(file) RDONLY]
		fconfigure $fd -translation binary


		while {[gets $fd line] >= 0} {
		    if {$asciiP} {
			set asciiP [encodingasciiP $line]
		    }
		    if {$lineP} {
			set lineP [encodinglineP $line]
		    }
		    if {(!$asciiP) && (!$lineP)} {
			break
		    }
		}
		catch {close $fd}
	    }
        }

        parts {
            return {}
        }

        string {
	    set saved $state(lines.current)
	    while {$state(lines.current) < $state(lines.count)} {
		set line [lindex $state(lines) $state(lines.current)]
		incr state(lines.current)
                if {$asciiP} {
                    set asciiP [encodingasciiP $line]
                }
                if {$lineP} {
                    set lineP [encodinglineP $line]
                }
                if {(!$asciiP) && (!$lineP)} {
                    break
                }
            }
	    set state(lines.current) $saved
        }
        default {
            error [list {Unknown value} $state(value)]
        }
    }

    switch -glob $content {
        text/* {
            if {!$asciiP} {
                #TODO: this path is not covered by tests
		if {[dict exists $params charset]} {
		    set v [string tolower [dict get $params $charset]]
		    if {($v ne "us-ascii") \
			    && (![string match {iso-8859-[1-8]} $v])} {
			return base64
		    }
		}
            }

            if {!$lineP} {
                return quoted-printable
            }
        }


        default {
            if {(!$asciiP) || (!$lineP)} {
                return base64
            }
        }
    }

    return {}
}

# ::mime::encodingasciiP --
#
#     Checks if a string is a pure ascii string, or if it has a non-standard
#     form.
#
# Arguments:
#       line    The line to check.
#
# Results:
#       Returns 1 if \r only occurs at the end of lines, and if all
#       characters in the line are between the ASCII codes of 32 and 126.

proc ::mime::encodingasciiP line {







    foreach c [split $line {}] {
        switch $c {
            { } - \t - \r - \n {
            }

            default {
                binary scan $c c c
                if {($c < 32) || ($c > 126)} {
                    return 0
                }
            }
        }
    }
    if {
	[set r [string first \r $line]] < 0
	||
	$r == {[string length $line] - 1}
    } {
        return 1
    }

    return 0
}

# ::mime::encodinglineP --
#
#     Checks if a string is a line is valid to be processed.
#
# Arguments:
#       line    The line to check.
#
# Results:
#       Returns 1 the line is less than 76 characters long, the line
#       contains more characters than just whitespace, the line does
#       not start with a '.', and the line does not start with 'From '.

proc ::mime::encodinglineP line {

    if {([string length $line] > 76) \
            || ($line ne [string trimright $line]) \
            || ([string first . $line] == 0) \
            || ([string first {From } $line] == 0)} {
        return 0
    }

    return 1
}


proc ::mime::contentid {} {














    set unique [uniqueID]









    return $unique@|
}


proc ::mime::dropchan token {
    variable channels
    upvar 0 $token state
    upvar 0 state(fd) fd

    if {[info exists fd]} {
	if {[incr channels($fd) -1] == 0} {
	    unset channels($fd)
	    if {$state(closechan)} {
		close $fd
	    }
	}
	unset state(fd)
    }
}









|
>








|

>
>
>








|





|






>
>
>
|
>
>
>
>
>
|
>
>
>
|
<
|
>
>
|
|
|
<
>
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








|

|





|






|



<
|














|
>
>
>
>
>
>
>
|
|
|
|

|
|
|
|
|
|
|
|
<
<
<
<
<
<

<
|














|
>
|
|
|
|
|
|
|




|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
|












|







1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281

1282
1283
1284
1285
1286
1287

1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300

1301
1302
1303



1304




















1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331

1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367






1368

1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442


# ::mime::encoding --
#
#     Determines how a token is encoded.
#
# Arguments:
#       token
#            The MIME token to parse.
#
# Results:
#       Returns the encoding of the message (the null string, base64,
#       or quoted-printable).

proc ::mime::encoding token {
    # FRINK: nocheck
    upvar 0 $token state
    upvar 0 state(fd) chan state(params) params

    if {[info exists state(encoding)]} {
	return $state(encoding)
    }
    lassign [contenttype $token] content

    switch -glob $content {
        audio/*
            -
        image/*
            -
        video/* {
            return [set state(encoding) base64]
        }

        message/*
            -
        multipart/* {
            return [set state(encoding) {}]
        }
        default {# Skip}
    }

    set asciiP 1
    set lineP 1
    if {[info exists state(parts)]} {
	return [set state(encoding) {}]
    }

    if {[set current [$chan tell]] < 0} {
	makeseekable $token
	set current [$chan tell]
    }
    set chanconfig [$chan configure]
    try {
	set buf {}
	set dataend 0
	while {[set data [$chan read 8192]] ne {} || $buf ne {}} {
	    if {$data eq {}} {

		set dataend 1
	    }
	    set data $buf[set buf {}]$data[set data{}]
	    set lines [split $data \n]
	    if {!$dataend} {
		set buf [lindex $lines end]

		set lines [lrange $lines[set lines {}] 0 end-1]
	    }
	    if {[llength $lines]} {
		if {$asciiP} {
		    set asciiP [encodingasciiP $lines]
		}
		if {$lineP} {
		    set lineP [encodinglineP $lines]
		}
		if {(!$asciiP) && (!$lineP)} {
		    break
		}
	    }

	}
    } finally {
	$chan configure {*}$chanconfig



	$chan seek 0




















    }

    switch -glob $content {
        text/* {
            if {!$asciiP} {
                #TODO: this path is not covered by tests
		if {[dict exists $params charset]} {
		    set v [string tolower [dict get $params $charset]]
		    if {($v ne {us-ascii}) \
			    && (![string match {iso-8859-[1-8]} $v])} {
			return [set state(encoding) base64]
		    }
		}
            }

            if {!$lineP} {
                return [set state(encoding) quoted-printable]
            }
        }


        default {
            if {(!$asciiP) || (!$lineP)} {
                return [set state(encoding) base64]
            }
        }
    }

    return [set state(encoding) {}]
}

# ::mime::encodingasciiP --
#
#     Checks if a string is a pure ascii string, or if it has a non-standard
#     form.
#
# Arguments:
#       line    The line to check.
#
# Results:
#       Returns 1 if \r only occurs at the end of lines, and if all
#       characters in the line are between the ASCII codes of 32 and 126.

proc ::mime::encodingasciiP lines {
    foreach line $lines {
	set firstr [string first \r $line]]
	if {
	    $firstr > 0 && $first != [string length $line]
	} {
	    return 0
	}
	foreach c [split $line {}] {
	    switch $c {
		{ } - \t - \r - \n {
		}

		default {
		    binary scan $c c c
		    if {($c < 32) || ($c > 126)} {
			return 0
		    }
		}
	    }
	}






    }

    return 1
}

# ::mime::encodinglineP --
#
#     Checks if a string is a line is valid to be processed.
#
# Arguments:
#       line    The line to check.
#
# Results:
#       Returns 1 the line is less than 76 characters long, the line
#       contains more characters than just whitespace, the line does
#       not start with a '.', and the line does not start with 'From '.

proc ::mime::encodinglineP lines {
    foreach line $line {
	if {([string length $line] > 76) \
		|| ($line ne [string trimright $line]) \
		|| ([string first . $line] == 0) \
		|| ([string first {From } $line] == 0)} {
	    return 0
	}
    }
    return 1
}


proc ::mime::contentid token {
    upvar 0 $token state
    upvar 0 state(parts) parts
    parsepart $token
    if {[info exists parts]} {
	foreach part $parts {
	    # use message-id here, not content-id, to account for header info
	    # in the parts
	    append ids [header get $part message-id] 
	}
	set id [::sha2::sha256 -hex $ids]
    } else {
	set chan [body decoded $token]
	set config [$chan configure]
	if {[dict exists $config -chan]} {
	    dict unset config -chan
	}
	try {
	    $chan seek 0
	    set id [::sha2::sha256 -hex -channel [$chan configure -chan]]
	    $chan seek 0
	} finally {
	    $chan configure {*}$config
	}
    }
    return $id@|
}


proc ::mime::dropchan token {
    variable channels
    upvar 0 $token state
    upvar 0 state(fd) fd

    if {[info exists fd]} {
	if {[incr channels($fd) -1] == 0} {
	    unset channels($fd)
	    if {$state(closechan)} {
		$fd close
	    }
	}
	unset state(fd)
    }
}


1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
    upvar 0 $token state
    array set options [list -subordinates dynamic]
    array set options $args

    switch $options(-subordinates) {
        all {
            #TODO: this code path is untested
            if {$state(value) eq "parts"} {
                foreach part $state(parts) {
                    eval [linsert $args 0 mime::finalize $part]
                }
            }
        }

        dynamic {







|







1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
    upvar 0 $token state
    array set options [list -subordinates dynamic]
    array set options $args

    switch $options(-subordinates) {
        all {
            #TODO: this code path is untested
            if {[info exists state(parts)]} {
                foreach part $state(parts) {
                    eval [linsert $args 0 mime::finalize $part]
                }
            }
        }

        dynamic {
1685
1686
1687
1688
1689
1690
1691
1692










1693
1694
1695
1696
1697
1698
1699


























































1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730

1731



1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784

        default {
            error "unknown value for -subordinates $options(-subordinates)"
        }
    }

    dropchan $token











    foreach name [array names state] {
        unset state($name)
    }
    # FRINK: nocheck
    unset $token
}




























































# ::mime::getsize --
#
#    Determine the size (in bytes) of a MIME part/token
#
# Arguments:
#       token      The MIME token to parse.
#
# Results:
#       Returns the size in bytes of the MIME token.

proc ::mime::getsize {token} {
    # FRINK: nocheck
    upvar 0 $token state

    switch $state(value)/$state(canonicalP) {
        file/0 {
            set size $state(count)
        }

        file/1 {
            return [file size $state(file)]
        }

        parts/0
            -
        parts/1 {
            set size 0
            foreach part $state(parts) {
                incr size [getsize $part]
            }

            return $size



        }

        string/0 {
            set size [string length $state(string)]
        }

        string/1 {
            return [string length $state(string)]
        }
        default {
            error [list {Unknown combination} $state(value) $state(canonicalP)]
        }
    }

    if {$state(encoding) eq {base64}} {
        set size [expr {($size * 3 + 2) / 4}]
    }

    return $size
}


proc ::mime::getTransferEncoding token {
    upvar 0 $token state
    set res {}
    if {[set encoding $state(encoding)] eq {}} {
	set encoding [encoding $token]
    }
    if {$encoding ne {}} {
	set res $encoding
    }
    switch $encoding {
	base64
	    -
	quoted-printable {
	    set converter $encoding
	}
	7bit - 8bit - binary - {} {
	    # Bugfix for [#477088], also [#539952]
	    # Go ahead
	}
	default {
	    error "Can't handle content encoding \"$encoding\""
	}
    }
    return $res
}


namespace eval ::mime::header {
    namespace ensemble create -map {
	get get
	exists exists








>
>
>
>
>
>
>
>
>
>







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>











|


|
<
<
<
|
|
<
<
|
|
<
<
<
|
|
|
|
>
|
>
>
>
|
|
|
|
<
|
<
<
|
<
|
|

|
|
|
<
|






<
<
|
<
<
|
<

<
<
<
<
<
|
<
<


|


|







1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580



1581
1582


1583
1584



1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597

1598


1599

1600
1601
1602
1603
1604
1605

1606
1607
1608
1609
1610
1611
1612


1613


1614

1615





1616


1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629

        default {
            error "unknown value for -subordinates $options(-subordinates)"
        }
    }

    dropchan $token

    if {$state(bodychan) ne {}} {
	if {[$state(bodychan) configure -chan] in [chan names]} {
	    rename $state(bodychan) {}
	}
    }

    if {[info exists state(bodychandecoded)]} {
	rename $state(bodychandecoded) {}
    }

    foreach name [array names state] {
        unset state($name)
    }
    # FRINK: nocheck
    unset $token
}


proc ::mime::messageid token {
    upvar 0 $token state
    #set unique [uniqueID]
    if {![header exists $token content-id] && $state(addcontentid)} {
	header::setinternal $token Content-ID [contentid $token]
    }
    set sha [::sha2::SHA256Init]
    foreach {key val} [lsort -stride 2 [header::get $token]] {
	lassign $val value params
	::sha2::SHA256Update $sha $key$value
	foreach {pkey pval} $params {
	    ::sha2::SHA256Update $sha $pkey$pval
	}
    }
    set hash [::sha2::SHA256Final $sha]
    binary scan $hash H* hex
    return $hex@|
}

# ::mime::mimegets --
#
#    like [gets] but does not run over multipart boundaries
#
#    only needed during the parsing stage, since after that the content of each
#    part is in a separate file
#
# Arguments:
#       token      The MIME token to parse.
#
# Results:
#       Returns the size in bytes of the MIME token.
proc ::mime::mimegets {token varname} {
    upvar 0 $token state
    upvar 0 state(boundary) boundary state(eof) eof
    upvar 1 $varname line
    if {$eof} {
	set line {}
	return -1
    }
    set res [$state(fd) gets line]
    if {$res == -1} {
	set eof 1
	set line {}
	return -1
    } else {
	set found [string first --$boundary $line]
	if {$found == 0} {
	    if {[string first --$boundary-- $line] >= 0} {
		set state(sawclosing) 1
		set eof 1
	    }
	    set line {}
	    return -1 
	}
	return $res
    }
}

# ::mime::getsize --
#
#    Determine the size (in bytes) of a MIME part/token
#
# Arguments:
#       token      The MIME token to parse.
#
# Results:
#       Returns the size in bytes of the MIME token.

proc ::mime::getsize token {
    # FRINK: nocheck
    upvar 0 $token state
    upvar 0 state(bodychan) bodychan state(fd) inputchan 




    parsepart $token



    if {[info exists state(parts)]} {



	set size 0
	foreach part $state(parts) {
	    incr size [getsize $part]
	}
    } else {
	set size 0
	if {$state(canonicalP)} {
	    if {[set current [$inputchan tell]] < 0} {
		makeseekable $token
	    }
	    set current [$inputchan tell]
	    $inputchan seek 0 end
	    set size [$inputchan tell]

	    $inputchan seek $current


	} else {

	    set size $state(size)
	}
    }
    # no longer needed since size is calculated during parsing
    #if {$state(encoding) eq {base64}} {
    #    set size [expr {($size * 3 + 2) / 4}]

    #}
    return $size
}


proc ::mime::getTransferEncoding token {
    upvar 0 $token state


    set encoding [encoding $token]


    # See also issues [#477088] and [#539952]

    switch $encoding {





	base64 - quoted-printable  - 7bit - 8bit - binary - {} {


	}
	default {
	    error [list {Can't handle content encoding} $encoding]
	}
    }
    return $encoding
}


namespace eval ::mime::header {
    namespace ensemble create -map {
	get get
	exists exists
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903



1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922


1923
1924
1925
1926


1927
1928
1929



1930
1931
1932

1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944






1945



1946










1947
1948
1949
1950
1951
1952
1953


# ::mime::dunset --
#
#   Unset all values for $key, without "normalizing" other redundant keys
proc ::mime::header::dunset {dictname key} {
    upvar 1 $dictname dict
    join [lmap {key1 val} $dict[set dict {}] {
	if {$key1 eq $key} continue
	list $key $val
    }]
}



proc ::mime::header::serialize {token name value params} {
    variable notattchar_re
    set lname [string tolower $name]

    # to do: check key for conformance
    # to do: properly quote/process $value for interpolation
    if {[regexp {[^\x21-\x39\x3b-\x7e]} $name]} {
	error [
	    list {non-printing character or colon character in header name} $name]
    }
    if {[regexp {[^\t\x20-\x7e]} $value]} {
	error [
	    list {non-printing character in header value}]
    }

    switch $lname {
	content-id - message-id {
	    set value <$value>
	}
    }

    set res "$name: $value"

    dict for {key value} $params {
	if {[regexp $notattchar_re $key]} {
	    error [list {illegal character found in attribute name}]
	}
	set len [expr {[string length $key]} + 1 + [string length $value]]
	# save one byte for the folding white space continuation space
	# and two bytes for "; "
	if {$len > 73 || ![regexp {[^-!#$%&'*+,.\w`~^@{}|]+$} $value]} {
	    # save two bytes for the quotes
	    if {$len <= 71 && ![regexp {[^\x20-\x7e]} $value]} {
		set value "[string map [list \\ \\\\ \" \\\"] $value[set value {}]]"
		append res "\n\t; $key=$value"
	    } else {
		set value [::encoding convertto utf-8 $value]

		regsub -all -- $notattchar_re $value {[format %%%02X [scan "\\&" %c]]} value
		set value [subst -novariables $value]

		set partnum 0
		set start 0
		set param $key*$partnum*=utf-8''
		while {$start < [string length $value]} {
		    # subtract one from the limit to ensure that at least one byte
		    # is included in the part value
		    if {[string length $param] > 72} {
			error [list {parameter name is too long}]
		    }
		    set end [expr {$start + 72 - [string length $param]}]
		    set part [string range $value $start $end]
		    incr start [string length $part]
		    append res "\n\t; $param$part"
		    set param $key*$partnum=
		    incr partnum
		}
	    }
	} else {
	    append res "\n\t; $key=$value"
	}
    }
    return $res
}


proc ::mime::header::exists {token name} {
    upvar 0 $token state
    set lname [string tolower $name]
    expr {[dict exists $state(headerlower) $lname]
	|| [dict exists $state(headerinternallower) $lname]}



}


# ::mime::header get --
#
#    Returns the header of a message as a multidict where each value is a list
#    containing the header value and a dictionary parameters for that header.

#    If $key is provided, returns only the value and paramemters of the last
#    maching header, without regard for case. 
#
#    If -names is specified, a list of all header names is returned.
#

proc ::mime::header::get {token {key {}}} {
    # FRINK: nocheck
    upvar 0 $token state
    parse $token



    set header $state(header)
    set headerlower $state(headerlower)
    set headerinternal $state(headerinternal)
    set headerinternallower $state(headerinternallower)


    switch $key {
	{} {
	    set result [dict merge $headerinternal $header]



	    set tencoding [getTransferEncoding $token]
	    if {$tencoding ne {}} {
		lappend result Content-Transfer-Encoding [list $tencoding {}]

	    }
	    return $result
	}

	-names {
	    return [dict keys $header]
	}

	default {
	    set lower [string tolower $key]

	    switch $lower {






		content-transfer-encoding {



		    return [list [getTransferEncoding $token] {}]










		}
		mime-version {
		    return [list $state(version) {}]
		}
		default {
		    set res {}
		    if {[dict exists $headerinternallower $lower]} {







|

|
|



<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




|
>
>
>



















>
>




>
>


|
>
>
>
|
|
|
>












>
>
>
>
>
>

>
>
>
|
>
>
>
>
>
>
>
>
>
>







1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676



































































1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761


# ::mime::dunset --
#
#   Unset all values for $key, without "normalizing" other redundant keys
proc ::mime::header::dunset {dictname key} {
    upvar 1 $dictname dict
    set dict [join [lmap {key1 val} $dict[set dict {}] {
	if {$key1 eq $key} continue
	list $key1 $val
    }]]
}





































































proc ::mime::header::exists {token name} {
    upvar 0 $token state
    set lname [string tolower $name]
    expr {[dict exists $state(headerlower) $lname]
		|| [dict exists $state(headerinternallower) $lname]
		|| [dict exists $state(contentidlower) $lname]
		|| [dict exists $state(messageidlower) $lname]
    }
}


# ::mime::header get --
#
#    Returns the header of a message as a multidict where each value is a list
#    containing the header value and a dictionary parameters for that header.

#    If $key is provided, returns only the value and paramemters of the last
#    maching header, without regard for case. 
#
#    If -names is specified, a list of all header names is returned.
#

proc ::mime::header::get {token {key {}}} {
    # FRINK: nocheck
    upvar 0 $token state
    parse $token

    set contentid $state(contentid)
    set contentidlower $state(contentidlower)
    set header $state(header)
    set headerlower $state(headerlower)
    set headerinternal $state(headerinternal)
    set headerinternallower $state(headerinternallower)
    set messageid $state(messageid) 
    set messageidlower $state(messageidlower)
    switch $key {
	{} {
	    set result [list {*}$messageid {*}$contentid {*}$headerinternal \
		{*}$header]
	    if {![dict exists $headerlower content-transfer-encoding]
		&& !$state(canonicalP)} {
		set tencoding [getTransferEncoding $token]
		if {$tencoding ne {}} {
		    lappend result Content-Transfer-Encoding [list $tencoding {}]
		}
	    }
	    return $result
	}

	-names {
	    return [dict keys $header]
	}

	default {
	    set lower [string tolower $key]

	    switch $lower {
		content-id {
		    if {![dict size $contentidlower]} {
			contentid $token
		    }
		    return [dict get $contentidlower content-id]
		}
		content-transfer-encoding {
		    if {[dict exists $headerinternallower $lower]} {
			return [dict get $headerinternallower $lower]
		    } elseif {!$state(canonicalP)} {
			return [list [getTransferEncoding $token] {}]
		    } else {
			error [list {no such header} $key]
		    }
		}
		message-id {
		    if {![dict size $messageidlower]} {
			setinternal $token Message-ID [
			    [namespace parent]::messageid $token]
		    }
		    return [dict get $messageidlower message-id]
		}
		mime-version {
		    return [list $state(version) {}]
		}
		default {
		    set res {}
		    if {[dict exists $headerinternallower $lower]} {
1963
1964
1965
1966
1967
1968
1969

1970
1971
1972
1973
1974
1975
1976
1977
1978

1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003

2004
2005
2006
2007
2008
2009
2010
    }
}


proc ::mime::header::parse token {
    # FRINK: nocheck
    upvar 0 $token state

    if {$state(canonicalP) || $state(headerparsed)} {
	return
    }
    set state(headerparsed) 1
    upvar 0 state(last) last

    if {[set fileP [info exists state(file)]]} {
        seek $state(fd) [set pos $state(offset)] start
        set last [expr {$state(offset) + $state(count) - 1}]

    } else {
        set string $state(string)
    }

    set vline {}
    while 1 {
	set blankP 0
	if {$fileP} {
	    if {($pos > $last) || ([set x [gets $state(fd) line]] <= 0)} {
		set blankP 1
	    } else {
		incr pos [expr {$x + 1}]
	    }
	} else {
	    if {$state(lines.current) >= $state(lines.count)} {
		set blankP 1
		set line {}
	    } else {
		set line [lindex $state(lines) $state(lines.current)]
		incr state(lines.current)
		set x [string length $line]
		if {$x == 0} {set blankP 1}
	    }
	}


	if {!$blankP && [string match *\r $line]} {
	    set line [string range $line 0 $x-2]
	    if {$x == 1} {
		set blankP 1
	    }
	}








>




<

|
<
<
>

|





<
<
|
<
|
<
<
<
|
<
<
<
<
<
<
|
|
|
>







1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782

1783
1784


1785
1786
1787
1788
1789
1790
1791
1792


1793

1794



1795






1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
    }
}


proc ::mime::header::parse token {
    # FRINK: nocheck
    upvar 0 $token state
    upvar 0 state(fd) fd state(boundary) boundary
    if {$state(canonicalP) || $state(headerparsed)} {
	return
    }
    set state(headerparsed) 1


    if {[info exists boundary]} {


	set gets [list [namespace parent]::mimegets $token line]
    } else {
	set gets [list $fd gets line]
    }

    set vline {}
    while 1 {
	set blankP 0


	set x [{*}$gets]

	if {$x <= 0} {



	    set blankP 1






	}

	# to do 2018-11-13: probably remove this now that line translation
	# happens automatically,
	if {!$blankP && [string match *\r $line]} {
	    set line [string range $line 0 $x-2]
	    if {$x == 1} {
		set blankP 1
	    }
	}

2033
2034
2035
2036
2037
2038
2039





2040
2041
2042
2043
2044
2045
2046
        }
        set value [string trim [string range $vline [expr {$x + 1}] end]]

        switch [set lower [string tolower $mixed]] {
	    content-disposition {
		set_ $token $mixed {*}[parseparts $token $value]
	    }





            content-type {
                if {[exists $token content-type]} {
                    error [list {multiple Content-Type fields starting with} \
			$vline]
                }

                set x [parsetype $token $value]







>
>
>
>
>







1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
        }
        set value [string trim [string range $vline [expr {$x + 1}] end]]

        switch [set lower [string tolower $mixed]] {
	    content-disposition {
		set_ $token $mixed {*}[parseparts $token $value]
	    }

	    content-id {
		setinternal $token $mixed $value
	    }

            content-type {
                if {[exists $token content-type]} {
                    error [list {multiple Content-Type fields starting with} \
			$vline]
                }

                set x [parsetype $token $value]
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
            }

            mime-version {
                set state(version) $value
            }

            default {
		setinternal $token $mixed $value -mode append
            }
        }

        if {$blankP} {
            break
        }
        set vline $line







|







1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
            }

            mime-version {
                set state(version) $value
            }

            default {
		set_ $token $mixed $value -mode append
            }
        }

        if {$blankP} {
            break
        }
        set vline $line
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319


































































2320
2321
2322
2323
2324
2325
2326

    set params {}
    dict for {key pinfo} $info[set info {}] {
	dict update pinfo encoding encoding value value {}
	if {[info exists encoding]} {
	    set value [string map {% {\x}} $value[set value {}]]
	    set value [subst -novariables -nocommands $value[set value {}]]
	    set value [encoding convertfrom $encoding $value]
	}
	dict set params $key $value
    }
    return $params
}




































































# ::mime::header::set --
#
#    mime::header::set writes, appends to, or deletes the value associated
#    with a key in the header.
#
#    The value for -mode is one of:







|






>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193

    set params {}
    dict for {key pinfo} $info[set info {}] {
	dict update pinfo encoding encoding value value {}
	if {[info exists encoding]} {
	    set value [string map {% {\x}} $value[set value {}]]
	    set value [subst -novariables -nocommands $value[set value {}]]
	    set value [::encoding convertfrom $encoding $value]
	}
	dict set params $key $value
    }
    return $params
}


proc ::mime::header::serialize {token name value params} {
    variable notattchar_re
    set lname [string tolower $name]

    # to do: check key for conformance
    # to do: properly quote/process $value for interpolation
    if {[regexp {[^\x21-\x39\x3b-\x7e]} $name]} {
	error [
	    list {non-printing character or colon character in header name} $name]
    }
    if {[regexp {[^\t\x20-\x7e]} $value]} {
	error [
	    list {non-printing character in header value}]
    }

    switch $lname {
	content-id - message-id {
	    set value <$value>
	}
    }

    set res "$name: $value"

    dict for {key value} $params {
	if {[regexp $notattchar_re $key]} {
	    error [list {illegal character found in attribute name}]
	}
	set len [expr {[string length $key]} + 1 + [string length $value]]
	# save one byte for the folding white space continuation space
	# and two bytes for "; "
	if {$len > 73 || ![regexp {[^-!#$%&'*+,.\w`~^@{}|]+$} $value]} {
	    # save two bytes for the quotes
	    if {$len <= 71 && ![regexp {[^\x20-\x7e]} $value]} {
		set value "[string map [list \\ \\\\ \" \\\"] $value[set value {}]]"
		append res "\n\t; $key=$value"
	    } else {
		set value [::encoding convertto utf-8 $value]

		regsub -all -- $notattchar_re $value {[format %%%02X [scan "\\&" %c]]} value
		set value [subst -novariables $value]

		set partnum 0
		set start 0
		set param $key*$partnum*=utf-8''
		while {$start < [string length $value]} {
		    # subtract one from the limit to ensure that at least one byte
		    # is included in the part value
		    if {[string length $param] > 72} {
			error [list {parameter name is too long}]
		    }
		    set end [expr {$start + 72 - [string length $param]}]
		    set part [string range $value $start $end]
		    incr start [string length $part]
		    append res "\n\t; $param$part"
		    set param $key*$partnum=
		    incr partnum
		}
	    }
	} else {
	    append res "\n\t; $key=$value"
	}
    }
    return $res
}


# ::mime::header::set --
#
#    mime::header::set writes, appends to, or deletes the value associated
#    with a key in the header.
#
#    The value for -mode is one of:
2347
2348
2349
2350
2351
2352
2353









2354
2355
2356
2357
2358
2359
2360
# Results:
#       Returns previous value associated with the specified key.

proc ::mime::header::set_ {token key value args} {
    variable internal
    # FRINK: nocheck
    upvar 0 $token state









    parse $token

    set params {}
    switch [llength $args] {
	1 - 3 {
	    set args [lassign $args[set args {}] params]
	}







>
>
>
>
>
>
>
>
>







2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
# Results:
#       Returns previous value associated with the specified key.

proc ::mime::header::set_ {token key value args} {
    variable internal
    # FRINK: nocheck
    upvar 0 $token state
    upvar 0 \
	state(contentid) contentid \
	state(contentidlower) contentidlower \
	state(header) header \
	state(headerinternal) headerinternal \
	state(headerinternallower) headerinternallower \
	state(headerlower) headerlower \
	state(messageid) messageid \
	state(messageidlower) messageidlower
    parse $token

    set params {}
    switch [llength $args] {
	1 - 3 {
	    set args [lassign $args[set args {}] params]
	}
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405

2406
2407
2408

2409
2410
2411
2412
2413
2414
2415
	    default {
		error [list {unknon option} $opt]
	    }
	}
    }

    set lower [string tolower $key]
    set headerlower $state(headerlower)
    set header $state(header)
    set headerinternallower $state(headerinternallower)
    set headerinternal $state(headerinternal)
    if {[catch {header get $lower} result]} {
        #TODO: this code path is not tested
        if {$options(-mode) eq {delete}} {
            error [list {key not in header} $key]
        }
	set result {}
    }
    switch $options(-mode) {
	append - write {
	    switch $lower {
		content-md5
		    -
		content-transfer-encoding
		    -
		mime-version
		    -
		content-type {
		    if {!$internal} {
			switch $lower {
			    default {

				lassign [get $token $lower] values params1
				if {$value ni $values} {
				    error "key $key may not be set"

				}
			    }
			}
		    }
		    switch $lower {
			content-type {
			    if {[string match multipart/* $value]







<
<
<
<
<
<
<
<
<
|
<













>
|
|
|
>







2251
2252
2253
2254
2255
2256
2257









2258

2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
	    default {
		error [list {unknon option} $opt]
	    }
	}
    }

    set lower [string tolower $key]









    set result {}

    switch $options(-mode) {
	append - write {
	    switch $lower {
		content-md5
		    -
		content-transfer-encoding
		    -
		mime-version
		    -
		content-type {
		    if {!$internal} {
			switch $lower {
			    default {
				if {[exists $token $lower]} {
				    lassign [get $token $lower] values params1
				    if {$value ni $values} {
					error "key $key may not be set"
				    }
				}
			    }
			}
		    }
		    switch $lower {
			content-type {
			    if {[string match multipart/* $value]
2439
2440
2441
2442
2443
2444
2445










2446
2447


2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
		if {[dict exists $headerinternallower $lower]} {
		    dunset headerinternallower $lower
		}

	    }
	    set newval [list $value $params]
	    if {$internal} {










		lappend headerinternal $key $newval 
		lappend headerinternallower $lower $newval 


	    } else {
		lappend header $key $newval 
		lappend headerlower $lower $newval 
	    }
	}
        delete {
            unset headerlower($lower)
	    unset headerinternallower($lower)
	    unset header($key)
	    unset headerinternal($key)
        }

        default {
            error "unknown value for -mode $options(-mode)"
        }
    }

    set state(header) $header 
    set state(headerlower) $headerlower 
    set state(headerinternal) $headerinternal 
    set state(headerinternallower) $headerinternallower

    return $result
}


proc ::mime::header::setinternal args {
    variable internal 1
    try {







>
>
>
>
>
>
>
>
>
>
|
|
>
>






|
|
|
|







<
<
<
<
<







2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344





2345
2346
2347
2348
2349
2350
2351
		if {[dict exists $headerinternallower $lower]} {
		    dunset headerinternallower $lower
		}

	    }
	    set newval [list $value $params]
	    if {$internal} {
		switch $lower {
		    content-id {
			lappend contentid $key $newval 
			lappend contentidlower $lower $newval 
		    }
		    message-id {
			lappend messageid $key $newval 
			lappend messageidlower $lower $newval 
		    }
		    default {
			lappend headerinternal $key $newval 
			lappend headerinternallower $lower $newval 
		    }
		}
	    } else {
		lappend header $key $newval 
		lappend headerlower $lower $newval 
	    }
	}
        delete {
            dunset headerlower $lower
	    dunset headerinternallower $lower
	    dunset header $key
	    dunset headerinternal $key
        }

        default {
            error "unknown value for -mode $options(-mode)"
        }
    }






    return $result
}


proc ::mime::header::setinternal args {
    variable internal 1
    try {
2494
2495
2496
2497
2498
2499
2500

2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551

2552

2553
2554
2555
2556
2557
2558
2559
2560



2561
2562







2563
2564
2565
2566
2567
2568





2569
2570
2571

2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586



2587
2588
2589



2590
2591
2592
2593
2594
2595
2596

2597
2598
2599
2600
2601
2602
































2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652

2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669



2670


2671
2672




2673
2674
2675

2676
2677

2678

2679

2680
2681




2682

2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
proc ::mime::initialize args {
    variable mime

    set token [namespace current]::[incr mime(uid)]
    # FRINK: nocheck
    upvar 0 $token state


    if {[catch [list mime::initializeaux $token {*}$args] result eopts]} {
        catch {mime::finalize $token -subordinates dynamic}
        return -options $eopts $result
    }
    return $token
}

# ::mime::initializeaux --
#
#    Creates a MIME part and returns the MIME token for that part.
#
# Arguments:
#    args   Args can be any one of the following:
#                  ?-canonical type/subtype
#                  ?-params    {?key value? ...}
#                  ?-encoding value?
#                  ?-headers   {?key value? ...}
#                  ?-http
#                  (-file name | -string value | -parts {token1 ... tokenN})
#
#       If the -canonical option is present, then the body is in
#       canonical (raw) form and is found by consulting either the -file,
#       -string, or -parts option.
#
#       -header
#           a dictionary of headers
#               with possibliy-redundant keys
#       -http
#           operate in http mode
#
#       -params
#           a dictionary of parameters
#           with possibly-redundant keys
#
#
#       Also, -encoding, if present, specifies the
#       "Content-Transfer-Encoding" when copying the body.
#
#       If the -canonical option is not present, then the MIME part
#       contained in either the -file or the -string option is parsed,
#       dynamically generating subordinates as appropriate.
#
# Results:
#    An initialized mime token.


proc ::mime::initializeaux {token args} {
    variable channels
    # FRINK: nocheck
    upvar 0 $token state
    upvar 0 state(canonicalP) canonicalP

    upvar 0 state(params) params


    set params {}

    set state(addcontentid) 1
    set state(addmimeversion) 1
    set state(encoding) {}
    set state(version) 1.0




    set state(bodyparsed) 0
    set canonicalP 0







    set state(header) {}
    set state(headerinternal) {}
    set state(headerinternallower) {}
    set state(headerlower) {}
    set state(headerparsed) 0






    set state(cid) 0
    set state(closechan) 1
    set state(root) $token


    set userparams 0

    set argc [llength $args]
    for {set argx 0} {$argx < $argc} {incr argx} {
        set option [lindex $args $argx]
        if {[incr argx] >= $argc} {
            error "missing argument to $option"
        }
        set value [lindex $args $argx]

        switch $option {
	    -addcontentid {
		set state(addcontentid) [expr {!!$value}]
	    }



	    -addmimeversion {
		set state(addmimeversion) [expr {!!$value}]
	    }



            -canonical {
		set canonicalP 1
		set type [string tolower $value]
            }

	    -chan {
		set state(file) {}

		addchan $token $value
	    }

	    -close {
		set state(closechan) [expr {!!$value}]
	    }

































            -params {
		if {$userparams} {
		    error [list {-params can only be provided once}]
		}
		set userparams 1
                if {[llength $value] % 2} {
		    error [list -params expects a dictionary]
                }
		foreach {mixed pvalue} $value {
		    set lower [string tolower $mixed]
		    if {[dict exists params $lower]} {
			error "the $mixed parameter may be specified at most once"
		    }

		    dict set params $lower $pvalue
		}
            }

            -encoding {
		set value [string tolower $value[set value {}]]

                switch $value {
                    7bit - 8bit - binary - quoted-printable - base64 {
                    }

                    default {
                        error "unknown value for -encoding $state(encoding)"
                    }
                }
                set state(encoding) [string tolower $value]
            }

            -headers {
		# process headers later in order to assure that content-id and
		# content-type occur first
		if {[info exists headers]} {
		    error [list {-headers option occurred more than once}]
		}
                if {[llength $value] % 2} {
                    error [list -headers expects a dictionary]
                }
		set headers $value
            }

            -file {
                set state(file) $value
            }

            -parts {

		set canonicalP 1
                set state(parts) $value
            }

            -string {
                set state(string) $value

                set state(lines) [split $value \n]
                set state(lines.count) [llength $state(lines)]
                set state(lines.current) 0
            }

            -root {
                # the following are internal options
                set state(root) $value
            }




            -offset {


                set state(offset) $value
            }





            -count {
                set state(count) $value

            }


            -lineslist {

                set state(lines) $value

                set state(lines.count) [llength $state(lines)]
                set state(lines.current) 0




                #state(string) is needed, but will be built when required

                set state(string) {}
            }

            default {
                error [list {unknown option} $option]
            }
        }
    }

    #We only want one of -chan -file, -parts or -string:
    set valueN 0
    foreach value {file parts string} {
        if {[info exists state($value)]} {
	    set state(value) $value
            incr valueN
        }
    }
    if {$valueN != 1 && ![info exists state(lines)]} {
        error [list {specify exactly one of} {-file -parts -string}]
    }


    if {$state(value) eq {file}} {
	if {$state(root) eq $token} {
	    if {![info exists state(fd)]} {
		addchan $token [open $state(file) RDONLY]
	    }
	    set state(offset) 0
	    seek $state(fd) 0 end
	    set state(count) [tell $state(fd)]

	    fconfigure $state(fd) -translation binary
	} else {
	    # FRINK: nocheck
	    upvar 0 $state(root) root
	    addchan $token $root(fd)
	}
    }


    if {$canonicalP} {
        if {![header exists $token content-id] && $state(addcontentid)} {
	    header::setinternal $token Content-ID [contentid]
        }

	if {![info exists type]} {
	    set type multipart/mixed
	}

	header setinternal $token Content-Type $type $params

	if {[info exists headers]} {







>
|
















|
|


|
|




<
<










|










|
>
|
>




|
|
<

>
>
>


>
>
>
>
>
>
>





|
>
>
>
>
>
|
|
|
>















>
>
>



>
>
>




<

<
>
|





>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



















<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

>




<
<
|
|
<
<
|






>
>
>
|
>
>
|
|
>
>
>
>
|
|
<
>
|
|
>
|
>
|
>
|
|
>
>
>
>
|
>
|
|







<
<
<
|
<
<
<
<
<
|


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

<
<
<
<







2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403


2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434

2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490

2491

2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549






























2550
2551
2552
2553
2554
2555


2556
2557


2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578

2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603



2604





2605
2606
2607



















2608




2609
2610
2611
2612
2613
2614
2615
proc ::mime::initialize args {
    variable mime

    set token [namespace current]::[incr mime(uid)]
    # FRINK: nocheck
    upvar 0 $token state

    if {[catch {uplevel 1 [
	list mime::initializeaux $token {*}$args]} result eopts]} {
        catch {mime::finalize $token -subordinates dynamic}
        return -options $eopts $result
    }
    return $token
}

# ::mime::initializeaux --
#
#    Creates a MIME part and returns the MIME token for that part.
#
# Arguments:
#    args   Args can be any one of the following:
#                  ?-canonical type/subtype
#                  ?-params    {?key value? ...}
#                  ?-encoding value?
#                  ?-headers   {?key value? ...}
#                  ?-spec   ?mime | http? 
#                  (-chan value | -parts {token1 ... tokenN})
#
#       If the -canonical option is present, then the body is in
#       canonical (raw) form and is found by consulting either the,
#       -chan, or -parts option.
#
#       -header
#           a dictionary of headers
#               with possibliy-redundant keys


#
#       -params
#           a dictionary of parameters
#           with possibly-redundant keys
#
#
#       Also, -encoding, if present, specifies the
#       "Content-Transfer-Encoding" when copying the body.
#
#       If the -canonical option is not present, then the MIME part
#       contained in -chan option is parsed,
#       dynamically generating subordinates as appropriate.
#
# Results:
#    An initialized mime token.


proc ::mime::initializeaux {token args} {
    variable channels
    # FRINK: nocheck
    upvar 0 $token state
    upvar 0 state(canonicalP) canonicalP state(params) params \
	state(relax) relax

    set ipnuts 0

    set params {}

    set state(addcontentid) 1
    set state(addmessageid) 1
    set state(addmimeversion) 1


    # contains the decoded message body 
    set state(bodychan) {}
    set state(bodydecoded) 0
    set state(bodyparsed) 0
    set canonicalP 0
    set state(cid) 0
    set state(closechan) 1
    set state(contentid) {}
    set state(contentidlower) {}
    set state(encoding) {}
    set state(encodingdone) 0
    set state(eof) 0
    set state(header) {}
    set state(headerinternal) {}
    set state(headerinternallower) {}
    set state(headerlower) {}
    set state(headerparsed) 0
    set state(isstring) 0 
    set relax [dict create finalboundary 0]
    set state(messageid) {}
    set state(messageidlower) {}
    set state(root) $token
    set state(sawclosing) 0
    set state(spec) mime
    set state(size) 0
    set state(usemem) 0 
    set state(version) 1.0

    set userparams 0

    set argc [llength $args]
    for {set argx 0} {$argx < $argc} {incr argx} {
        set option [lindex $args $argx]
        if {[incr argx] >= $argc} {
            error "missing argument to $option"
        }
        set value [lindex $args $argx]

        switch $option {
	    -addcontentid {
		set state(addcontentid) [expr {!!$value}]
	    }
	    -addmessageid {
		set state(addmessageid) [expr {!!$value}]
	    }
	    -addmimeversion {
		set state(addmimeversion) [expr {!!$value}]
	    }
	    -boundary {
		set state(boundary) $value
	    }
            -canonical {
		set canonicalP 1
		set type [string tolower $value]
            }

	    -chan {

		checkinputs
		addchan $token [uplevel 1 [list namespace which $value]]
	    }

	    -close {
		set state(closechan) [expr {!!$value}]
	    }

            -encoding {
		set value [string tolower $value[set value {}]]

                switch $value {
                    7bit - 8bit - binary - quoted-printable - base64 {
                    }

                    default {
                        error "unknown value for -encoding $state(encoding)"
                    }
                }
                set state(encoding) [string tolower $value]
            }

	    -file {
		checkinputs
		addchan $token [tcllib::chan::base .new [
		    info cmdcount]_chan [open $value]]
	    }

            -headers {
		# process headers later in order to assure that content-id and
		# content-type occur first
		if {[info exists headers]} {
		    error [list {-headers option occurred more than once}]
		}
                if {[llength $value] % 2} {
                    error [list -headers expects a dictionary]
                }
		set headers $value
            }

            -params {
		if {$userparams} {
		    error [list {-params can only be provided once}]
		}
		set userparams 1
                if {[llength $value] % 2} {
		    error [list -params expects a dictionary]
                }
		foreach {mixed pvalue} $value {
		    set lower [string tolower $mixed]
		    if {[dict exists params $lower]} {
			error "the $mixed parameter may be specified at most once"
		    }

		    dict set params $lower $pvalue
		}
            }































            -parts {
		checkinputs
		set canonicalP 1
                set state(parts) $value
            }



	    -relax {
		relax $token $value 1 


	    }

            -root {
                # the following are internal options
                set state(root) $value
            }

	    -spec {
		switch $value {
		    http {
			set state(addcontentid) 0
			set state(addmimeversion) 0
			set state(addmessageid) 0
			set state(spec) http
		    }
		    mime {
			set state(addcontentid) 1
			set state(addmimeversion) 1
			set state(spec) mime
		    }
		    default {

			error [list {unknown protocol}]
		    }
		}
	    }

	    -strict {
		relax $token $value [expr {!$value}]
	    }

	    -string {
		checkinputs
		addchan $token [tcllib::chan::base .new [
		    info cmdcount]_chan [::tcl::chan::string $value]]
	    }

	    -usemem {
		set state(usemem) [expr {!!$value}] 
	    }

            default {
                error [list {unknown option} $option]
            }
        }
    }




    if {![info exists inputs]} {





	error [list {specify exactly one of} {-chan -file -parts -string}]
    }




















    if {$canonicalP} {




	if {![info exists type]} {
	    set type multipart/mixed
	}

	header setinternal $token Content-Type $type $params

	if {[info exists headers]} {
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794














2795
2796
2797
2798
2799
2800
2801
		}
		header::setinternal $token $name $hvalue
	    }
	}

	lassign [header get $token content-type] content dummy

        switch $state(value) {
            file {
                set state(offset) 0
            }

            parts {
                switch -glob $content {
                    text/*
                        -
                    image/*
                        -
                    audio/*
                        -
                    video/* {
                        error "-canonical $content and -parts do not mix"
                    }

                    default {
                        if {$state(encoding) ne {}} {
                            error "-encoding and -parts do not mix"
                        }
                    }
                }
            }
            default {# Go ahead}
        }

        set state(version) 1.0
        return
    }

    if {[dict size $params]} {
        error "-param requires -canonical"
    }
    if {$state(encoding) ne {}} {
        error "-encoding requires -canonical"
    }
    if {[info exists headers]} {
        error "-header requires -canonical"
    }

}
















# ::mime::mapencoding --
#
#    mime::mapencodings maps tcl encodings onto the proper names for their
#    MIME charset type.  This is only done for encodings whose charset types
#    were known.  The remaining encodings return {} for now.
#







<
<
<
<
|
<
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
<
<

















>
>
>
>
>
>
>
>
>
>
>
>
>
>







2626
2627
2628
2629
2630
2631
2632




2633

2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651


2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
		}
		header::setinternal $token $name $hvalue
	    }
	}

	lassign [header get $token content-type] content dummy





	if {[info exists state(parts)]} {

	    switch -glob $content {
		text/*
		    -
		image/*
		    -
		audio/*
		    -
		video/* {
		    error "-canonical $content and -parts do not mix"
		}

		default {
		    if {$state(encoding) ne {}} {
			error "-encoding and -parts do not mix"
		    }
		}
	    }
	}



        set state(version) 1.0
        return
    }

    if {[dict size $params]} {
        error "-param requires -canonical"
    }
    if {$state(encoding) ne {}} {
        error "-encoding requires -canonical"
    }
    if {[info exists headers]} {
        error "-header requires -canonical"
    }

}


proc mime::makeseekable token {
    upvar 0 $token state
    upvar 0 state(bodychan) bodychan state(fd) inputchan 
    set chan2 [::tcllib::chan::base [info cmdcount]_chan [file tempfile]]
    chan configure $chan2 -translation binary
    chan copy $inputchan $chan2
    incr size [tell $chan2]
    seek $chan2 0
    close $inputchan
    set inputchan [::tcllib::chan::base [info cmdcount]_chan $chan2]
    return
}


# ::mime::mapencoding --
#
#    mime::mapencodings maps tcl encodings onto the proper names for their
#    MIME charset type.  This is only done for encodings whose charset types
#    were known.  The remaining encodings return {} for now.
#
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826

    if {[info exists encodings($enc)]} {
        return $encodings($enc)
    }
    return {}
}


# ::mime::parsepart --
#
#       Parses the MIME headers and attempts to break up the message
#       into its various parts, creating a MIME token for each part.
#
# Arguments:
#       token  The MIME token to parse.







<







2700
2701
2702
2703
2704
2705
2706

2707
2708
2709
2710
2711
2712
2713

    if {[info exists encodings($enc)]} {
        return $encodings($enc)
    }
    return {}
}


# ::mime::parsepart --
#
#       Parses the MIME headers and attempts to break up the message
#       into its various parts, creating a MIME token for each part.
#
# Arguments:
#       token  The MIME token to parse.
2838
2839
2840
2841
2842
2843
2844
2845

2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859






































































2860
2861
2862
2863
2864

2865





2866

2867

2868


2869
2870







2871





































2872
2873
2874


2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068

3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
    parsepartaux $token
}


proc ::mime::parsepartaux token {
    # FRINK: nocheck
    upvar 0 $token state
    upvar 0 state(last) last


    header parse $token

    # although rfc 2045 5.2 defines a default treatment for content without a
    # type, don't automatically add an explicit content-type field

    #if {![header exists $token content-type]} {
    #    # rfc 2045 5.2
    #    header setinternal $token Content-Type text/plain [
    #        dict create charset us-ascii]
    #}

    lassign [contenttype $token] content params








































































    set fileP [info exists state(file)]
    if {![string match multipart/* $content]} {
        if {$fileP} {
            set x [tell $state(fd)]

            incr state(count) [expr {$state(offset) - $x}]





            set state(offset) $x

        } else {

            # rebuild string, this is cheap and needed by other functions


            set state(string) [join [
                lrange $state(lines) $state(lines.current) end] \n]







        }






































        if {[string match message/* $content]} {
            # FRINK: nocheck


            variable [set child $token-[incr state(cid)]]

            set state(value) parts
            set state(parts) $child
            if {$fileP} {
                mime::initializeaux $child \
                    -file $state(file) -root $state(root) \
                    -offset $state(offset) -count $state(count)
            } else {
                if {[info exists state(encoding)]} {
                    set strng [join [
                        lrange $state(lines) $state(lines.current) end] \n]
                    switch $state(encoding) {
                        base64 -
                        quoted-printable {
                            set strng [$state(encoding) -mode decode -- $strng]
                        }
                        default {}
                    }
                    mime::initializeaux $child -root $state(root) -string $strng
                } else {
                    mime::initializeaux $child -root $state(root) -lineslist [
                        lrange $state(lines) $state(lines.current) end]
                }
            }
        }
        return
    }

    set state(value) parts

    dict update params boundary boundary {}
    if {![info exists boundary]} {
        error "boundary parameter is missing in $content"
    }

    if {[string trim $boundary] eq {}} {
        error "boundary parameter is empty in $content"
    }

    if {$fileP} {
        set pos [tell $state(fd)]
            # This variable is like 'start', for the reasons laid out
            # below, in the other branch of this conditional.
            set initialpos $pos
        } else {
            # This variable is like 'start', a list of lines in the
            # part. This record is made even before we find a starting
            # boundary and used if we run into the terminating boundary
            # before a starting boundary was found. In that case the lines
            # before the terminator as recorded by tracelines are seen as
            # the part, or at least we attempt to parse them as a
            # part. See the forceoctet and nochild flags later. We cannot
            # use 'start' as that records lines only after the starting
            # boundary was found.
            set tracelines [list]
    }

    set inP 0
    set moreP 1
    set forceoctet 0
    while {$moreP} {
        if {$fileP} {
            if {$pos > $last} {
                # We have run over the end of the part per the outer
                # information without finding a terminating boundary.
                # We now fake the boundary and force the parser to
                # give any new part coming of this a mime-type of
                # application/octet-stream regardless of header
                # information.
                set line "--$boundary--"
                set x [string length $line]
                set forceoctet 1
            } else {
                if {[set x [gets $state(fd) line]] < 0} {
                    error "end-of-file encountered while parsing $content"
                }
            }
            incr pos [expr {$x + 1}]
        } else {
            if {$state(lines.current) >= $state(lines.count)} {
                error "end-of-string encountered while parsing $content"
            } else {
                set line [lindex $state(lines) $state(lines.current)]
                incr state(lines.current)
                set x [string length $line]
            }
            set x [string length $line]
        }
        if {[string last \r $line] == $x - 1} {
            set line [string range $line 0 [expr {$x - 2}]]
            set crlf 2
        } else {
            set crlf 1
        }

        if {[string first --$boundary $line] != 0} {
             if {$inP && !$fileP} {
                 lappend start $line
             }
             continue
        } else {
            lappend tracelines $line
        }

        if {!$inP} {
            # Haven't seen the starting boundary yet. Check if the
            # current line contains this starting boundary.

            if {$line eq "--$boundary"} {
                # Yes. Switch parser state to now search for the
                # terminating boundary of the part and record where
                # the part begins (or initialize the recorder for the
                # lines in the part).
                set inP 1
                if {$fileP} {
                    set start $pos
                } else {
                    set start [list]
                }
                continue
            } elseif {$line eq "--$boundary--"} {
                # We just saw a terminating boundary before we ever
                # saw the starting boundary of a part. This forces us
                # to stop parsing, we do this by forcing the parser
                # into an accepting state. We will try to create a
                # child part based on faked start position or recorded
                # lines, or, if that fails, let the current part have
                # no children.

                # As an example note the test case mime-3.7 and the
                # referenced file "badmail1.txt".

                set inP 1
                if {$fileP} {
                    set start $initialpos
                } else {
                    set start $tracelines
                }
                set forceoctet 1
                # Fall through. This brings to the creation of the new
                # part instead of searching further and possible
                # running over the end.
            } else {
                continue
            }
        }

        # Looking for the end of the current part. We accept both a
        # terminating boundary and the starting boundary of the next
        # part as the end of the current part.

        if {[set moreP [string compare $line --$boundary--]]
	    && $line ne "--$boundary"} {

            # The current part has not ended, so we record the line
            # if we are inside a part and doing string parsing.
            if {$inP && !$fileP} {
                lappend start $line
            }
            continue
        }

        # The current part has ended. We now determine the exact
        # boundaries, create a mime part object for it and recursively
        # parse it deeper as part of that action.

        # FRINK: nocheck
        variable [set child $token-[incr state(cid)]]

        lappend state(parts) $child

        set nochild 0
        if {$fileP} {
            if {[set count [expr {$pos - ($start + $x + $crlf + 1)}]] < 0} {
                set count 0
            }
            if {$forceoctet} {
                if {[catch {
                    mime::initializeaux $child \
                        -file $state(file) -root $state(root) \
                        -offset $start -count $count
		    parsepart $child
                }]} {
                    set nochild 1
                    set state(parts) [lrange $state(parts) 0 end-1]
                }
	    } else {
                mime::initializeaux $child \
                    -file $state(file) -root $state(root) \
                    -offset $start -count $count
		parsepart $child
            }
            seek $state(fd) [set start $pos] start

        } else {
            if {$forceoctet} {
                if {[catch {
                    mime::initializeaux $child -root $state(root) \
			-lineslist $start
		    parsepart $child
                } cres copts]} {
                    set nochild 1
                    set state(parts) [lrange $state(parts) 0 end-1]
                }
            } else {
                mime::initializeaux $child -root $state(root) -lineslist $start
		parsepart $child
            }
            set start {}
        }
        if {$forceoctet && !$nochild} {
	    header setinternal $child Content-Type application/octet-stream
        }
        set forceoctet 0
    }
}


# ::mime::property --
#
#   mime::property returns the properties of a MIME part.
#
#   The properties are:
#
#       property    value
#       ========    =====
#       content     the type/subtype describing the content
#       encoding    the "Content-Transfer-Encoding"
#       params      a list of "Content-Type" parameters
#       parts       a list of tokens for the part's subordinates
#       size        the approximate size of the content (unencoded)
#
#   The "parts" property is present only if the MIME part has
#   subordinates.
#
#   If mime::property is invoked with the name of a specific
#   property, then the corresponding value is returned; instead, if
#   -names is specified, a list of all properties is returned;







|
>














>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
|
>
|
>
>
>
>
>
|
>
|
>
|
>
>
|
|
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



>
>


<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
|
<
<
<
<
<
<
>
|
<
|
<
|
<
<
<
<
|
<
<
<
|
|
<
<
<
<
<
<















|







2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890



2891






































































































2892





























































2893











2894




2895






2896
2897

2898

2899




2900



2901
2902






2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
    parsepartaux $token
}


proc ::mime::parsepartaux token {
    # FRINK: nocheck
    upvar 0 $token state
    upvar 0 state(bodychan) bodychan state(eof) eof \
	state(fd) fd state(size) size state(usemem) usemem state(relax) relax

    header parse $token

    # although rfc 2045 5.2 defines a default treatment for content without a
    # type, don't automatically add an explicit content-type field

    #if {![header exists $token content-type]} {
    #    # rfc 2045 5.2
    #    header setinternal $token Content-Type text/plain [
    #        dict create charset us-ascii]
    #}

    lassign [contenttype $token] content params

    if {$usemem} {
	set bodychan [tcllib::chan::base .new [info cmdcount]_bodychan [
	    ::tcl::chan::memchan]]
    } else {
	set bodychan [tcllib::chan::getslimit .new [info cmdcount]_bodychan [
	    file tempfile]]
    }
    if {[dict exists $params charset]} {
	set charset [reversemapencoding [dict get $params charset]]
	if {$charset eq {}} {
	    puts stderr [list {unknown charset} [
		dict get $params charset] {using binary translation instead}]
	    # but still do line automatic translation
	    $fd configure -encoding binary -translation auto
	} else {
	    $fd configure -encoding [reversemapencoding [dict get $params charset]]
	}
    }
    $bodychan configure -translation binary

    if {[info exists state(boundary)]} {
	set gets [list mimegets $token line]
	set iseof {$eof}
    } else {
	set gets [list $fd gets line]
	set iseof {[$fd eof] || $eof}
    }

    if {[string match multipart/* $content]} {
	set state(parts) {}

	dict update params boundary boundary {}
	if {![info exists state(boundary)]} {
	    if {![info exists boundary]} {
		error "boundary parameter is missing in $content"
	    }

	    if {[string trim $boundary] eq {}} {
		error "boundary parameter is empty in $content"
	    }
	}

	while 1 {
	    if $iseof {
		break
	    }
	    if {![llength $state(parts)]} {
		set x [{*}$gets]
		if {$x == -1} {
		    break
		}
	    }
	    if {[string first --$boundary-- $line] >= 0} {
		    # No starting boundary was seen prior to the terminating boundary.
		    # Interpret this to mean there are no more parts, and also attempt
		    # to make a part from data already seen.

		    # Covered by by test case mime-3.7, using  "badmail1.txt".

		    set state(sawclosing) 1

		    $bodychan puts $line
		    $bodychan seek 0

		    # FRINK: nocheck
		    variable [set child $token-[incr state(cid)]]

		    mime::initializeaux $child -chan $bodychan \
			-root $state(root) -boundary $boundary -usemem $usemem
		    parsepart $child
		    
		    lappend state(parts) $child
		    header setinternal $child Content-Type application/octet-stream
		    break
	    } elseif {[llength $state(parts)] || [string first --$boundary $line] == 0} {
		    # either just saw the first boundary or saw a boundary between parts

		    # do not brace this expression 
		    if $iseof {
			# either saw the closing boundary or reached the end of the file
			break
		    } elseif {[string first --$boundary-- $line] >= 0} {
			set state(sawclosing) 1
			break
		    } else {
			#mimegets returned 0 because it found a border

			# FRINK: nocheck
			variable [set child $token-[incr state(cid)]]


			mime::initializeaux $child -chan $fd \
			    -root $state(root) -boundary $boundary -usemem $usemem
			parsepart $child
			lappend state(parts) $child
			upvar 0 $child childstate
			set state(sawclosing) $childstate(sawclosing)
			if {$childstate(eof)} break
		    }
	    } else {
		# Accumulate data in case the terminating boundary occurs starting
		# boundary was found, so that a part can be generated from data
		# seen so far.
		if $iseof {
		    $bodychan puts -nonewline $line
		} else {
		    $bodychan puts $line
		}
		set size [expr {$size + [
		    string length $line] + 1}]
	    }
	}
	if {!$state(sawclosing) && ![dict get $relax finalboundary]} {
	    error {end-of-string encountered while parsing multipart/form-data}
	}
    } else {
	if {[info exists state(boundary)]} {
	    while 1 {
		set x [{*}$gets]
		if {$x == -1} {
		    break
		} else {
		    if {[incr linesout] > 1} {
			$bodychan puts -nonewline \n$line
		    } else {
			$bodychan puts -nonewline $line
		    }
		    set size [expr {$size + [
			string length $line] + 1}]
		}
	    }
	} else {
	    $fd copy [$bodychan configure -chan]
	    set size [$bodychan tell]
	}
	$bodychan seek 0

        if {[string match message/* $content]} {
            # FRINK: nocheck
	    setencoding $token $bodychan
	    setcharset $token $bodychan
            variable [set child $token-[incr state(cid)]]




	    mime::initializeaux $child -chan $bodychan -usemem $usemem




































































































































































            set state(parts) $child











	    parsepart $child




        } else {






	    # this is undtrusted data, so keep the getslimit enabled on the
	    # assumption that no one else wants to get hit by a long-line

	    # attack either.

	    #$bodychan configure -getslimit -1




	}



    }
    return






}


# ::mime::property --
#
#   mime::property returns the properties of a MIME part.
#
#   The properties are:
#
#       property    value
#       ========    =====
#       content     the type/subtype describing the content
#       encoding    the "Content-Transfer-Encoding"
#       params      a list of "Content-Type" parameters
#       parts       a list of tokens for the part's subordinates
#       size        the approximate size of the content {before decoding} 
#
#   The "parts" property is present only if the MIME part has
#   subordinates.
#
#   If mime::property is invoked with the name of a specific
#   property, then the corresponding value is returned; instead, if
#   -names is specified, a list of all properties is returned;
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
# Results:
#       Returns the properties of a MIME part

proc ::mime::property {token {property {}}} {
    # FRINK: nocheck
    upvar 0 $token state
    parsepart $token


    lassign [contenttype $token] content params

    switch $property {
        {} {
            array set properties [list content  $content \
                                       encoding $state(encoding) \







<







2934
2935
2936
2937
2938
2939
2940

2941
2942
2943
2944
2945
2946
2947
# Results:
#       Returns the properties of a MIME part

proc ::mime::property {token {property {}}} {
    # FRINK: nocheck
    upvar 0 $token state
    parsepart $token


    lassign [contenttype $token] content params

    switch $property {
        {} {
            array set properties [list content  $content \
                                       encoding $state(encoding) \
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242

proc ::mime::parseaddress {string args} {
    variable mime
    set token [namespace current]::[incr mime(uid)]
    # FRINK: nocheck
    upvar 0 $token state

	if {[llength $args]} {
		set string2 [lindex $args end]
		set args [list $string {*}[lrange $args 0 end-1]]
		set string $string2
	}
	dict for {opt val} $args {
		switch $opt {
			hostname {
				set state(default_host) $val
			}
		}
	}

    catch {mime::parseaddressaux $token $string} result copts

    foreach name [array names state] {
        unset state($name)
    }
    # FRINK: nocheck







|
|
|
|
|
|
|
|
|
|
|
|







3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054

proc ::mime::parseaddress {string args} {
    variable mime
    set token [namespace current]::[incr mime(uid)]
    # FRINK: nocheck
    upvar 0 $token state

    if {[llength $args]} {
	set string2 [lindex $args end]
	set args [list $string {*}[lrange $args 0 end-1]]
	set string $string2
    }
    dict for {opt val} $args {
	switch $opt {
	    hostname {
		set state(default_host) $val
	    }
	}
    }

    catch {mime::parseaddressaux $token $string} result copts

    foreach name [array names state] {
        unset state($name)
    }
    # FRINK: nocheck
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697





















3698
3699
3700
3701
3702
3703
3704

        set state(input) [string range $state(input) 1 end]
    }

    return [set state(lastC) LX_ATOM]
}


# ::mime::qp_encode --
#
#    Tcl version of quote-printable encode
#
# Arguments:
#    string        The string to quote.
#       encoded_word  Boolean value to determine whether or not encoded words
#                     (RFC 2047) should be handled or not. (optional)
#
# Results:
#    The properly quoted string is returned.

proc ::mime::qp_encode {string {encoded_word 0} {no_softbreak 0}} {
    # 8.1+ improved string manipulation routines used.
    # Replace outlying characters, characters that would normally
    # be munged by EBCDIC gateways, and special Tcl characters "[\]{}
    # with =xx sequence

    if {$encoded_word} {
        # Special processing for encoded words (RFC 2047)
        set regexp {[\x00-\x08\x0B-\x1E\x21-\x24\x3D\x40\x5B-\x5E\x60\x7B-\xFF\x09\x5F\x3F]}
	lappend mapChars { } _
    } else {
        set regexp {[\x00-\x08\x0B-\x1E\x21-\x24\x3D\x40\x5B-\x5E\x60\x7B-\xFF]}
    }
    regsub -all -- $regexp $string {[format =%02X [scan "\\&" %c]]} string

    # Replace the format commands with their result

    set string [subst -novariables $string]

    # soft/hard newlines and other
    # Funky cases for SMTP compatibility
    lappend mapChars " \n" =20\n \t\n =09\n \n\.\n =2E\n "\nFrom " "\n=46rom "

    set string [string map $mapChars $string]

    # Break long lines - ugh

    # Implementation of FR #503336
    if {$no_softbreak} {
        set result $string
    } else {
        set result {}
        foreach line [split $string \n] {
            while {[string length $line] > 72} {
                set chunk [string range $line 0 72]
                if {[regexp -- (=|=.)$ $chunk dummy end]} {

                    # Don't break in the middle of a code

                    set len [expr {72 - [string length $end]}]
                    set chunk [string range $line 0 $len]
                    incr len
                    set line [string range $line $len end]
                } else {
                    set line [string range $line 73 end]
                }
                append result $chunk=\n
            }
            append result $line\n
        }

        # Trim off last \n, since the above code has the side-effect
        # of adding an extra \n to the encoded string and return the
        # result.
        set result [string range $result 0 end-1]
    }

    # If the string ends in space or tab, replace with =xx

    set lastChar [string index $result end]
    if {$lastChar eq { }} {
        set result [string replace $result end end =20]
    } elseif {$lastChar eq "\t"} {
        set result [string replace $result end end =09]
    }

    return $result
}


# ::mime::qp_decode --
#
#    Tcl version of quote-printable decode
#
# Arguments:
#    string        The quoted-prinatble string to decode.
#       encoded_word  Boolean value to determine whether or not encoded words
#                     (RFC 2047) should be handled or not. (optional)
#
# Results:
#    The decoded string is returned.

proc ::mime::qp_decode {string {encoded_word 0}} {
    # 8.1+ improved string manipulation routines used.
    # Special processing for encoded words (RFC 2047)

    if {$encoded_word} {
        # _ == \x20, even if SPACE occupies a different code position
        set string [string map [list _ \u0020] $string]
    }

    # smash the white-space at the ends of lines since that must've been
    # generated by an MUA.

    regsub -all -- {[ \t]+\n} $string \n string
    set string [string trimright $string " \t"]

    # Protect the backslash for later subst and
    # smash soft newlines, has to occur after white-space smash
    # and any encoded word modification.

    #TODO: codepath not tested
    set string [string map [list \\ {\\} =\n {}] $string]

    # Decode specials

    regsub -all -nocase {=([a-f0-9][a-f0-9])} $string {\\u00\1} string

    # process \u unicode mapped chars

    return [subst -novariables -nocommands $string]
}


# ::mime::reversemapencoding --
#
#    mime::reversemapencodings maps MIME charset types onto tcl encoding names.
#    Those that are unknown return {}.
#
# Arguments:
#       mimeType  The MIME charset to convert into a tcl encoding type.
#
# Results:
#    Returns the tcl encoding name for the specified mime charset, or {}
#       if none is known.

proc ::mime::reversemapencoding {mimeType} {

    variable reversemap

    set lmimeType [string tolower $mimeType]
    if {[info exists reversemap($lmimeType)]} {
        return $reversemap($lmimeType)
    }
    return {}
}























# ::mime::serialize --
#
#    Serializes a message to a value or a channel.
#
# Arguments:
#       token      The MIME token to parse.







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<













|
<









>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







3353
3354
3355
3356
3357
3358
3359






























































































































3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373

3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410

        set state(input) [string range $state(input) 1 end]
    }

    return [set state(lastC) LX_ATOM]
}
































































































































# ::mime::reversemapencoding --
#
#    mime::reversemapencodings maps MIME charset types onto tcl encoding names.
#    Those that are unknown return {}.
#
# Arguments:
#       mimeType  The MIME charset to convert into a tcl encoding type.
#
# Results:
#    Returns the tcl encoding name for the specified mime charset, or {}
#       if none is known.

proc ::mime::reversemapencoding mimeType {

    variable reversemap

    set lmimeType [string tolower $mimeType]
    if {[info exists reversemap($lmimeType)]} {
        return $reversemap($lmimeType)
    }
    return {}
}


proc ::mime::relax {token args} {
    upvar 0 $token state
    upvar 0 state(relax) relax
    foreach {key val} $args {
	switch $key {
	    all {
		dict set relax finalboundary 1
	    }
	    finalboundary {
		dict set relax $key [expr {!!$val}]
	    }
	    default {
		error [list {unknown value for -relax} $key {should be one of} {
		    all finalboundary
		}]
	    }
	}
    }
}


# ::mime::serialize --
#
#    Serializes a message to a value or a channel.
#
# Arguments:
#       token      The MIME token to parse.
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763








3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900

3901
3902
3903
3904
3905
3906
3907
3908
3909
3910























































3911
3912
3913
3914
3915
3916
3917
    set chan {} 
    dict for {arg val} $args {
	switch $arg {
	    -chan {
		if {$val eq {}} {
		    error [list {chan must not be the empty string}]
		}
		set chan $val
	    }
	    -level {
		set level [expr {$val + 0}]
	    }
	    default {
		error [list {unknown option} $arg]
	    }
	}
    }

    if {$chan eq {}} {
	# FRINK: nocheck
	upvar 0 $token state

	set openP [info exists state(fd)]

	set code [catch {mime::serialize_value $token $level} result copts]

	if {!$openP && [info exists state(fd)]} {
	    if {![info exists state(root)]} {
		catch {close $state(fd)}
	    }
	    unset state(fd)
	}
	return -options $copts $result
    } else {
	return [serialize_chan $token $chan $level]
    }

}


proc ::mime::serialize_chan {token channel level} {
    # FRINK: nocheck
    upvar 0 $token state
    upvar 0 state(fd) fd
    parsepart $token

    set result {}
    if {!$level && $state(addmimeversion)} {
	puts $channel [header serialize $token MIME-Version $state(version) {}]
    }








    foreach {name value} [header get $token] {
	puts $channel [header serialize $token $name {*}$value]
    }

    set converter {}
    set encoding {}
    if {$state(value) ne "parts"} {
        if {$state(canonicalP)} {
            if {[set encoding $state(encoding)] eq {}} {
                set encoding [encoding $token]
            }
            if {$encoding ne {}} {
                puts $channel "Content-Transfer-Encoding: $encoding"
            }
            switch $encoding {
                base64
                    -
                quoted-printable {
                    set converter $encoding
                }
                7bit - 8bit - binary - {} {
                    # Bugfix for [#477088], also [#539952]
                    # Go ahead
                }
                default {
                    error "Can't handle content encoding \"$encoding\""
                }
            }
        }
    }

    if {[info exists state(error)]} {
        unset state(error)
    }

    switch $state(value) {
        file {
            if {[info exists state(root)]} {
                set size $state(count)
            } else {
                # read until eof
                set size -1
            }
            seek $fd $state(offset) start

            puts $channel {}

            while {$size != 0 && ![eof $fd]} {
                if {$size < 0 || $size > 32766} {
                    set X [read $fd 32766]
                } else {
                    set X [read $fd $size]
                }
                if {$size > 0} {
                    set size [expr {$size - [string length $X]}]
                }
                if {$converter eq {}} {
                    puts -nonewline $channel $X
                } else {
                    puts -nonewline $channel [$converter -mode encode -- $X]
                }
            }
        }

        parts {
	    lassign [contenttype $token] content params
	    set boundary [dict get $params boundary]

            switch -glob $content {
                message/* {
                    puts $channel {}
                    foreach part $state(parts) {
                        mime::serialize_chan $part $channel 1
                        break
                    }
                }

                default {
                    # Note RFC 2046: See serialize_value for details.
                    #
                    # The boundary delimiter MUST occur at the
                    # beginning of a line, i.e., following a CRLF, and
                    # the initial CRLF is considered to be attached to
                    # the boundary delimiter line rather than part of
                    # the preceding part.
                    #
                    # - The above means that the CRLF before $boundary
                    #   is needed per the RFC, and the parts must not
                    #   have a closing CRLF of their own. See Tcllib bug
                    #   1213527, and patch 1254934 for the problems when
                    #   both file/string branches added CRLF after the
                    #   body parts.


                    foreach part $state(parts) {
                        puts $channel \n--$boundary
                        mime::serialize_chan $part $channel 1
                    }
                    puts $channel \n--$boundary--
                }
            }
        }

        string {
            if {[catch {fconfigure $channel -buffersize} blocksize]} {
                set blocksize 4096
            } elseif {$blocksize < 512} {
                set blocksize 512
            }
            set blocksize [expr {($blocksize / 4) * 3}]

            # [893516]
            fconfigure $channel -buffersize $blocksize

            puts $channel {}

            #TODO: tests don't cover these paths
            if {$converter eq {}} {
                puts -nonewline $channel $state(string)
            } else {
                puts -nonewline $channel [$converter -mode encode -- $state(string)]
            }
        }
        default {
            error "Unknown value \"$state(value)\""
        }
    }

    flush $channel

    if {[info exists state(error)]} {
        error $state(error)
    }
}


proc ::mime::serialize_value {token level} {

    set chan [tcl::chan::memchan]
    chan configure $chan -translation crlf
    serialize_chan $token $chan $level
    seek $chan 0
    chan configure $chan -translation binary
    set res [read $chan]
    close $chan
    return $res
}

























































# ::mime::uniqueID --
#
#    Used to generate a 'globally unique identifier' for the content-id.
#    The id is built from the pid, the current time, the hostname, and
#    a counter that is incremented each time a message is sent.
#







|













<
<
<

<
<
<
<
<
<
<




<






|




|

>
>
>
>
>
>
>
>

|




|

<
|
<

|
<
<
<
<
<
<
<
<
<
<
<
<
<
<








<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|

|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|
|
|
|
|
|
|
|
|
<
<
<
|
|
<
<
|
<
|
|
|
|
<
<
<
|
|
<
<
<
|
|


|








>
|
|

|
|
|
|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440



3441







3442
3443
3444
3445

3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474

3475

3476
3477














3478
3479
3480
3481
3482
3483
3484
3485


3486



























3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524



3525
3526


3527

3528
3529
3530
3531



3532
3533



3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
    set chan {} 
    dict for {arg val} $args {
	switch $arg {
	    -chan {
		if {$val eq {}} {
		    error [list {chan must not be the empty string}]
		}
		set chan [uplevel 1 [list ::namespace which $val]]
	    }
	    -level {
		set level [expr {$val + 0}]
	    }
	    default {
		error [list {unknown option} $arg]
	    }
	}
    }

    if {$chan eq {}} {
	# FRINK: nocheck
	upvar 0 $token state



	set code [catch {mime::serialize_value $token $level} result copts]







	return -options $copts $result
    } else {
	return [serialize_chan $token $chan $level]
    }

}


proc ::mime::serialize_chan {token channel level} {
    # FRINK: nocheck
    upvar 0 $token state
    upvar 0 state(bodychan) bodychan
    parsepart $token

    set result {}
    if {!$level && $state(addmimeversion)} {
	$channel puts [header serialize $token MIME-Version $state(version) {}]
    }
    contentid $token
    if {![header exists $token content-id] && $state(addcontentid)} {
	header::setinternal $token Content-ID [contentid $token]
    }
    if {![header exists $token message-id] && $state(addmessageid)} {
	header::setinternal $token Message-ID [messageid $token]
    }

    foreach {name value} [header get $token] {
	$channel puts [header serialize $token $name {*}$value]
    }

    set converter {}
    set encoding {}
    if {![info exists state(parts)]} {
        if {$state(canonicalP)} {

	    set encoding [getTransferEncoding $token]

            if {$encoding ne {}} {
                $channel puts "Content-Transfer-Encoding: $encoding"














            }
        }
    }

    if {[info exists state(error)]} {
        unset state(error)
    }



    if {[info exists state(parts)]} {



























	lassign [contenttype $token] content params
	set boundary [dict get $params boundary]

	switch -glob $content {
	    message/* {
		$channel puts {}
		foreach part $state(parts) {
		    mime::serialize_chan $part $channel 1
		    break
		}
	    }

	    default {
		# Note RFC 2046: See serialize_value for details.
		#
		# The boundary delimiter MUST occur at the
		# beginning of a line, i.e., following a CRLF, and
		# the initial CRLF is considered to be attached to
		# the boundary delimiter line rather than part of
		# the preceding part.
		#
		# - The above means that the CRLF before $boundary
		#   is needed per the RFC, and the parts must not
		#   have a closing CRLF of their own. See Tcllib bug
		#   1213527, and patch 1254934 for the problems when
		#   both file/string branches added CRLF after the
		#   body parts.


		foreach part $state(parts) {
		    $channel puts \n--$boundary
		    mime::serialize_chan $part $channel 1
		}
		$channel puts \n--$boundary--
	    }
	}
    } else {
	$channel puts {}



	if {$state(canonicalP)} {
	    set transforms [setencoding $token $channel]


	    $state(fd) seek 0

	    $state(fd) copy [$channel $ chan]
	    while {[incr transforms -1] >= 0} {
		$channel $channel
	    }



	} else {
	    $state(bodychan) seek 0



	    $state(bodychan) copy [$channel $ chan]
	}
    }

    $channel flush

    if {[info exists state(error)]} {
        error $state(error)
    }
}


proc ::mime::serialize_value {token level} {
    set chan [::tcllib::chan::base .new [info cmdcount]_serialize_value [
	tcl::chan::memchan]]
    $chan configure -translation crlf
    serialize_chan $token $chan $level
    $chan seek 0
    $chan configure -translation binary
    set res [$chan read]
    $chan close
    return $res
}


proc ::mime::setencoding {token chan} {
    upvar 0 $token state

    set transforms 0

    if {[info exists state(encoding)]} {
	switch $state(encoding) {
	    base64 {
		package require tcl::transform::base64
		::tcl::transform::base64 [$chan configure -chan]
		incr transforms
	    }
	    quoted-printable {
		package require {tcl transform qp}
		::tcl::transform::qp [$chan configure -chan]
		incr transforms
	    }
	    7bit - 8bit - binary - {} {
		# Bugfix for [#477088]
		# Go ahead, leave chunk alone
	    }
	    default {
		error [list {Can't handle content encoding} $state(encoding)]
	    }
	}
    }
    return $transforms
}

proc ::mime::setcharset {token chan} {
    upvar 0 $token state
    lassign [contenttype $token] content params
    if {[dict exists $params charset]} {
	set mcharset [dict get $params charset]
    } else {
	switch $state(spec) {
	    http {
		set mcharset UTF-8
	    }
	    mime - default {
		# mime
		set mcharset US-ASCII
	    }
	}
    }
    set encoding [reversemapencoding $mcharset]
    if {$encoding eq {}} {
	$chan configure -translation binary
    } else {
	$chan configure -encoding $encoding 
    }
    return
}


# ::mime::uniqueID --
#
#    Used to generate a 'globally unique identifier' for the content-id.
#    The id is built from the pid, the current time, the hostname, and
#    a counter that is incremented each time a message is sent.
#
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
        error [list {unknown charset} $charset]
    }

    if {$encodings($charset) eq {}} {
        error [list {invalid charset} $charset]
    }

    if {$method ne "base64" && $method ne "quoted-printable"} {
        error [list {unknown method} $method {must be one of} \
	    {base64 quoted-printable}]
    }

    # default to encoded and a length that won't make the Subject header to long
    array set options [list -charset_encoded 1 -maxlength 66]
    array set options $args







|







3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
        error [list {unknown charset} $charset]
    }

    if {$encodings($charset) eq {}} {
        error [list {invalid charset} $charset]
    }

    if {$method ne {base64} && $method ne {quoted-printable}} {
        error [list {unknown method} $method {must be one of} \
	    {base64 quoted-printable}]
    }

    # default to encoded and a length that won't make the Subject header to long
    array set options [list -charset_encoded 1 -maxlength 66]
    array set options $args
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
            set count 0
            while {$count < $string_length} {
                set length 0
                set encoded_word {}
                while {$length < $maxlength && $count < $string_length} {
                    set char [string range $unencoded_string $count $count]
                    set enc_char [::encoding convertto $charset $char]
                    set qp_enc_char [qp_encode $enc_char 1]
                    set qp_enc_char_length [string length $qp_enc_char]
                    if {$qp_enc_char_length > $maxlength} {
                        error [list maxlength $options(-maxlength) \
			    {too short for chosen charset and encoding}]
                    }
                    if {
			$length + [string length $qp_enc_char] > $maxlength







|







3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
            set count 0
            while {$count < $string_length} {
                set length 0
                set encoded_word {}
                while {$length < $maxlength && $count < $string_length} {
                    set char [string range $unencoded_string $count $count]
                    set enc_char [::encoding convertto $charset $char]
                    set qp_enc_char [qp::encode $enc_char 1]
                    set qp_enc_char_length [string length $qp_enc_char]
                    if {$qp_enc_char_length > $maxlength} {
                        error [list maxlength $options(-maxlength) \
			    {too short for chosen charset and encoding}]
                    }
                    if {
			$length + [string length $qp_enc_char] > $maxlength
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
    }

    switch -exact $method {
        base64 {
            set result [base64 -mode decode -- $string]
        }
        quoted-printable {
            set result [qp_decode $string 1]
        }
        {} {
            # Go ahead
        }
        default {
            error "Can't handle content encoding \"$method\""
        }







|







3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
    }

    switch -exact $method {
        base64 {
            set result [base64 -mode decode -- $string]
        }
        quoted-printable {
            set result [qp::decode $string 1]
        }
        {} {
            # Go ahead
        }
        default {
            error "Can't handle content encoding \"$method\""
        }

Changes to modules/mime/mime.test.

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
    use md5/md5x.tcl md5

    use namespacex/namespacex.tcl namespacex
}
testing {
    useLocal mime.tcl mime
}



# -------------------------------------------------------------------------

namespace import mime::*

# -------------------------------------------------------------------------



proc channamescmp names {
    expr {[llength $names] == [llength [chan names]]}
}


proc cleanly script {
    set ns [info cmdcount]
    namespace eval $ns {
	namespace path [namespace parent]
    }
    catch {namespace eval $ns $script} cres copts
    foreach name [info vars ${ns}::*] {
	catch [list mime finalize $name]
    }
    namespace delete $ns
    return -options $copts $cres
}


proc setup1 {} {
    uplevel 1 {
	set channames [chan names]
    }
}


proc with.chan {name args} {
    set body [lindex $args end]
    set args [lrange $args 0 end-1]

    set chan [open $name]
    uplevel 1 [list set tok [::mime::initialize {*}$args -chan $chan]]

    uplevel 1 $body


}



proc with.file {name args} {
    set body [lindex $args end]
    set args [lrange $args 0 end-1]
    uplevel 1 [list set tok [::mime::initialize {*}$args -file $name]]
    uplevel 1 $body
}


proc main {} {
variable encoded
variable name
variable n






test mime-1.1 {initialize with no args} {cleanly {
    catch {initialize} res
    subst $res
}} {{specify exactly one of} {-file -parts -string}}


test mime-2.1 {Generate a MIME message} {cleanly {
    
    set tok [initialize -canonical Text/plain -string {jack and jill}]
    set msg [mime::serialize $tok]

    # The generated message is predictable except for the Content-ID
    regexp "MIME-Version: 1.0\r

Content-ID: \[^\n]+\r
Content-Type: text/plain\r
\r
jack and jill" $msg
}} 1

foreach name {file chan} {
    test mime-2.1.1.$name {Generate a MIME message} {cleanly {
	setup1
	with.$name [makeFile {jack and jill} input.txt] -canonical Text/plain {
	    set msg [mime::body $tok]
	    mime::finalize $tok

	    # The generated message is predictable except for the Content-ID
	    lappend res $msg
	    lappend res [channamescmp $channames]
	    return $res
	}
    }} [list "jack and jill\n" 1]
}


test mime-2.2 {Generate a multi-part MIME message} {cleanly {
    set tok1 [initialize -canonical Text/plain -string {jack and jill}]
    set tok2 [initialize -canonical Text/plain -string james]
    set bigTok [mime::initialize -canonical Multipart/MyType \
	    -params [list MyParam foo boundary bndry] \
	    -headers [list Content-Description {Test Multipart}] \
	    -parts [list $tok1 $tok2]]
    set msg [mime::serialize $bigTok]
    # The generated message is predictable except for the Content-ID

    list [regexp "MIME-Version: 1.0\r

Content-ID: \[^\n]+\r
Content-Type: multipart/mytype\r
\t; \[^\n]+\r
\t; \[^\n]+\r
Content-Description: Test Multipart\r
\r
--bndry\r

Content-ID: \[^\n]+\r
Content-Type: text/plain\r
\r
jack and jill\r
--bndry\r

Content-ID: \[^\n]+\r
Content-Type: text/plain\r
\r
james\r
--bndry--\r
" $msg] [regexp boundary=bndry $msg] [regexp myparam=foo $msg]
}} {1 1 1}



test mime-2.3 {Generate a multi-part MIME message} {cleanly {
    set tok1 [initialize -canonical Text/plain -string {jack and jill}]
    set tok2 [initialize -canonical Text/plain -string james]
    set bigTok [mime::initialize \
	    -params [list MyParam foo boundary bndry] \
	    -headers [list Content-Description {Test Multipart}] \
	    -parts [list $tok1 $tok2]]
    set msg [mime::serialize $bigTok]
    # The generated message is predictable except for the Content-ID
    list [regexp "MIME-Version: 1.0\r

Content-ID: \[^\n]+\r
Content-Type: multipart/mixed\r
	; \[^\n]+\r
	; \[^\n]+\r
Content-Description: Test Multipart\r
\r
--bndry\r

Content-ID: \[^\n]+\r
Content-Type: text/plain\r
\r
jack and jill\r
--bndry\r

Content-ID: \[^\n]+\r
Content-Type: text/plain\r
\r
james\r
--bndry--\r
" $msg] [regexp boundary=bndry $msg] [regexp myparam=foo $msg]
}} {1 1 1}



test mime-3.1 {Parse a MIME message} {cleanly {
    set msg {MIME-Version: 1.0
Content-Type: Text/plain

I'm the message.}
    set tok [mime::initialize -string $msg]
    mime::body $tok
}} {I'm the message.}


test mime-3.2 {Parse a multi-part MIME message} {cleanly {
    set msg {MIME-Version: 1.0
Content-Type: Multipart/foo; boundary="bar"








>
>








<



>













>






>




>
|

>
|
>
>
|
>
>







>





>
>
>
>
>
>



|



|


<
<
|
>
|


|
<

<
|
|
|
|
|

|
|
|
|
|
|
<









|
<
<
|
>
|

|
|



>
|




>
|




<
<
|









|
<
|
>
|

|
|



>
|




>
|




<
<
>








|







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
    use md5/md5x.tcl md5

    use namespacex/namespacex.tcl namespacex
}
testing {
    useLocal mime.tcl mime
}

package require {chan base}

# -------------------------------------------------------------------------

namespace import mime::*

# -------------------------------------------------------------------------



proc channamescmp names {
    expr {[llength $names] == [llength [chan names]]}
}


proc cleanly script {
    set ns [info cmdcount]
    namespace eval $ns {
	namespace path [namespace parent]
    }
    catch {namespace eval $ns $script} cres copts
    foreach name [info vars ${ns}::*] {
	catch [list mime finalize $name]
    }
    namespace delete $ns
    return -options $copts $cres
}


proc setup1 {} {
    uplevel 1 {
	set channames [chan names]
    }
}


proc with.chan {name args} {
    set body [lindex $args end]
    set args [lrange $args 0 end-1]
    set chan chan_[info cmdcount]
    ::tcllib::chan::base .new $chan [open $name]
    uplevel 1 [list set tok [::mime::initialize {*}$args -chan $chan]]
    try {
	uplevel 1 $body
    } finally {
	rename $chan {}
    }
}


proc with.file {name args} {
    set body [lindex $args end]
    set args [lrange $args 0 end-1]
    uplevel 1 [list set tok [::mime::initialize {*}$args -file $name]]
    uplevel 1 $body
}


proc main {} {
variable encoded
variable name
variable n

set message1 {MIME-Version: 1.0
Content-Type: Text/plain

I'm the message.}

test mime-1.1 {initialize with no args} {cleanly {
    catch {initialize} res
    subst $res
}} {{specify exactly one of} {-chan -file -parts -string}}


test mime-2.1 {Generate a MIME message} {cleanly {
   
    set tok [initialize -canonical Text/plain -string {jack and jill}]
    set msg [mime::serialize $tok]


}} "MIME-Version: 1.0\r
Message-ID: <ac7319c5a872e80af7fe7fb7efa5fd7ac7356ec74eb4410d23287b6cf7fa0129@|>\r
Content-ID: <8e84af0326e6170dfb2720eeb49b23337250b571c563247605c9ec6910772d2c@|>\r
Content-Type: text/plain\r
\r
jack and jill"



test mime-2.1.1 {Generate a MIME message} {cleanly {
    setup1
    with.chan [makeFile {jack and jill} input.txt] -canonical Text/plain {
	set msg [[mime::body raw $tok] read]
	mime::finalize $tok

	# The generated message is predictable except for the Content-ID
	lappend res $msg
	lappend res [channamescmp $channames]
	return $res
    }
}} [list "jack and jill\n" 1]



test mime-2.2 {Generate a multi-part MIME message} {cleanly {
    set tok1 [initialize -canonical Text/plain -string {jack and jill}]
    set tok2 [initialize -canonical Text/plain -string james]
    set bigTok [mime::initialize -canonical Multipart/MyType \
	    -params [list MyParam foo boundary bndry] \
	    -headers [list Content-Description {Test Multipart}] \
	    -parts [list $tok1 $tok2]]
    mime::serialize $bigTok


}} "MIME-Version: 1.0\r
Message-ID: <0b1ce38bc23a7af000d136b6227d7e47af437c850c83145d8ae807bb4ab4d748@|>\r
Content-ID: <b534a48db81537371fd048c0fc6da3047924c773b8f1b1691df58d032ed717c1@|>\r
Content-Type: multipart/mytype\r
	; myparam=foo\r
	; boundary=bndry\r
Content-Description: Test Multipart\r
\r
--bndry\r
Message-ID: <ac7319c5a872e80af7fe7fb7efa5fd7ac7356ec74eb4410d23287b6cf7fa0129@|>\r
Content-ID: <8e84af0326e6170dfb2720eeb49b23337250b571c563247605c9ec6910772d2c@|>\r
Content-Type: text/plain\r
\r
jack and jill\r
--bndry\r
Message-ID: <ab7737bc7bbff0d4096ba7e130fd69e77ea5a1e1d7618d17e15f4914bae8600f@|>\r
Content-ID: <119c9ae6f9ca741bd0a76f87fba0b22cab5413187afb2906aa2875c38e213603@|>\r
Content-Type: text/plain\r
\r
james\r
--bndry--\r


"


test mime-2.3 {Generate a multi-part MIME message} {cleanly {
    set tok1 [initialize -canonical Text/plain -string {jack and jill}]
    set tok2 [initialize -canonical Text/plain -string james]
    set bigTok [mime::initialize \
	    -params [list MyParam foo boundary bndry] \
	    -headers [list Content-Description {Test Multipart}] \
	    -parts [list $tok1 $tok2]]
    mime::serialize $bigTok

}} "MIME-Version: 1.0\r
Message-ID: <6fd7e9b06fe3961dbc67d3bcc058451c3674403801ed18714d11aa200aed02a2@|>\r
Content-ID: <b534a48db81537371fd048c0fc6da3047924c773b8f1b1691df58d032ed717c1@|>\r
Content-Type: multipart/mixed\r
	; myparam=foo\r
	; boundary=bndry\r
Content-Description: Test Multipart\r
\r
--bndry\r
Message-ID: <ac7319c5a872e80af7fe7fb7efa5fd7ac7356ec74eb4410d23287b6cf7fa0129@|>\r
Content-ID: <8e84af0326e6170dfb2720eeb49b23337250b571c563247605c9ec6910772d2c@|>\r
Content-Type: text/plain\r
\r
jack and jill\r
--bndry\r
Message-ID: <ab7737bc7bbff0d4096ba7e130fd69e77ea5a1e1d7618d17e15f4914bae8600f@|>\r
Content-ID: <119c9ae6f9ca741bd0a76f87fba0b22cab5413187afb2906aa2875c38e213603@|>\r
Content-Type: text/plain\r
\r
james\r
--bndry--\r


"


test mime-3.1 {Parse a MIME message} {cleanly {
    set msg {MIME-Version: 1.0
Content-Type: Text/plain

I'm the message.}
    set tok [mime::initialize -string $msg]
    [mime::body raw $tok] read
}} {I'm the message.}


test mime-3.2 {Parse a multi-part MIME message} {cleanly {
    set msg {MIME-Version: 1.0
Content-Type: Multipart/foo; boundary="bar"

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
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
}

    set tok [mime::initialize -string $msg]
    set partToks [mime::property $tok parts]

    set res {} 
    foreach childTok $partToks {
	lappend res [mime::body $childTok]
    }
    set res
}} {part1 part2 part3}


test mime-3.3 {Try to parse a totally invalid message} {
	set token [mime::initialize -string blah]
    catch {mime::header get $token} err0
    set err0
} {{improper line in header} blah}


test mime-3.4 {Try to parse a MIME message with an invalid version} {cleanly {
    set msg1 {MIME-Version: 2.0
Content-Type: text/plain

msg1}

    set tok [mime::initialize -string $msg1]
    catch {mime::body $tok} err1
    catch {mime::serialize $tok} err1a
    list $err1 $err1a
}} "msg1 {MIME-Version: 2.0\r


Content-Type: text/plain\r
\r
msg1}"


test mime-3.5 {Try to parse a MIME message with no newline between headers and data} {cleanly {
    set msg2 {MIME-Version: 1.0
Content-Type: foobar
data without newline}

    set token [mime::initialize -string $msg2]
    catch {mime::header get $token} err2
    set err2
}} {expecting type/subtype found foobar}


test mime-3.6 {Try to parse a MIME message with no MIME version and generate a new message from it} {cleanly {

    # No MIME version
    set msg3 {Content-Type: text/plain

foo}

    set tok [mime::initialize -string $msg3]
    catch {mime::body $tok} err3
    catch {mime::serialize $tok} err3a
    list $err3 $err3a
}} "foo {MIME-Version: 1.0\r


Content-Type: text/plain\r
\r
foo}"


foreach name {file chan} {
    test mime-3.7.$name {Test mime with a bad email [SF Bug 631314 ]} {cleanly {
	with.$name $tcltest::testsDirectory/badmail1.txt {
	    set res {}

	    set ctok [lindex [mime::property $tok parts] 0]
	    lappend res [dictsort [mime::property $tok]]
	    lappend res [dictsort [mime::property $ctok]]
	    mime::finalize $tok
	    string map [list $ctok CHILD] $res
	}
    }} {{content multipart/mixed encoding {} params {boundary ----------CSFNU9QKPGZL79} parts CHILD size 0} {content application/octet-stream encoding {} params {} size 0}}













    test mime-3.8 {Test mime with another bad email [SF Bug 631314 ]} {cleanly {
	with.$name $tcltest::testsDirectory/badmail2.txt {
	    set res {}
	    set ctok [lindex [mime::property $tok parts] 0]
	    lappend res [dictsort [mime::property $tok]]
	    lappend res [dictsort [mime::property $ctok]]
	    mime::finalize $tok
	    string map [list $ctok CHILD] $res
	}
    }} {{content multipart/related encoding {} params {boundary ----=_NextPart_000_0000_2CBA2CBA.150C56D2} parts CHILD size 659} {content application/octet-stream encoding base64 params {} size 659}}
}




test mime-3.9 {Parse a MIME message with a charset encoded body and use [body] -decode to get it back} {cleanly {
    set msg {MIME-Version: 1.0
Content-Type: text/plain; charset=ISO-8859-1

Fran\xE7ois
}
    set tok [mime::initialize -string $msg]
    mime::body $tok -decode
}} {Fran\xE7ois
}


test mime-3.10 {Parse a MIME message with a charset encoded body and use [body] -decode to get it back (example from encoding man page)} {cleanly {
    set msg {MIME-Version: 1.0
Content-Type: text/plain; charset=EUC-JP
Content-Transfer-Encoding: quoted-printable

=A4=CF}
    set tok [mime::initialize -string $msg]
    mime::body $tok -decode
}} \u306F


test mime-3.11 {Parse a MIME message without a charset encoded body and use [body] -decode to get it back} {cleanly {
    set msg {MIME-Version: 1.0
Content-Type: text/plain
Content-Transfer-Encoding: quoted-printable

A plain text message.}
    set tok [mime::initialize -string $msg]
    mime::body $tok -decode
}} {A plain text message.}


test mime-3.12 {Parse a MIME message with a charset encoded body in an unrecognised charset and use [body] -decode to attempt to get it back} {cleanly {
    set msg {MIME-Version: 1.0
Content-Type: text/plain; charset=SCRIBBLE
Content-Transfer-Encoding: quoted-printable

This is a message in the scribble charset that tcl does not recognise.}
    set tok [mime::initialize -string $msg]
    catch {mime::body $tok -decode} errmsg
    set errmsg
}} {{-decode cannot reversemap charset} SCRIBBLE}


test mime-3.13 {Parse a MIME message with a charset encoded body in an unrecognised charset but don't use -decode so we get it back raw} {cleanly {
    set msg {MIME-Version: 1.0
Content-Type: text/plain; charset=SCRIBBLE
Content-Transfer-Encoding: quoted-printable

This is a message in the scribble charset that tcl does not recognise.}
    set tok [mime::initialize -string $msg]
    mime::body $tok
}} {This is a message in the scribble charset that tcl does not recognise.}


test mime-4.1 {Test qp_encode with a > 76 character string containing special chars.} {cleanly {
    set str1 "foo!\"\t barbaz \$ ` \{ # jack and jill went up a hill to fetch a pail of water. Jack fell down and said !\"\#\$@\[\\\]^`\{\|\}\~  \nJill said, \"Oh my\""
    mime::qp_encode $str1
}} "foo=21=22\t barbaz =24 =60 =7B =23 jack and jill went up a hill to fetch a=\n pail of water. Jack fell down and said =21=22=23=24=40=5B=5C=5D=5E=60=7B=\n=7C=7D=7E =20\nJill said, =22Oh my=22"


test mime-4.2 {Check that encode/decode yields original string} {cleanly {
    set str1 "foo!\"\t barbaz \$ ` \{ # jack and jill went up a hill to fetch a pail of water. Jack fell down and said !\"\#\$@\[\\\]^`\{\|\}\~  \nJill said, \"Oh my\"  "
    set enc [mime::qp_encode $str1]
    set dec [mime::qp_decode $enc]
    string equal $dec $str1
}} 1


test mime-4.3 {mime::decode data that might come from an MUA} {cleanly {
    set enc "I'm the =22 message =\nwith some new lines=  \n but with some extra space, too.   "
    mime::qp_decode $enc
}} "I'm the \" message with some new lines but with some extra space, too."


test mime-4.4 {Test qp_encode with non-US_ASCCI characters.} {cleanly {
    set str1 "Test de caractères accentués : â î é ç et quelques contrôles \"\[|\]()\""
    mime::qp_encode $str1
}} "Test de caract=E8res accentu=E9s : =E2 =EE =E9 =E7 et quelques contr=F4le=\ns =22=5B=7C=5D()=22"


test mime-4.5 {Test qp_encode with softbreak} {cleanly {
    set str1 [string repeat abc 40]
    mime::qp_encode $str1
}} "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca=
bcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc"


test mime-4.6 {Test qp_encode with softbreak} {cleanly {
    set str1 [string repeat abc 40]
    mime::qp_encode $str1 0 1
}} [string repeat abc 40]


test mime-4.7 {Test qp_encode/decode in encoded_word mode} {cleanly {
    set enc [mime::qp_encode {jack and jill went up the hill} 1]
    mime::qp_decode $enc 1
}} {jack and jill went up the hill}


test mime-4.8 {Test qp_encode in encoded_word mode with equal signs} {cleanly {
    mime::qp_encode 1and1=2 1
}} 1and1=3D2

test mime-4.9 {Test qp_encode in encoded_word mode with tabs and spaces} {cleanly {
    mime::qp_encode "1 and 1 =\t2" 1
}} 1_and_1_=3D=092


test mime-4.10 {Test qp_encode in encoded_word mode with underscores} {cleanly {
    mime::qp_encode 2003_06_30 1
}} 2003=5F06=5F30


test mime-4.11 {Test qp_encode in encoded_word mode with underscores and spaces} {cleanly {
    mime::qp_encode {2003_06_30 is 30 June 2003} 1
}} 2003=5F06=5F30_is_30_June_2003


test mime-4.12 {Test qp_encode in encoded_word mode with question marks} {cleanly {
    mime::qp_encode {How long is a piece of string ?} 1
}} How_long_is_a_piece_of_string_=3F


test mime-4.13 {Test qp_encode in no_softbreak mode} {cleanly {
    mime::qp_encode {This is a very long string into which we do not want inserted softbreaks as we want one very long line returned even though that's probably not how we whould be doing it (see RFC2047) but we don't want to break backward compatibility} 0 1
}} {This is a very long string into which we do not want inserted softbreaks as we want one very long line returned even though that's probably not how we whould be doing it (see RFC2047) but we don't want to break backward compatibility}
 


test mime-5.1 {Test word_encode with quoted-printable method} {cleanly {
    mime::word_encode iso8859-1 quoted-printable {Test de contrôle effectué}
}} =?ISO-8859-1?Q?Test_de_contr=F4le_effectu=E9?=







|


|
















|



>
>

















<




<

|



>
>









>






|
|
>
>
>
>
>
>
>
>
>
>
>
>
|
|







|



<
<
|






|




|






|



|






|



|






|
<
<
|
|
<
<
<
<
|
|
|
<
<


|

|





|
|






|



|

|



|

|




|

|



|
|
|



|
|


|
|



|
|



|
|



|
|



|
|







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
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
}

    set tok [mime::initialize -string $msg]
    set partToks [mime::property $tok parts]

    set res {} 
    foreach childTok $partToks {
	lappend res [[mime::body raw $childTok] read]
    }
    set res
}} [list part1 part2 part3]


test mime-3.3 {Try to parse a totally invalid message} {
	set token [mime::initialize -string blah]
    catch {mime::header get $token} err0
    set err0
} {{improper line in header} blah}


test mime-3.4 {Try to parse a MIME message with an invalid version} {cleanly {
    set msg1 {MIME-Version: 2.0
Content-Type: text/plain

msg1}

    set tok [mime::initialize -string $msg1]
    catch {[mime::body raw $tok] read} err1
    catch {mime::serialize $tok} err1a
    list $err1 $err1a
}} "msg1 {MIME-Version: 2.0\r
Message-ID: <d956986793d51d614044c01a7e7650665330a4a170d071aff1de6dceda8c8b0d@|>\r
Content-ID: <289e5175e02c788c2d442cfe81d6be0533d8c13e253ef763fda45d37accfe4d4@|>\r
Content-Type: text/plain\r
\r
msg1}"


test mime-3.5 {Try to parse a MIME message with no newline between headers and data} {cleanly {
    set msg2 {MIME-Version: 1.0
Content-Type: foobar
data without newline}

    set token [mime::initialize -string $msg2]
    catch {mime::header get $token} err2
    set err2
}} {expecting type/subtype found foobar}


test mime-3.6 {Try to parse a MIME message with no MIME version and generate a new message from it} {cleanly {

    # No MIME version
    set msg3 {Content-Type: text/plain

foo}

    set tok [mime::initialize -string $msg3]
    catch {[mime::body raw $tok] read} err3
    catch {mime::serialize $tok} err3a
    list $err3 $err3a
}} "foo {MIME-Version: 1.0\r
Message-ID: <fb8bfc091f5ff55264834b7ea21278fbcb7bf875b20ddeae2f5e4eb662de2129@|>\r
Content-ID: <2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae@|>\r
Content-Type: text/plain\r
\r
foo}"


foreach name {file chan} {
    test mime-3.7.$name {Test mime with a bad email [SF Bug 631314 ]} {cleanly {
	with.$name $tcltest::testsDirectory/badmail1.txt {
	    set res {}
	    lappend res [llength [mime::property $tok parts]]
	    set ctok [lindex [mime::property $tok parts] 0]
	    lappend res [dictsort [mime::property $tok]]
	    lappend res [dictsort [mime::property $ctok]]
	    mime::finalize $tok
	    string map [list $ctok CHILD] $res
	}
    }} {1 {content multipart/mixed encoding {} params {boundary ----------CSFNU9QKPGZL79} parts CHILD size 0} {content application/octet-stream encoding {} params {} size 0}}
}

foreach name {file chan} {

    test mime-3.8.1.$name {Test mime with another bad email [SF Bug 631314 ]} -body {cleanly {
	with.$name $tcltest::testsDirectory/badmail2.txt {
	    set ctok [lindex [mime::property $tok parts] 0]
	}
    }} -returnCodes 1 -result {end-of-string encountered while parsing multipart/form-data}
}

foreach name {file chan} {

    test mime-3.8.2.$name {Test mime with another bad email [SF Bug 631314 ]} {cleanly {
	with.$name $tcltest::testsDirectory/badmail2.txt -relax finalboundary {
	    set res {}
	    set ctok [lindex [mime::property $tok parts] 0]
	    lappend res [dictsort [mime::property $tok]]
	    lappend res [dictsort [mime::property $ctok]]
	    mime::finalize $tok
	    string map [list $ctok CHILD] $res
	}
    }} {{content multipart/related encoding {} params {boundary ----=_NextPart_000_0000_2CBA2CBA.150C56D2} parts CHILD size 879} {content text/html encoding base64 params {} size 879}}
}




test mime-3.9 {Parse a MIME message with a charset encoded body and use [body decoded] to get it back} {cleanly {
    set msg {MIME-Version: 1.0
Content-Type: text/plain; charset=ISO-8859-1

Fran\xE7ois
}
    set tok [mime::initialize -string $msg]
    [mime::body decoded $tok] read
}} {Fran\xE7ois
}


test mime-3.10 {Parse a MIME message with a charset encoded body and use [body decoded] to get it back (example from encoding man page)} {cleanly {
    set msg {MIME-Version: 1.0
Content-Type: text/plain; charset=EUC-JP
Content-Transfer-Encoding: quoted-printable

=A4=CF}
    set tok [mime::initialize -string $msg]
    [mime::body decoded $tok] read
}} \u306F


test mime-3.11 {Parse a MIME message without a charset encoded body and use [body decoded] to get it back} {cleanly {
    set msg {MIME-Version: 1.0
Content-Type: text/plain
Content-Transfer-Encoding: quoted-printable

A plain text message.}
    set tok [mime::initialize -string $msg]
    [mime::body decoded $tok] read
}} {A plain text message.}


test mime-3.12 {Parse a MIME message with a charset encoded body in an unrecognised charset and use [body decoded] to attempt to get it back} {cleanly {
    set msg {MIME-Version: 1.0
Content-Type: text/plain; charset=SCRIBBLE
Content-Transfer-Encoding: quoted-printable

This is a message in the scribble charset that tcl does not recognise.}
    set tok [mime::initialize -string $msg]
    lappend res [mime::header get $tok content-type]


    lappend res [[mime::body decoded $tok] configure -encoding]
    catch {[mime::body decoded $tok] read} errmsg




    lappend res $errmsg
}} {{text/plain {charset SCRIBBLE}} binary {This is a message in the scribble charset that tcl does not recognise.}}





test mime-4.1 {Test qp::encode with a > 76 character string containing special chars.} {cleanly {
    set str1 "foo!\"\t barbaz \$ ` \{ # jack and jill went up a hill to fetch a pail of water. Jack fell down and said !\"\#\$@\[\\\]^`\{\|\}\~  \nJill said, \"Oh my\""
    mime::qp::encode $str1
}} "foo=21=22\t barbaz =24 =60 =7B =23 jack and jill went up a hill to fetch a=\n pail of water. Jack fell down and said =21=22=23=24=40=5B=5C=5D=5E=60=7B=\n=7C=7D=7E =20\nJill said, =22Oh my=22"


test mime-4.2 {Check that encode/decode yields original string} {cleanly {
    set str1 "foo!\"\t barbaz \$ ` \{ # jack and jill went up a hill to fetch a pail of water. Jack fell down and said !\"\#\$@\[\\\]^`\{\|\}\~  \nJill said, \"Oh my\"  "
    set enc [mime::qp::encode $str1]
    set dec [mime::qp::decode $enc]
    string equal $dec $str1
}} 1


test mime-4.3 {mime::decode data that might come from an MUA} {cleanly {
    set enc "I'm the =22 message =\nwith some new lines=  \n but with some extra space, too.   "
    mime::qp::decode $enc
}} "I'm the \" message with some new lines but with some extra space, too."


test mime-4.4 {Test qp::encode with non-US_ASCCI characters.} {cleanly {
    set str1 "Test de caractères accentués : â î é ç et quelques contrôles \"\[|\]()\""
    mime::qp::encode $str1
}} "Test de caract=E8res accentu=E9s : =E2 =EE =E9 =E7 et quelques contr=F4le=\ns =22=5B=7C=5D()=22"


test mime-4.5 {Test qp::encode with softbreak} {cleanly {
    set str1 [string repeat abc 40]
    mime::qp::encode $str1
}} "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca=
bcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc"


test mime-4.6 {Test qp::encode with softbreak} {cleanly {
    set str1 [string repeat abc 40]
    mime::qp::encode $str1 0 1
}} [string repeat abc 40]


test mime-4.7 {Test qp::encode/decode in encoded_word mode} {cleanly {
    set enc [mime::qp::encode {jack and jill went up the hill} 1]
    mime::qp::decode $enc 1
}} {jack and jill went up the hill}


test mime-4.8 {Test qp::encode in encoded_word mode with equal signs} {cleanly {
    mime::qp::encode 1and1=2 1
}} 1and1=3D2

test mime-4.9 {Test qp::encode in encoded_word mode with tabs and spaces} {cleanly {
    mime::qp::encode "1 and 1 =\t2" 1
}} 1_and_1_=3D=092


test mime-4.10 {Test qp::encode in encoded_word mode with underscores} {cleanly {
    mime::qp::encode 2003_06_30 1
}} 2003=5F06=5F30


test mime-4.11 {Test qp::encode in encoded_word mode with underscores and spaces} {cleanly {
    mime::qp::encode {2003_06_30 is 30 June 2003} 1
}} 2003=5F06=5F30_is_30_June_2003


test mime-4.12 {Test qp::encode in encoded_word mode with question marks} {cleanly {
    mime::qp::encode {How long is a piece of string ?} 1
}} How_long_is_a_piece_of_string_=3F


test mime-4.13 {Test qp::encode in no_softbreak mode} {cleanly {
    mime::qp::encode {This is a very long string into which we do not want inserted softbreaks as we want one very long line returned even though that's probably not how we whould be doing it (see RFC2047) but we don't want to break backward compatibility} 0 1
}} {This is a very long string into which we do not want inserted softbreaks as we want one very long line returned even though that's probably not how we whould be doing it (see RFC2047) but we don't want to break backward compatibility}
 


test mime-5.1 {Test word_encode with quoted-printable method} {cleanly {
    mime::word_encode iso8859-1 quoted-printable {Test de contrôle effectué}
}} =?ISO-8859-1?Q?Test_de_contr=F4le_effectu=E9?=
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

foreach name {file chan} {
    test mime-9.0.$name {Test chunk handling of serialize and helpers} {cleanly {
	set in [makeFile [set data [string repeat [string repeat {123456789 } 10]\n 350]] input.txt]
	set mi [makeFile {} mime.txt]

	with.$name $in -canonical text/plain {
	    set f [open $mi w]
	    fconfigure $f -translation binary
	    mime::serialize $tok -chan $f
	    close $f

	    with.$name $mi {
		set newdata [mime::body $tok]
		set res [string compare $data $newdata]

		removeFile input.txt
		removeFile mime.txt
		unset data newdata tok f in mi
		set res
	    }
	}
    }} 0
}

set ::env(TZ) UTC0







|
|
|
|


|




|







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

foreach name {file chan} {
    test mime-9.0.$name {Test chunk handling of serialize and helpers} {cleanly {
	set in [makeFile [set data [string repeat [string repeat {123456789 } 10]\n 350]] input.txt]
	set mi [makeFile {} mime.txt]

	with.$name $in -canonical text/plain {
	    ::tcllib::chan::base .new chan1 [open $mi w]
	    chan1 configure -translation binary
	    mime::serialize $tok -chan chan1 
	    chan1 close

	    with.$name $mi {
		set newdata [[mime::body raw $tok] read]
		set res [string compare $data $newdata]

		removeFile input.txt
		removeFile mime.txt
		unset data newdata tok in mi
		set res
	    }
	}
    }} 0
}

set ::env(TZ) UTC0
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759


760
761
762
763
764
765
766
767
--------------090305080603000703000106--
} mail_part]
    set token [mime::initialize -file $in]
    set allparts [mime::property $token parts]
    set attachment [lindex $allparts 1]

    set out [makeFile {} mail_att]
    set ofh [open $out w]
    fconfigure $ofh -translation binary
    mime::serialize $attachment -chan $ofh -level 1
    close $ofh

    set data [viewFile $out]
    file delete $in $out
    set data


}} {Content-Type: application/octet-stream
	; name=a0036.dss
Content-Disposition: attachment
	; filename=a0036.dss
Content-Transfer-Encoding: base64

BGRzcwEAAQABAAAAYQAAAAAAAAAAAAAAAAAAACQAAAD+//7/+/8wNzA2MTYwODE1MjQwNzA2
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZ}







|
|
|
|




>
>
|







763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
--------------090305080603000703000106--
} mail_part]
    set token [mime::initialize -file $in]
    set allparts [mime::property $token parts]
    set attachment [lindex $allparts 1]

    set out [makeFile {} mail_att]
    ::tcllib::chan::base .new chan1 [open $out w]
    chan1 configure -translation binary
    mime::serialize $attachment -chan chan1 -level 1
    chan1 close

    set data [viewFile $out]
    file delete $in $out
    set data
}} {Message-ID: <f60c78370648168a30158b8cda876db2f875d1531e86e5594c5a108dcf5209db@|>
Content-ID: <93755e1312eacd488b6170673caa5e7a9a9445ce82ff11c934055bd1f907b229@|>
Content-Type: application/octet-stream
	; name=a0036.dss
Content-Disposition: attachment
	; filename=a0036.dss
Content-Transfer-Encoding: base64

BGRzcwEAAQABAAAAYQAAAAAAAAAAAAAAAAAAACQAAAD+//7/+/8wNzA2MTYwODE1MjQwNzA2
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZ}
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
    set msg "MIME-Version: 1.0
Content-Type: text/plain\r
\r
so plain
"

    set tok [mime::initialize -string $msg]
	mime::body $tok
} "so plain\n"

# -------------------------------------------------------------------------

test mime-14.0 {cleanly {
	hostname argument to parseaddress
}} {







|







815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
    set msg "MIME-Version: 1.0
Content-Type: text/plain\r
\r
so plain
"

    set tok [mime::initialize -string $msg]
    [mime::body raw $tok] read 
} "so plain\n"

# -------------------------------------------------------------------------

test mime-14.0 {cleanly {
	hostname argument to parseaddress
}} {
876
877
878
879
880
881
882
883
884
885
886
887
888
889

890
891
892
893
894
895
896

897
898
899
900
901
902
903
set char [encoding convertfrom utf-8 \xE3\x81\xAF]
test mime-16.1 {cleanly {
}} {
    set res {}
    set mime [mime::initialize -canonical text/plain -string {dawg one}]
    mime::header set $mime Content-Disposition attachment [list param1 $char]
    set msg [mime::serialize $mime]
    regsub {(Content-ID: <).*(>)} $msg {\1\2} msg
    lappend res $msg
    set mime2 [mime::initialize -string $msg]
    lappend res [mime::header get $mime2]
    return $res

} [list "MIME-Version: 1.0\r

Content-ID: <>\r
Content-Type: text/plain\r
Content-Disposition: attachment\r
	; param1*0*=utf-8''%E3%81%AF\r
\r
dawg one" \
[list Content-ID {<> {}} Content-Type {text/plain {}} \

    Content-Disposition [list attachment [list param1 $char]]]

]


# -------------------------------------------------------------------------








<






>
|





|
>







896
897
898
899
900
901
902

903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
set char [encoding convertfrom utf-8 \xE3\x81\xAF]
test mime-16.1 {cleanly {
}} {
    set res {}
    set mime [mime::initialize -canonical text/plain -string {dawg one}]
    mime::header set $mime Content-Disposition attachment [list param1 $char]
    set msg [mime::serialize $mime]

    lappend res $msg
    set mime2 [mime::initialize -string $msg]
    lappend res [mime::header get $mime2]
    return $res

} [list "MIME-Version: 1.0\r
Message-ID: <c7aa6d4b48aa9fcfe18d9c24adf71de96efbaaf2e261eb1de738ef45f453d1a4@|>\r
Content-ID: <086570e97284c5bc5145f32689a5342363b10b64963446293b83930fa8a9fa45@|>\r
Content-Type: text/plain\r
Content-Disposition: attachment\r
	; param1*0*=utf-8''%E3%81%AF\r
\r
dawg one" \
[list Content-ID {<086570e97284c5bc5145f32689a5342363b10b64963446293b83930fa8a9fa45@|> {}} Content-Type {text/plain {}} \
    Message-ID {<c7aa6d4b48aa9fcfe18d9c24adf71de96efbaaf2e261eb1de738ef45f453d1a4@|> {}} \
    Content-Disposition [list attachment [list param1 $char]]]

]


# -------------------------------------------------------------------------

961
962
963
964
965
966
967





















968
969
970
971
972
973
974
975
976
977
978
    Content-Type is not automatically added to a subordinate
} {
    set mime [mime::initialize -string {Content-Disposition: form-data; name="field2"}]
    mime::header get $mime content-disposition 
} {form-data {name field2}}

























testsuiteCleanup
set [namespace current]::done 1
return
}

after 0 [list ::coroutine [info cmdcount]_main [namespace current]::main]
vwait [namespace current]::done
return








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







|



982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
    Content-Type is not automatically added to a subordinate
} {
    set mime [mime::initialize -string {Content-Disposition: form-data; name="field2"}]
    mime::header get $mime content-disposition 
} {form-data {name field2}}


test mime-18.1 {
    non-seekable channel
} {
    set script [list puts -nonewline $message1]
    set chan [open |[list [info nameofexecutable] <<$script]]
    tcllib::chan::base .new chan1 $chan
    set mime [mime::initialize -spec http -chan chan1]
    mime::serialize $mime
} "Content-Type: text/plain\r
\r
I'm the message."

test mime-19.1 {
    -http
} {
    set mime [mime::initialize -spec http -string {}]
    mime::serialize  $mime
} "\r
"




testsuiteCleanup
set [namespace current]::done 1
return
}

after 0 [list ::coroutine [info cmdcount]_main [namespace which main]]
vwait [namespace current]::done
return

Changes to modules/mime/pkgIndex.tcl.

1
2
3
4

if {![package vsatisfies [package provide Tcl] 8.3]} {return}
package ifneeded smtp 1.5 [list source [file join $dir smtp.tcl]]
if {![package vsatisfies [package provide Tcl] 8.5]} {return}
package ifneeded mime 1.7 [list source [file join $dir mime.tcl]]





>
1
2
3
4
5
if {![package vsatisfies [package provide Tcl] 8.3]} {return}
package ifneeded smtp 1.5 [list source [file join $dir smtp.tcl]]
if {![package vsatisfies [package provide Tcl] 8.5]} {return}
package ifneeded mime 1.7 [list source [file join $dir mime.tcl]]
package ifneeded {mime qp} 1.7 [list source [file join $dir qp.tcl]]

Added modules/mime/qp.tcl.









































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#! /usr/bin/env tclsh

# ::mime::qp::encode --
#
#    Tcl version of quote-printable encode
#
# Arguments:
#    string        The string to quote.
#       encoded_word  Boolean value to determine whether or not encoded words
#                     (RFC 2047) should be handled or not. (optional)
#
# Results:
#    The properly quoted string is returned.


namespace eval ::mime::qp {}

proc ::mime::qp::encode {string {encoded_word 0} {no_softbreak 0}} {
    # 8.1+ improved string manipulation routines used.
    # Replace outlying characters, characters that would normally
    # be munged by EBCDIC gateways, and special Tcl characters "[\]{}
    # with =xx sequence

    if {$encoded_word} {
        # Special processing for encoded words (RFC 2047)
        set regexp {[\x00-\x08\x0B-\x1E\x21-\x24\x3D\x40\x5B-\x5E\x60\x7B-\xFF\x09\x5F\x3F]}
	lappend mapChars { } _
    } else {
        set regexp {[\x00-\x08\x0B-\x1E\x21-\x24\x3D\x40\x5B-\x5E\x60\x7B-\xFF]}
    }
    regsub -all -- $regexp $string {[format =%02X [scan "\\&" %c]]} string

    # Replace the format commands with their result

    set string [subst -novariables $string]

    # soft/hard newlines and other
    # Funky cases for SMTP compatibility
    lappend mapChars " \n" =20\n \t\n =09\n \n\.\n =2E\n "\nFrom " "\n=46rom "

    set string [string map $mapChars $string]

    # Break long lines - ugh

    # Implementation of FR #503336
    if {$no_softbreak} {
        set result $string
    } else {
        set result {}
        foreach line [split $string \n] {
            while {[string length $line] > 72} {
                set chunk [string range $line 0 72]
                if {[regexp -- (=|=.)$ $chunk dummy end]} {

                    # Don't break in the middle of a code

                    set len [expr {72 - [string length $end]}]
                    set chunk [string range $line 0 $len]
                    incr len
                    set line [string range $line $len end]
                } else {
                    set line [string range $line 73 end]
                }
                append result $chunk=\n
            }
            append result $line\n
        }

        # Trim off last \n, since the above code has the side-effect
        # of adding an extra \n to the encoded string and return the
        # result.
        set result [string range $result 0 end-1]
    }

    # If the string ends in space or tab, replace with =xx

    set lastChar [string index $result end]
    if {$lastChar eq { }} {
        set result [string replace $result end end =20]
    } elseif {$lastChar eq "\t"} {
        set result [string replace $result end end =09]
    }

    return $result
}


# ::mime::qp_decode --
#
#    Tcl version of quote-printable decode
#
# Arguments:
#    string        The quoted-printable string to decode.
#    encoded_word  Boolean value to determine whether or not encoded words
#                     (RFC 2047) should be handled or not. (optional)
#
# Results:
#    The decoded string is returned.

proc ::mime::qp::decode {string {encoded_word 0}} {
    # 8.1+ improved string manipulation routines used.
    # Special processing for encoded words (RFC 2047)

    if {$encoded_word} {
        # _ == \x20, even if SPACE occupies a different code position
        set string [string map [list _ \u0020] $string]
    }

    # smash the white-space at the ends of lines since that must've been
    # generated by an MUA.

    regsub -all -- {[ \t]+\n} $string \n string
    set string [string trimright $string " \t"]

    # Protect the backslash for later subst and
    # smash soft newlines, has to occur after white-space smash
    # and any encoded word modification.

    #TODO: codepath not tested
    set string [string map [list \\ {\\} =\n {}] $string]

    # Decode specials

    regsub -all -nocase {=([a-f0-9][a-f0-9])} $string {\\u00\1} string

    # process \u unicode mapped chars

    return [subst -novariables -nocommands $string]
}


package provide {mime qp} 1.7

Changes to modules/mime/smtp.tcl.

304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
                lappend header($senderL) $aprops(address)
            }
        }
    }

    # We're done parsing the arguments.

    if {$recipients != ""} {
        set who -recipients
    } elseif {![info exists header($toL)]} {
        error "need -header \"$toM ...\""
    } else {
        set recipients [join $header($toL) ,]
	# Add Cc values to recipients list
	set who $toM







|







304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
                lappend header($senderL) $aprops(address)
            }
        }
    }

    # We're done parsing the arguments.

    if {$recipients ne {}} {
        set who -recipients
    } elseif {![info exists header($toL)]} {
        error "need -header \"$toM ...\""
    } else {
        set recipients [join $header($toL) ,]
	# Add Cc values to recipients list
	set who $toM
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
    # If there's no date header, get the date from the mime message.  Same for
    # the message-id.

    if {([lsearch -exact $lowerL $dateL] < 0) \
            && ([catch {::mime::header get $part $dateL}])} {
        lappend lowerL $dateL
        lappend mixedL $dateM
        lappend header($dateL) [::mime::parsedatetime -now proper]
    }

    if {([lsearch -exact $lowerL ${message-idL}] < 0) \
            && ([catch {::mime::header get $part ${message-idL}}])} {
        lappend lowerL ${message-idL}
        lappend mixedL ${message-idM}
        lappend header(${message-idL}) [::mime::uniqueID]

    }

    # Get all the headers from the MIME object and save them so that they can
    # later be restored.
    set savedH [::mime::header get $part]
    puts [list crackle $savedH]

    # Take all the headers defined earlier and add them to the MIME message.
    foreach lower $lowerL mixed $mixedL {
        foreach value $header($lower) {
            ::mime::header set $part $mixed $value -mode append
        }
    }







|













<







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
    # If there's no date header, get the date from the mime message.  Same for
    # the message-id.

    if {([lsearch -exact $lowerL $dateL] < 0) \
            && ([catch {::mime::header get $part $dateL}])} {
        lappend lowerL $dateL
        lappend mixedL $dateM
        lappend header($dateL) [::mime::datetime -now proper]
    }

    if {([lsearch -exact $lowerL ${message-idL}] < 0) \
            && ([catch {::mime::header get $part ${message-idL}}])} {
        lappend lowerL ${message-idL}
        lappend mixedL ${message-idM}
        lappend header(${message-idL}) [::mime::uniqueID]

    }

    # Get all the headers from the MIME object and save them so that they can
    # later be restored.
    set savedH [::mime::header get $part]


    # Take all the headers defined earlier and add them to the MIME message.
    foreach lower $lowerL mixed $mixedL {
        foreach value $header($lower) {
            ::mime::header set $part $mixed $value -mode append
        }
    }
424
425
426
427
428
429
430

431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
    # server.
    set token [initialize -debug $debugP -client $client \
		                -maxsecs $maxsecs -usetls $tlsP \
                                -multiple $bccP -queue $queueP \
                                -servers $servers -ports $ports \
                                -tlspolicy $tlspolicy -tlsimport $tlsimport \
                                -username $username -password $password]


    if {![string match "::smtp::*" $token]} {
	# An error occurred and $token contains the error info
	array set respArr $token
	return -code error $respArr(diagnostic)
    }

    set code [catch { sendmessageaux $token $part \
                                           $sender $vrecipients $aloP } \
                    result]
    set ecode $errorCode
    set einfo $errorInfo

    # Send the message to bcc recipients as a MIME attachment.

    if {($code == 0) && ($bccP)} {
        set inner [::mime::initialize -canonical message/rfc822 \







>







|
|
<







423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439

440
441
442
443
444
445
446
    # server.
    set token [initialize -debug $debugP -client $client \
		                -maxsecs $maxsecs -usetls $tlsP \
                                -multiple $bccP -queue $queueP \
                                -servers $servers -ports $ports \
                                -tlspolicy $tlspolicy -tlsimport $tlsimport \
                                -username $username -password $password]


    if {![string match "::smtp::*" $token]} {
	# An error occurred and $token contains the error info
	array set respArr $token
	return -code error $respArr(diagnostic)
    }

    set code [catch {
	sendmessageaux $token $part $sender $vrecipients $aloP } result]

    set ecode $errorCode
    set einfo $errorInfo

    # Send the message to bcc recipients as a MIME attachment.

    if {($code == 0) && ($bccP)} {
        set inner [::mime::initialize -canonical message/rfc822 \
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
        }

        set outer [::mime::initialize \
	    -canonical multipart/digest \
	    -headers [list \
		From [list $originator {}] \
		Bcc 
		Date [::mime::parsedatetime -now proper] \
		Subject $subject \
		Message-ID [::mime::uniqueID] \
		Content-Description {Blind Carbon Copy} \
	     -parts [list $inner]]


        set code [catch { sendmessageaux $token $outer \







|







454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
        }

        set outer [::mime::initialize \
	    -canonical multipart/digest \
	    -headers [list \
		From [list $originator {}] \
		Bcc 
		Date [::mime::datetime -now proper] \
		Subject $subject \
		Message-ID [::mime::uniqueID] \
		Content-Description {Blind Carbon Copy} \
	     -parts [list $inner]]


        set code [catch { sendmessageaux $token $outer \
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
    }

    # Destroy SMTP token 'cause we're done with it.
    
    catch { finalize $token -close $status } copts cres

    # Restore provided MIME object to original state (without the SMTP headers).
    
    foreach key [::mime::header get $part -names] {
        mime::header set $part $key "" -mode delete
    }
    foreach {key value} $savedH {
	::mime::header set $part $key {*}$value -mode append
    }

    retuern -options $copts $cres
}

# ::smtp::sendmessageaux --
#
#	Sends a mime object (containing a message) to some recipients using an
#       existing SMTP token.
#







|
|






|







502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
    }

    # Destroy SMTP token 'cause we're done with it.
    
    catch { finalize $token -close $status } copts cres

    # Restore provided MIME object to original state (without the SMTP headers).
   
    foreach {key val} [::mime::header get $part] {
        mime::header set $part $key "" -mode delete
    }
    foreach {key value} $savedH {
	::mime::header set $part $key {*}$value -mode append
    }

    return -options $copts $cres
}

# ::smtp::sendmessageaux --
#
#	Sends a mime object (containing a message) to some recipients using an
#       existing SMTP token.
#
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006

    set from "$mode FROM:<$originator>"

    # RFC 1870 -  SMTP Service Extension for Message Size Declaration
    if {[info exists state(esmtp)] 
        && [lsearch -glob $state(esmtp) "SIZE*"] != -1} {
        catch {
            set size [string length [mime::buildmessage $part]]
            append from " SIZE=$size"
        }
    }

    array set response [set result [talk $token 600 $from]]

    if {$response(code) == 250} {







|







991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005

    set from "$mode FROM:<$originator>"

    # RFC 1870 -  SMTP Service Extension for Message Size Declaration
    if {[info exists state(esmtp)] 
        && [lsearch -glob $state(esmtp) "SIZE*"] != -1} {
        catch {
            set size [string length [mime::serialize $part]]
            append from " SIZE=$size"
        }
    }

    array set response [set result [talk $token 600 $from]]

    if {$response(code) == 250} {
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
    # replace all '.'s that start their own line with '..'s, and
    # then write the mime body out to the filehandle. Do not forget to
    # deal with bare LF's here too (SF bug #499242).

    if {$trf} {
        set code [catch { ::mime::copymessage $part $state(sd) } result]
    } else {
        set code [catch { ::mime::buildmessage $part } result]
        if {$code == 0} {
	    # Detect and transform bare LF's into proper CR/LF
	    # sequences.

	    while {[regsub -all -- {([^\r])\n} $result "\\1\r\n" result]} {}
            regsub -all -- {\n\.}      $result "\n.."   result








|







1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
    # replace all '.'s that start their own line with '..'s, and
    # then write the mime body out to the filehandle. Do not forget to
    # deal with bare LF's here too (SF bug #499242).

    if {$trf} {
        set code [catch { ::mime::copymessage $part $state(sd) } result]
    } else {
        set code [catch { ::mime::serialize $part } result]
        if {$code == 0} {
	    # Detect and transform bare LF's into proper CR/LF
	    # sequences.

	    while {[regsub -all -- {([^\r])\n} $result "\\1\r\n" result]} {}
            regsub -all -- {\n\.}      $result "\n.."   result

Added modules/mime/smtp.test.















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#! /usr/bin/env tclsh

# copyright 2018 Poor Yorick

source [file join \
	[file dirname [file dirname [file dirname [
	    file normalize [info script]/...]]]]/devtools/testutilities.tcl]

testsNeedTcl     8.5
testsNeedTcltest 1.0-

testing {
    useLocal smtp.tcl smtp
}

package require nettool
package require smtpd

variable port [nettool::allocate_port 1025]
smtpd::start localhost $port

proc accept token {
    variable result
    set headers [::mime::header get $token]
    lappend result [lsort [dict keys $headers]]
    lappend result [::mime::header get $token From]
    ::mime::finalize $token
    return
}


proc main {} {
    variable done
    variable result
    test smtp-1.1 {} -body {
	variable port
	smtpd::configure -deliverMIME [namespace which accept]
	set msg [mime::initialize -canonical text/plain \
	    -string {a door is ajar}]
	smtp::sendmessage $msg -ports $port -originator Slawkenbergius -recipients {[email protected]}
	return $result
    } -cleanup {
	unset result
    } -result [list \
	{Bcc Content-ID Content-Type Date From Message-ID Received Return-Path} {Slawkenbergius {}}
    ]

    testsuiteCleanup
    set done 1
    return
}

after 0 [list coroutine [info cmdcount]_main [namespace which main]]
vwait [namespace current]::done

Changes to modules/namespacex/namespacex.tcl.

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# # ## ### ##### ######## ############# ######################
## Requisites

package require Tcl 8.5  ; # namespace ensembles, {*}

namespace eval ::namespacex {
    namespace export add hook info normalize strip state
    namespace ensemble create

    namespace eval hook {
	namespace export add proc on next
	namespace ensemble create

	# add - hook a command prefix into the chain of unknown handlers for a







|







11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# # ## ### ##### ######## ############# ######################
## Requisites

package require Tcl 8.5  ; # namespace ensembles, {*}

namespace eval ::namespacex {
    namespace export add hook import info normalize strip state
    namespace ensemble create

    namespace eval hook {
	namespace export add proc on next
	namespace ensemble create

	# add - hook a command prefix into the chain of unknown handlers for a
179
180
181
182
183
184
185

























186
187
188
189
190
191
192
        return -code $rc $result
    }
}

# # ## ### ##### ######## ############# ######################
## Implementation :: Info - Visible API



























proc ::namespacex::info::allvars ns {
    set ns [uplevel 1 [list [namespace parent] normalize $ns]]
    ::set result [::info vars ${ns}::*]
    foreach cns [allchildren $ns] {
	lappend result {*}[::info vars ${cns}::*]
    }







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
        return -code $rc $result
    }
}

# # ## ### ##### ######## ############# ######################
## Implementation :: Info - Visible API


proc ::namespacex::import {from args} {
    set upns [uplevel 1 {namespace current}]
    if {![string match ::* $from]} {
	set from $upns::$from[set from {}]
    }
    set orig [namespace eval $from {namespace export}]
    try {
	namespace eval $from {namespace export *}
	set tmp [namespace current]::[::info cmdcount]
	namespace eval $tmp [list ::namespace import ${from}::*]
	if {[llength $args] == 1} {
	    lappend args [lindex $args 0]
	}
	dict size $args
	foreach {old new} $args {
	    rename ${tmp}::$old ${upns}::$new
	}
	namespace delete $tmp
    } finally {
	namespace eval $from [list ::namespace export -clear {*}$orig]
    }
    return
}


proc ::namespacex::info::allvars ns {
    set ns [uplevel 1 [list [namespace parent] normalize $ns]]
    ::set result [::info vars ${ns}::*]
    foreach cns [allchildren $ns] {
	lappend result {*}[::info vars ${cns}::*]
    }

Changes to modules/ncgi/ncgi.man.

164
165
166
167
168
169
170
171
172
173
174
175

176
177
178
179
180
181
182

Returns the mime type of the uploaded file.

[def "[option -data] [arg name]"]

Returns the contents of the file.

[def "[option -server] [arg name] [opt [arg filename]]"]

Writes the file contents to a local temporary file, or [arg filename]
if supplied, and returns the name of the file. The caller is
responsible for deleting this file after use.


[list_end]


[call [cmd ::ncgi::query] [arg session] [cmd parse]]

Returns the parsed query data as a multidict.







|

<
|
<
>







164
165
166
167
168
169
170
171
172

173

174
175
176
177
178
179
180
181

Returns the mime type of the uploaded file.

[def "[option -data] [arg name]"]

Returns the contents of the file.

[def "[option -server] [arg name]"]


Returns the name of a channel routine for the contents of the field named [arg

name].

[list_end]


[call [cmd ::ncgi::query] [arg session] [cmd parse]]

Returns the parsed query data as a multidict.

Changes to modules/ncgi/ncgi.tcl.

21
22
23
24
25
26
27

28
29
30
31
32
33
34
# to a CGI program.  Typically this comes from a Form in an HTML browser.
# The query data is composed of names and values, and the names can be
# repeated.  The names and values are encoded, and this module takes care
# of decoding them.

# We use newer string routines
package require Tcl 8.6

package require fileutil ; # Required by importFile.
package require mime
package require uri

package provide ncgi 1.5.0

namespace eval ::ncgi {







>







21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# to a CGI program.  Typically this comes from a Form in an HTML browser.
# The query data is composed of names and values, and the names can be
# repeated.  The names and values are encoded, and this module takes care
# of decoding them.

# We use newer string routines
package require Tcl 8.6
package require {chan base}
package require fileutil ; # Required by importFile.
package require mime
package require uri

package provide ncgi 1.5.0

namespace eval ::ncgi {
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
#
# Side Effects:
#	Outputs a normal header

proc ::ncgi::header {token {type text/html} args} {
    namespace upvar $token cookieOutput cookieOutput
    set mimeout [mime::initialize -canonical $type -addcontentid 0 \
	-addmimeversion 0 -string {}]
    foreach {n v} $args {
	mime::header set $mimeout $n $v {}
    }
    if {[info exists cookieOutput]} {
	foreach line $cookieOutput {
	    mime::header set $mimeout Set-Cookie $line {}
	}
    }
    mime::serialize $mimeout -chan stdout
    flush stdout
}


# ::ncgi::importFile --
#
#   get information about a file upload field
#
# Arguments:
#   cmd         one of '-server' '-client' '-type' '-data'
#   var         cgi variable name for the file field
#   filename    filename to write to for -server
# Results:
#   -server returns the name of the file on the server: side effect
#      is that the file gets stored on the server and the 
#      script is responsible for deleting/moving the file
#   -client returns the name of the file sent from the client 
#   -type   returns the mime type of the file
#   -data   returns the contents of the file 

proc ::ncgi::importFile {token cmd var {filename {}}} {
    namespace upvar $token mimeparts mimeparts
    if {[form $token exists]} {
	set form [form $token get]
    }

    lassign [dict get $mimeparts $var] mime 

    lassign [mime::header get $mime content-disposition] cdisp dispparams

    switch -exact -- $cmd {
	-server {
	    ## take care not to write it out more than once
	    namespace upvar $token _tmpfiles _tmpfiles
	    if {![info exists _tmpfiles($var)]} {
		if {$filename eq {}} {
		    ## create a tmp file 
		    set _tmpfiles($var) [::fileutil::tempfile ncgi]
		} else {
		    ## use supplied filename 
		    set _tmpfiles($var) $filename
		}

		# write out the data only if it's not been done already
		if {[catch {open $_tmpfiles($var) w} h]} {
		    error "Can't open temporary file in ncgi::importFile ($h)"
		} 

		fconfigure $h -translation binary -encoding binary
		puts -nonewline $h [mime::body $mime]
		close $h
	    }
	    return $_tmpfiles($var)
	}
	-client {
	    if {[dict exists $dispparams filename]} {
		return [dict get $dispparams filename]
	    }
	    return {}
	}
	-type {
	    lassign [mime::header get $mime content-type] ctype params
	    return $ctype
	}
	-data {
	    return [mime::body $mime]
	}
	default {
	    error "Unknown subcommand to ncgi::import_file: $cmd"
	}
    }
}








|








|
|










<






|













<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<












|







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
#
# Side Effects:
#	Outputs a normal header

proc ::ncgi::header {token {type text/html} args} {
    namespace upvar $token cookieOutput cookieOutput
    set mimeout [mime::initialize -canonical $type -addcontentid 0 \
	-addmimeversion 0 -addmessageid 0  -string {}]
    foreach {n v} $args {
	mime::header set $mimeout $n $v {}
    }
    if {[info exists cookieOutput]} {
	foreach line $cookieOutput {
	    mime::header set $mimeout Set-Cookie $line {}
	}
    }
    mime::serialize $mimeout -chan ${token}::stdout
    ${token}::stdout flush
}


# ::ncgi::importFile --
#
#   get information about a file upload field
#
# Arguments:
#   cmd         one of '-server' '-client' '-type' '-data'
#   var         cgi variable name for the file field

# Results:
#   -server returns the name of the file on the server: side effect
#      is that the file gets stored on the server and the 
#      script is responsible for deleting/moving the file
#   -client returns the name of the file sent from the client 
#   -type   returns the mime type of the file
#   -data   returns a channel command for the contents of the file 

proc ::ncgi::importFile {token cmd var {filename {}}} {
    namespace upvar $token mimeparts mimeparts
    if {[form $token exists]} {
	set form [form $token get]
    }

    lassign [dict get $mimeparts $var] mime 

    lassign [mime::header get $mime content-disposition] cdisp dispparams

    switch -exact -- $cmd {
	-server {

















	    return [mime::body decode $mime]



	}
	-client {
	    if {[dict exists $dispparams filename]} {
		return [dict get $dispparams filename]
	    }
	    return {}
	}
	-type {
	    lassign [mime::header get $mime content-type] ctype params
	    return $ctype
	}
	-data {
	    return [mime::body decoded $mime]
	}
	default {
	    error "Unknown subcommand to ncgi::import_file: $cmd"
	}
    }
}

488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
    set parts [mime::property $mime parts]
    trace add variable mime unset [list apply [list token {
	mime::finalize $token
    } $token]]

    set results [list]
    foreach part $parts {
	    set value [::mime::body $part -decode]
	    lassign [::mime::header get $part content-disposition] hvalue params
	    if {$hvalue eq {form-data} && [dict exists $params name]} {
		set name [dict get $params name]
		dict unset params name
	    } else {
		set name {}
	    }







|







468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
    set parts [mime::property $mime parts]
    trace add variable mime unset [list apply [list token {
	mime::finalize $token
    } $token]]

    set results [list]
    foreach part $parts {
	    set value [[::mime::body decoded $part] read]
	    lassign [::mime::header get $part content-disposition] hvalue params
	    if {$hvalue eq {form-data} && [dict exists $params name]} {
		set name [dict get $params name]
		dict unset params name
	    } else {
		set name {}
	    }
523
524
525
526
527
528
529


530
531
532
533
534
535
536
    } elseif {![string match ::* $name]} {
	set name [uplevel 1 {namespace current}]::$name
    }
    set new [namespace eval $name {
	namespace ensemble create
	namespace current
    }]



    # normalize $new
    set new [namespace which $new]

    set map [list decode decode encode encode {*}[join [lmap cmdname {
	.namespace all importFile input body cookies delete form get
	header merge method new query redirect setCookie type urlStub







>
>







503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
    } elseif {![string match ::* $name]} {
	set name [uplevel 1 {namespace current}]::$name
    }
    set new [namespace eval $name {
	namespace ensemble create
	namespace current
    }]

    ::tcllib::chan::base .new ${new}::stdout stdout -close 0

    # normalize $new
    set new [namespace which $new]

    set map [list decode decode encode encode {*}[join [lmap cmdname {
	.namespace all importFile input body cookies delete form get
	header merge method new query redirect setCookie type urlStub

Changes to modules/ncgi/ncgi.test.

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
testsNeedTcl     8.4
testsNeedTcltest 2

testing {
    useLocal ncgi.tcl ncgi
}

proc main {} {
	global env
	global auto_path

	set     sub_ap $auto_path
	lappend sub_ap $::tcltest::testsDirectory
	set ncgiFile   [localPath ncgi.tcl]
	set futlFile   [tcllibPath fileutil/fileutil.tcl]







|







19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
testsNeedTcl     8.4
testsNeedTcltest 2

testing {
    useLocal ncgi.tcl ncgi
}

proc main {} {try {
	global env
	global auto_path

	set     sub_ap $auto_path
	lappend sub_ap $::tcltest::testsDirectory
	set ncgiFile   [localPath ncgi.tcl]
	set futlFile   [tcllibPath fileutil/fileutil.tcl]
42
43
44
45
46
47
48

49
50
51
52
53
54
55
			} finally {
				set done 1
			}]
			vwait done
			exit
		}
	}


	proc resetenv {} {
		global env
		foreach varname {
			CONTENT_LENGTH CONTENT_TYPE HTTP_COOKIE HTTPS QUERY_STRING
			REQUEST_METHOD REQUEST_URI SERVER_NAME SERVER_PORT
	} {







>







42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
			} finally {
				set done 1
			}]
			vwait done
			exit
		}
	}


	proc resetenv {} {
		global env
		foreach varname {
			CONTENT_LENGTH CONTENT_TYPE HTTP_COOKIE HTTPS QUERY_STRING
			REQUEST_METHOD REQUEST_URI SERVER_NAME SERVER_PORT
	} {
371
372
373
374
375
376
377
378

379
380
381
382
383
384
385
			if {[catch {
				source %s
				source %s
				source %s
				ncgi new ncgi1
				ncgi1 redirect %s
				ncgi1 delete
			} err]} {

				puts $err
			}
		} $sub_ap $cmdlFile $futlFile $ncgiFile $URL]] test1
		set f [open "|[list $::tcltest::tcltest test1]" r+]
		set res [read $f]
		close $f
		removeFile test1







|
>







372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
			if {[catch {
				source %s
				source %s
				source %s
				ncgi new ncgi1
				ncgi1 redirect %s
				ncgi1 delete
			} err eopts]} {
				puts stderr [dict get $eopts -errorinfo]
				puts $err
			}
		} $sub_ap $cmdlFile $futlFile $ncgiFile $URL]] test1
		set f [open "|[list $::tcltest::tcltest test1]" r+]
		set res [read $f]
		close $f
		removeFile test1
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
		set b [genformdatapart field2 "" {another value}]
		set c [genformdatapart the_file_name "; filename=\"C:\\Program Files\\Netscape\\Communicator\\Program\\nareadme.htm\"\nContent-Type: text/html" $bcontent]

		return "$a$b$c--$form_boundary--\n" 
	}



	test ncgi-14.5 {ncgi::multipart--check binary file} {
		set X [genformdata $binary_content]
		withncgi body $X contenttype [genformcontent_type] {
			set content [ncgi1 get the_file_name]
			list [ncgi1 get field1] [ncgi1 get field2] $content
		}
	} [list value {another value} [string map [list \r {}] $binary_content]]







<







772
773
774
775
776
777
778

779
780
781
782
783
784
785
		set b [genformdatapart field2 "" {another value}]
		set c [genformdatapart the_file_name "; filename=\"C:\\Program Files\\Netscape\\Communicator\\Program\\nareadme.htm\"\nContent-Type: text/html" $bcontent]

		return "$a$b$c--$form_boundary--\n" 
	}



	test ncgi-14.5 {ncgi::multipart--check binary file} {
		set X [genformdata $binary_content]
		withncgi body $X contenttype [genformcontent_type] {
			set content [ncgi1 get the_file_name]
			list [ncgi1 get field1] [ncgi1 get field2] $content
		}
	} [list value {another value} [string map [list \r {}] $binary_content]]
852
853
854
855
856
857
858
859



860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
	} text/html


	test ncgi-16.3 {ncgi::importFile -- file contents} {
		global binary_content
		set X [genformdata $binary_content]
		withncgi contenttype [genformcontent_type] body $X  {
			ncgi1 importFile -data the_file_name



		}
	} $binary_content


	test ncgi-16.4 {ncgi::importFile -- save file} {
		global binary_content
		set X [genformdata $binary_content]
		withncgi contenttype [genformcontent_type] body $X  {
			set localfile [ncgi1 importFile -server the_file_name]

			# get the contents of the local file to verify
			set in [open $localfile]
			fconfigure $in -translation binary
			set content [read $in]
			close $in
			file delete $localfile
			set content
		}

	} $binary_content


	test ncgi-16.5 {ncgi::importFile -- save file, given name} {
		global binary_content
		set X [genformdata $binary_content]
		withncgi contenttype [genformcontent_type] body $X {
			set localfile [ncgi1 importFile -server the_file_name fofo]

			# get the contents of the local file to verify
			set in [open $localfile]
			fconfigure $in -translation binary
			set content [read $in]
			close $in
			file delete $localfile
			set content
		}
	} $binary_content


	test ncgi-16.6 {ncgi::importFile -- bad input} {

		set X "bad multipart data"







|
>
>
>








|


<
|
|
|
<
|









|


<
|
|
|
<
|







853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874

875
876
877

878
879
880
881
882
883
884
885
886
887
888
889
890

891
892
893

894
895
896
897
898
899
900
901
	} text/html


	test ncgi-16.3 {ncgi::importFile -- file contents} {
		global binary_content
		set X [genformdata $binary_content]
		withncgi contenttype [genformcontent_type] body $X  {
			set chan [ncgi1 importFile -data the_file_name]
			set res [$chan read]
			$chan close
			return $res
		}
	} $binary_content


	test ncgi-16.4 {ncgi::importFile -- save file} {
		global binary_content
		set X [genformdata $binary_content]
		withncgi contenttype [genformcontent_type] body $X  {
			set chan [ncgi1 importFile -server the_file_name]

			# get the contents of the local file to verify

			$chan configure -translation binary
			set content [$chan read]
			$chan close

			return $content
		}

	} $binary_content


	test ncgi-16.5 {ncgi::importFile -- save file, given name} {
		global binary_content
		set X [genformdata $binary_content]
		withncgi contenttype [genformcontent_type] body $X {
			set chan [ncgi1 importFile -server the_file_name]

			# get the contents of the local file to verify

			$chan configure -translation binary
			set content [$chan read]
			$chan close

			return $content
		}
	} $binary_content


	test ncgi-16.6 {ncgi::importFile -- bad input} {

		set X "bad multipart data"
959
960
961
962
963
964
965
966
967


968
969
970
971
972
			ncgi1 cookies all two
		}
	} {2 3}

	# -------------------------------------------------------------------------

	testsuiteCleanup
	set [namespace current]::done 1
	return


}

after 0 [list ::coroutine [info cmdcount]_main [namespace current]::main]
vwait [namespace current]::done
return







<

>
>
|




959
960
961
962
963
964
965

966
967
968
969
970
971
972
973
			ncgi1 cookies all two
		}
	} {2 3}

	# -------------------------------------------------------------------------

	testsuiteCleanup

	return
} finally {
	set [namespace current]::done 1
}}

after 0 [list ::coroutine [info cmdcount]_main [namespace current]::main]
vwait [namespace current]::done
return

Changes to modules/virtchannel_base/pkgIndex.tcl.

9
10
11
12
13
14
15

16
17
package ifneeded tcl::chan::null 1         [list source [file join $dir null.tcl]]
package ifneeded tcl::chan::nullzero 1     [list source [file join $dir nullzero.tcl]]
package ifneeded tcl::chan::random 1       [list source [file join $dir random.tcl]]
package ifneeded tcl::chan::std 1.0.1      [list source [file join $dir std.tcl]]
package ifneeded tcl::chan::string 1.0.3   [list source [file join $dir string.tcl]]
package ifneeded tcl::chan::textwindow 1   [list source [file join $dir textwindow.tcl]]
package ifneeded tcl::chan::variable 1.0.4 [list source [file join $dir variable.tcl]]

package ifneeded tcl::chan::zero 1         [list source [file join $dir zero.tcl]]
package ifneeded tcl::randomseed 1         [list source [file join $dir randseed.tcl]]







>


9
10
11
12
13
14
15
16
17
18
package ifneeded tcl::chan::null 1         [list source [file join $dir null.tcl]]
package ifneeded tcl::chan::nullzero 1     [list source [file join $dir nullzero.tcl]]
package ifneeded tcl::chan::random 1       [list source [file join $dir random.tcl]]
package ifneeded tcl::chan::std 1.0.1      [list source [file join $dir std.tcl]]
package ifneeded tcl::chan::string 1.0.3   [list source [file join $dir string.tcl]]
package ifneeded tcl::chan::textwindow 1   [list source [file join $dir textwindow.tcl]]
package ifneeded tcl::chan::variable 1.0.4 [list source [file join $dir variable.tcl]]
package ifneeded tcl::chan::wrapper 1      [list source [file join $dir wrapper.tcl]]
package ifneeded tcl::chan::zero 1         [list source [file join $dir zero.tcl]]
package ifneeded tcl::randomseed 1         [list source [file join $dir randseed.tcl]]

Added modules/virtchannel_base/wrapper.tcl.













































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#! /usr/bin/env tclsh

# # ## ### ##### ######## #############
# (C) 2018 Poor Yorick
# # ## ### ##### ######## #############

package require Tcl 8.6

package require coroutine

package require tcl::chan::events

oo::class create ::tcl::chan::wrapper {
    superclass ::tcl::chan::events ; # -> initialize, finalize, watch


    constructor args {
	namespace path [list ::coroutine::util {*}[namespace path]]
	dict size $args
	foreach {key val} $args {
	    switch $key {
		chan {
		    set chan $chan
		}
	    }
	}
	next {*}$args
    }

    method blocking {c m} {
	chan blocking $c $m
    }


    method cget {c o} {
	chan configure $chan $o
    }


    method cgetall c {
	chan configure $chan
    }


    method configure {c o v} {
	chan configure $chan $o $v
    }


    method finalize {} {
	close $chan
	next
    }

    method read {c n} {
	read $c $n
    }

    method seek {c o b} {
	seek $c $o $b
    }

    method write {c d} {
	puts -nonwline $chan $d
    }

    variable chan
}

package provide tcl::chan::wrapper 1

Changes to modules/virtchannel_core/transformcore.tcl.

49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
		lappend supported $m
	    }
	}
	return $supported
    }

    method finalize {c} {
	set channel {} ; # Prevent destroctor from calling close.
	my destroy
	return
    }

    # # ## ### ##### ######## #############

    variable channel







|







49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
		lappend supported $m
	    }
	}
	return $supported
    }

    method finalize {c} {
	set channel {} ; # Prevent destructor from calling close.
	my destroy
	return
    }

    # # ## ### ##### ######## #############

    variable channel

Changes to modules/virtchannel_transform/base64.tcl.

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
    return
}

oo::class create ::tcl::transform::base64::implementation {
    superclass tcl::transform::core ;# -> initialize, finalize, destructor

    method write {c data} {
	my Code encodebuf encode $data 3


    }

    method read {c data} {




	my Code decodebuf decode $data 4


    }

    method flush {c} {
	set data [binary encode base64 $encodebuf]
	set encodebuf {}
	return $data
    }

    method drain {c} {

	set data [binary decode base64 $decodebuf]



	set decodebuf {}
	return $data
    }

    method clear {c} {
	set decodebuf {}
	return
    }

    # # ## ### ##### ######## #############

    constructor {} {
	set encodebuf {}


	set decodebuf {}
	return
    }

    # # ## ### ##### ######## #############

    variable encodebuf decodebuf

    # # ## ### ##### ######## #############

    method Code {bufvar op data n} {
	upvar 1 $bufvar buffer

	append buffer $data

	set n [my Complete $buffer $n]
	if {$n < 0} {
	    return {}
	}

	set result \
	    [binary $op base64 \
		 [string range $buffer 0 $n]]




	incr n
	set buffer \
	    [string range $buffer $n end]

	return $result
    }

    method Complete {buffer n} {
	set len [string length $buffer]
	return [expr {(($len / $n) * $n)-1}]
    }







|
>
>



>
>
>
>
|
>
>









>

>
>
>













>
>






|













|
|
|
>
>
>
>

<
|
|







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
    return
}

oo::class create ::tcl::transform::base64::implementation {
    superclass tcl::transform::core ;# -> initialize, finalize, destructor

    method write {c data} {
	set res [my Code encodebuf encode $data 3]
	incr encdount [string length $data]
	return $res
    }

    method read {c data} {
	set length [string length $data]
	# remove whitespace to make framing calculations in [Code] accurate
	# to do:  Add a -strict configuration to disallow whitespace?
	regsub -all {[[:space:]]} $data[set data {}] {} data
	set res [my Code decodebuf decode $data 4]
	incr deccount $length 
	return $res
    }

    method flush {c} {
	set data [binary encode base64 $encodebuf]
	set encodebuf {}
	return $data
    }

    method drain {c} {
	set length [string length $decodebuf]
	set data [binary decode base64 $decodebuf]
	if {$data eq {} && $length} {
	    error [list {invalid input after } $deccount]
	}
	set decodebuf {}
	return $data
    }

    method clear {c} {
	set decodebuf {}
	return
    }

    # # ## ### ##### ######## #############

    constructor {} {
	set encodebuf {}
	set deccount 0
	set enccount 0
	set decodebuf {}
	return
    }

    # # ## ### ##### ######## #############

    variable enccount encodebuf deccount decodebuf

    # # ## ### ##### ######## #############

    method Code {bufvar op data n} {
	upvar 1 $bufvar buffer

	append buffer $data

	set n [my Complete $buffer $n]
	if {$n < 0} {
	    return {}
	}

	set chunk [string range $buffer 0 $n]
	set result [binary $op base64 $chunk]

	if {$result eq {} && $chunk ne {}} {
	    error [list {invalid input after} [
		expr {$op eq {encode} ? $enccount : $deccount}]]
	}
	incr n

	set buffer [string range $buffer $n end]
	
	return $result
    }

    method Complete {buffer n} {
	set len [string length $buffer]
	return [expr {(($len / $n) * $n)-1}]
    }

Changes to modules/virtchannel_transform/pkgIndex.tcl.

1
2
3
4
5
6
7
8
9
10
11

12
13
14
if {![package vsatisfies [package provide Tcl] 8.6]} {return}

package ifneeded tcl::transform::adler32 1     [list source [file join $dir adler32.tcl]]
package ifneeded tcl::transform::base64 1      [list source [file join $dir base64.tcl]]
package ifneeded tcl::transform::counter 1     [list source [file join $dir counter.tcl]]
package ifneeded tcl::transform::crc32 1       [list source [file join $dir crc32.tcl]]
package ifneeded tcl::transform::hex 1         [list source [file join $dir hex.tcl]]
package ifneeded tcl::transform::identity 1    [list source [file join $dir identity.tcl]]
package ifneeded tcl::transform::limitsize 1   [list source [file join $dir limitsize.tcl]]
package ifneeded tcl::transform::observe 1     [list source [file join $dir observe.tcl]]
package ifneeded tcl::transform::otp 1         [list source [file join $dir otp.tcl]]

package ifneeded tcl::transform::rot 1         [list source [file join $dir rot.tcl]]
package ifneeded tcl::transform::spacer 1      [list source [file join $dir spacer.tcl]]
package ifneeded tcl::transform::zlib 1.0.1    [list source [file join $dir zlib.tcl]]











>



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if {![package vsatisfies [package provide Tcl] 8.6]} {return}

package ifneeded tcl::transform::adler32 1     [list source [file join $dir adler32.tcl]]
package ifneeded tcl::transform::base64 1      [list source [file join $dir base64.tcl]]
package ifneeded tcl::transform::counter 1     [list source [file join $dir counter.tcl]]
package ifneeded tcl::transform::crc32 1       [list source [file join $dir crc32.tcl]]
package ifneeded tcl::transform::hex 1         [list source [file join $dir hex.tcl]]
package ifneeded tcl::transform::identity 1    [list source [file join $dir identity.tcl]]
package ifneeded tcl::transform::limitsize 1   [list source [file join $dir limitsize.tcl]]
package ifneeded tcl::transform::observe 1     [list source [file join $dir observe.tcl]]
package ifneeded tcl::transform::otp 1         [list source [file join $dir otp.tcl]]
package ifneeded {tcl transform qp} 0.1        [list source [file join $dir qp.tcl]]
package ifneeded tcl::transform::rot 1         [list source [file join $dir rot.tcl]]
package ifneeded tcl::transform::spacer 1      [list source [file join $dir spacer.tcl]]
package ifneeded tcl::transform::zlib 1.0.1    [list source [file join $dir zlib.tcl]]

Added modules/virtchannel_transform/qp.tcl.































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#! /usr/bin/env tclsh

# # ## ### ##### ######## #############
# (C) 2018 Poor Yorick

# # ## ### ##### ######## #############

package require {mime qp}
package require tcl::transform::core

namespace eval ::tcl::transform {}

proc ::tcl::transform::qp chan {
    ::chan push $chan [qp::implementation new]
    return

}

oo::class create ::tcl::transform::qp::implementation {
    superclass tcl::transform::core ;# -> initialize, finalize, destructor

    method write {c data} {
	::mime::qp::encode $data
    }

    method read {c data} {
	::mime::qp::decode $data
    }
}

package provide {tcl transform qp} 0.1