Tcl Library Source Code

Check-in [57af8b6c63]
Login

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

Overview
Comment:Pulling changes from trunk
Timelines: family | ancestors | descendants | both | hypnotoad
Files: files | file ages | folders
SHA3-256:57af8b6c63c013ec5faaa5988392e97a3efae9d28cd0a5cccbeb255e96fb0651
User & Date: hypnotoad 2018-09-08 18:56:45
Context
2018-09-11
17:13
Modifications to the httpd module: httpd::reply object in order to simplify the code inside of httpd::server and give developers more rope to hang themselves. The httpd::reply method now uses one general purpose dispatch public method, with all of the application specific wulu magic now confined to a new private method Dispatch Folded the functions of the former reply::dispatch method into the new public dispatch method, and eliminated reply::dispatch. Replaced http::reply.scgi with a mixin that swaps that one function that is different between them. httpd::server no longer looks for an alternate reply class. It is now assumed that every reply will be httpd::reply, and that the dispatch method will be able to sort out what behaviors get mixed in. Simplified the implementation of ::httpd::plugin.dict_dispatch Added a new method to the Uri ensemble: uri::direct which automates the process of producing simple dynamic content cases. Formalized the arguments for uri::add Moved the headers parsing out of the body of Connect and into a dedicated method ServerHeaders. Added a call to Dispatch_Local to the default dispatch method. check-in: 7b4c25cd6e user: hypnotoad tags: hypnotoad
2018-09-08
18:56
Pulling changes from trunk check-in: 57af8b6c63 user: hypnotoad tags: hypnotoad
18:56
Httpd module: Fixed a goof in redirect handlers. Fixed which headers are accessed for logging. Added a shim for web servers to provide a standard style mixin. Added a shim for servers to participate with their own private methods prior and following mixin dispatch. Added a hook for server to provide a local method for Headers check-in: d20a51f758 user: hypnotoad tags: hypnotoad
2018-09-06
09:46
Fix namespace resolution for relative namespaces. Add "normalize" and 'strip" commands. check-in: ccd9433cb2 user: pooryorick tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to modules/fumagic/filetypes.tcl.

47
48
49
50
51
52
53
54
55

56
57
58
59
60
61
62
63
64
..
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

    set chan [open $file]
    try {
	set matches {}
	file stat $file stats
	set finfo [array get stats]
	dict set finfo name $file
	set coro [coroutine [info cmdcount] rt::new $finfo $chan $named [
	    list [namespace which filetype::analyze]]]

	while 1 {
	    lassign [$coro] weight result mimetype ext 
	    dict update matches $weight weight {
		lappend weight [list $result $mimetype $ext]
	    }
	}
    } finally {
	close $chan
    }
................................................................................
		return $res
	    }
	}
	if {$mimtetype ne {} || $ext ne {}} {
	    return $res
	}
    }
    return [list {} {} {}]
}


package provide fileutil::magic::filetype 2.0


namespace eval ::fileutil::magic::filetype {







|

>

|







 







|







47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
..
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

    set chan [open $file]
    try {
	set matches {}
	file stat $file stats
	set finfo [array get stats]
	dict set finfo name $file
	set ft [rt::new $finfo $chan $named [
	    list [namespace which filetype::analyze]]]
	set class [$ft]
	while 1 {
	    lassign [$ft] weight result mimetype ext 
	    dict update matches $weight weight {
		lappend weight [list $result $mimetype $ext]
	    }
	}
    } finally {
	close $chan
    }
................................................................................
		return $res
	    }
	}
	if {$mimtetype ne {} || $ext ne {}} {
	    return $res
	}
    }
    return [list $class {} {}]
}


package provide fileutil::magic::filetype 2.0


namespace eval ::fileutil::magic::filetype {

Changes to modules/fumagic/filetypes.test.

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
..
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
...
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
...
274
275
276
277
278
279
280

281
282
283
284
285
286
287


test fumagic.filetype-1.4 {test simple binary} {
    set f [makeBinFile]
    set res [catch {fileutil::magic::filetype $f} msg]
    removeBinFile
    list $res $msg
} {0 {{} {} {}}}


test fumagic.filetype-1.5 {test elf executable} {
    set f [makeElfFile]
    set res [catch {fileutil::magic::filetype $f} msg]
    removeElfFile
    list $res $msg
................................................................................


test fumagic.filetype-1.6 {test simple text} {
    set f [makeTextFile]
    set res [catch {fileutil::magic::filetype $f} msg]
    removeTextFile
    list $res $msg
} {0 {{} {} {}}}


test fumagic.filetype-1.7 {test script file} {
    set f [makeScriptFile]
    set res [catch {fileutil::magic::filetype $f} msg]
    removeScriptFile
    list $res $msg
................................................................................


test fumagic.filetype-1.19 {test binary gravity_wave_data_frame} {
    set f [makeIgwdFile]
    set res [catch {fileutil::magic::filetype $f} msg]
    removeIgwdFile
    list $res $msg
} {0 {{} {} {}}}


test fumagic.filetype-1.20 {test binary compressed bzip} {
    set f [makeBzipFile]
    set res [catch {fileutil::magic::filetype $f} msg]
    removeBzipFile
    list $res $msg
................................................................................
        set finfo [array get stats]
        dict set finfo name $f

        set coro [coroutine [info cmdcount] \
            ::fileutil::magic::rt::new $finfo $chan \
		$::fileutil::magic::filetype::named [
        	list [namespace which ::fileutil::magic::filetype::analyze]]]

        while 1 {
            lassign [$coro] weight result mimetype ext 
            dict update matches $weight weight {
        	lappend weight [list $result $mimetype $ext]
            }
        }
    } finally {







|







 







|







 







|







 







>







60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
..
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
...
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
...
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288


test fumagic.filetype-1.4 {test simple binary} {
    set f [makeBinFile]
    set res [catch {fileutil::magic::filetype $f} msg]
    removeBinFile
    list $res $msg
} {0 {binary {} {}}}


test fumagic.filetype-1.5 {test elf executable} {
    set f [makeElfFile]
    set res [catch {fileutil::magic::filetype $f} msg]
    removeElfFile
    list $res $msg
................................................................................


test fumagic.filetype-1.6 {test simple text} {
    set f [makeTextFile]
    set res [catch {fileutil::magic::filetype $f} msg]
    removeTextFile
    list $res $msg
} {0 {text {} {}}}


test fumagic.filetype-1.7 {test script file} {
    set f [makeScriptFile]
    set res [catch {fileutil::magic::filetype $f} msg]
    removeScriptFile
    list $res $msg
................................................................................


test fumagic.filetype-1.19 {test binary gravity_wave_data_frame} {
    set f [makeIgwdFile]
    set res [catch {fileutil::magic::filetype $f} msg]
    removeIgwdFile
    list $res $msg
} {0 {binary {} {}}}


test fumagic.filetype-1.20 {test binary compressed bzip} {
    set f [makeBzipFile]
    set res [catch {fileutil::magic::filetype $f} msg]
    removeBzipFile
    list $res $msg
................................................................................
        set finfo [array get stats]
        dict set finfo name $f

        set coro [coroutine [info cmdcount] \
            ::fileutil::magic::rt::new $finfo $chan \
		$::fileutil::magic::filetype::named [
        	list [namespace which ::fileutil::magic::filetype::analyze]]]
	set class [$coro]
        while 1 {
            lassign [$coro] weight result mimetype ext 
            dict update matches $weight weight {
        	lappend weight [list $result $mimetype $ext]
            }
        }
    } finally {

Changes to modules/fumagic/rtcore.tcl.

122
123
124
125
126
127
128



129
130
131
132
133
134
135
...
252
253
254
255
256
257
258





259
260
261
262
263
264
265
266
267
...
289
290
291
292
293
294
295


296
297
298
299
300
301
302

    # [*] The vast majority of magic strings are in the first 4k of the file.

    # Export APIs (full public, recognizer public)
    namespace export file_start result
    namespace export emit ext mime new offset strength \
	D Nv N O S Nvx Nx Sx L R T I U < >



}




# ### ### ### ######### ######### #########
## Public API, general use.
................................................................................

proc ::fileutil::magic::rt::mime value {
    upvar #1 mime mime
    set mime [split [message $value] /]
}







# level #1 of a coroutine
proc ::fileutil::magic::rt::new {finfo chan named tests} {
    array set cache {}	    ; # Cache of fetched and decoded numeric
			    ; # values.

    ::fconfigure $chan -translation binary

    # fill the string cache
    set strbuf [::read $chan 4096]  ; # Input cache [*].
................................................................................

    set virtual(0) 0	; # the virtual start of the file at each level

    set strengths(0) 0
    set typematch(0) 0

    yield [info coroutine]


    if {[string length $strbuf] == 0} {
	yield [list 0 empty {} {}]
    } else {
	{*}$tests
    }
    rename [info coroutine] {}
    return -code break







>
>
>







 







>
>
>
>
>

|







 







>
>







122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
...
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
...
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312

    # [*] The vast majority of magic strings are in the first 4k of the file.

    # Export APIs (full public, recognizer public)
    namespace export file_start result
    namespace export emit ext mime new offset strength \
	D Nv N O S Nvx Nx Sx L R T I U < >

    namespace eval _ {}

}




# ### ### ### ######### ######### #########
## Public API, general use.
................................................................................

proc ::fileutil::magic::rt::mime value {
    upvar #1 mime mime
    set mime [split [message $value] /]
}


proc ::fileutil::magic::rt::new {finfo chan named tests} {
    coroutine _::[info cmdcount] [list [
	namespace which coro]] $finfo $chan $named $tests
}

# level #1 of a coroutine
proc ::fileutil::magic::rt::coro {finfo chan named tests} {
    array set cache {}	    ; # Cache of fetched and decoded numeric
			    ; # values.

    ::fconfigure $chan -translation binary

    # fill the string cache
    set strbuf [::read $chan 4096]  ; # Input cache [*].
................................................................................

    set virtual(0) 0	; # the virtual start of the file at each level

    set strengths(0) 0
    set typematch(0) 0

    yield [info coroutine]
    yield $class

    if {[string length $strbuf] == 0} {
	yield [list 0 empty {} {}]
    } else {
	{*}$tests
    }
    rename [info coroutine] {}
    return -code break

Changes to modules/math/ChangeLog.







1
2
3
4
5
6
7






2018-07-22  Arjen Markus <arjenmarkus@users.sourceforge.net>
	* trig.tcl: Implementation of (additional) trigonometric functions - package math::trig
	* trig.test: Trst for the (additional) trigonometric functions
	* trig.man: Documentation for the (additional) trigonometric functions
	* pkgIndex.tcl: Add the new package

2018-07-19  Arjen Markus <arjenmarkus@users.sourceforge.net>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
2018-08-04  Arjen Markus <arjenmarkus@users.sourceforge.net>
	* statistics.tcl: Source stat_wasserstein.tcl and stat_logit.tcl - for new commands
	* statistics.test: Add corresponding tests
	* statistics.man: Add description of these commands
	* pkgIndex.tcl: Bump the version to 1.3.0

2018-07-22  Arjen Markus <arjenmarkus@users.sourceforge.net>
	* trig.tcl: Implementation of (additional) trigonometric functions - package math::trig
	* trig.test: Trst for the (additional) trigonometric functions
	* trig.man: Documentation for the (additional) trigonometric functions
	* pkgIndex.tcl: Add the new package

2018-07-19  Arjen Markus <arjenmarkus@users.sourceforge.net>

Changes to modules/math/TODO.

1






2
3
4
5
6
7
8
This file records outstanding actions for the math module







dd. 17 june 2018
- Factor out the backward rotation in the intersection routines for circles
- Add a normalisation routine for vectors
- Add routines to construct a perpendicular vector and line
- Add a routine to return the perpendicular bisector of a line segment
- Add routines to deal with triangles (incircle, circumcircle)

>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
This file records outstanding actions for the math module

dd. 4 september 2018
- Implement a "typical profile" for timeseries and determining residuals
  (Plus perhaps a notion of outliers)
- Implement detection of extreme values/periods with extreme values


dd. 17 june 2018
- Factor out the backward rotation in the intersection routines for circles
- Add a normalisation routine for vectors
- Add routines to construct a perpendicular vector and line
- Add a routine to return the perpendicular bisector of a line segment
- Add routines to deal with triangles (incircle, circumcircle)

Changes to modules/math/pkgIndex.tcl.

17
18
19
20
21
22
23

24
25
26
27
28
29
30
31
32
33
34
package ifneeded math::bignum            3.1.1 [list source [file join $dir bignum.tcl]]
package ifneeded math::bigfloat          1.2.2 [list source [file join $dir bigfloat.tcl]]
package ifneeded math::machineparameters 0.1   [list source [file join $dir machineparameters.tcl]]

if {![package vsatisfies [package provide Tcl] 8.5]} {return}
package ifneeded math::calculus          0.8.1 [list source [file join $dir calculus.tcl]]
# statistics depends on linearalgebra (for multi-variate linear regression).

package ifneeded math::statistics        1.2.0 [list source [file join $dir statistics.tcl]]
package ifneeded math::linearalgebra     1.1.6 [list source [file join $dir linalg.tcl]]
package ifneeded math::calculus::symdiff 1.0.1 [list source [file join $dir symdiff.tcl]]
package ifneeded math::bigfloat          2.0.2 [list source [file join $dir bigfloat2.tcl]]
package ifneeded math::numtheory         1.1.1 [list source [file join $dir numtheory.tcl]]
package ifneeded math::decimal           1.0.3 [list source [file join $dir decimal.tcl]]
package ifneeded math::geometry          1.3.0 [list source [file join $dir geometry.tcl]]
package ifneeded math::trig              1.0   [list source [file join $dir trig.tcl]]
if {![package vsatisfies [package require Tcl] 8.6]} {return}
package ifneeded math::exact             1.0   [list source [file join $dir exact.tcl]]
package ifneeded math::PCA               1.0   [list source [file join $dir pca.tcl]]







>
|










17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package ifneeded math::bignum            3.1.1 [list source [file join $dir bignum.tcl]]
package ifneeded math::bigfloat          1.2.2 [list source [file join $dir bigfloat.tcl]]
package ifneeded math::machineparameters 0.1   [list source [file join $dir machineparameters.tcl]]

if {![package vsatisfies [package provide Tcl] 8.5]} {return}
package ifneeded math::calculus          0.8.1 [list source [file join $dir calculus.tcl]]
# statistics depends on linearalgebra (for multi-variate linear regression).
# statistics depends on optimize (for logistic regression).
package ifneeded math::statistics        1.3.0 [list source [file join $dir statistics.tcl]]
package ifneeded math::linearalgebra     1.1.6 [list source [file join $dir linalg.tcl]]
package ifneeded math::calculus::symdiff 1.0.1 [list source [file join $dir symdiff.tcl]]
package ifneeded math::bigfloat          2.0.2 [list source [file join $dir bigfloat2.tcl]]
package ifneeded math::numtheory         1.1.1 [list source [file join $dir numtheory.tcl]]
package ifneeded math::decimal           1.0.3 [list source [file join $dir decimal.tcl]]
package ifneeded math::geometry          1.3.0 [list source [file join $dir geometry.tcl]]
package ifneeded math::trig              1.0   [list source [file join $dir trig.tcl]]
if {![package vsatisfies [package require Tcl] 8.6]} {return}
package ifneeded math::exact             1.0   [list source [file join $dir exact.tcl]]
package ifneeded math::PCA               1.0   [list source [file join $dir pca.tcl]]

Added modules/math/stat_logit.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
# stat_logit.tcl --
#     Logistic regression functions - part of the statistics package
#
#     Note:
#     The implementation was derived from the Wikipedia page on logistic regression,
#     (https://en.wikipedia.org/wiki/Logistic_regression) as is the test case.
#
#     TODO:
#     - Deviance to evaluate the goodness of fit
#     - Evaluate the probability
#

package require math::optimize

namespace eval ::math::statistics {
     variable xLogit {}
     variable yLogit {}
}

# logistic-model --
#     Fit 1/0 data to a logistic model
#
# Arguments:
#     xdata        Independent variables (list of lists if there are more than one)
#     ydata        Corresponding scores (0 or 1)
#
# Result:
#     Estimate of the parameters for a logistic model
#
# Note:
#     It is expected that the independent variables have roughly the same scale
#
proc ::math::statistics::logistic-model {xdata ydata} {
    variable xLogit
    variable yLogit

    set xLogit {}
    foreach coords $xdata {
        lappend xLogit [concat 1.0 $coords]
    }
    set yLogit $ydata

    #
    # Use a trivial starting point
    #
    set startx [lrepeat [llength [lindex $xLogit 0]] 0.0]

    set result [::math::optimize::nelderMead LogisticML_NM $startx]

    return [dict get $result x]
}


# LogisticML_NM --
#     Calculate the (log) maximum likelihood for the given logistic model
#     using Nelder-Mead
#
# Arguments:
#     args        Vector of the current regression coefficients
#
# Returns:
#     Log maximum likelihood
#
proc ::math::statistics::LogisticML_NM {args} {
    variable xLogit
    variable yLogit

    set loglike 0.0
    foreach coords $xLogit score $yLogit {
        set sum 0.0

        foreach c $coords v $args {
            set sum [expr {$sum + $v * $c}]
        }
        set exp [expr {exp(-$sum)}]

        if { $score == 1 } {
            set loglike [expr {$loglike - log(1.0 + $exp)}]
        } else {
            set loglike [expr {$loglike - $sum - log(1.0 + $exp)}]
        }
    }
    return [expr {-$loglike}]
}

# logistic-probability --
#     Calculate the probability of a positive score (1) given the model
#
# Arguments:
#     coeffs      Coefficients of the logistic model (for instance outcome of model fit)
#     values      Values of the independent variables
#
# Returns:
#     Probability
#
proc ::math::statistics::logistic-probability {coeffs values} {
    set sum 0.0

    foreach c $coeffs v [concat 1.0 $values] {
        set sum [expr {$sum + $c * $v}]
    }

    return [expr {1.0 / (1.0 + exp(-$sum))}]
}

# test case: from Wikipedia
if {0} {
set xdata {0.50 0.75 1.00 1.25 1.50 1.75 1.75 2.00 2.25 2.50 2.75 3.00 3.25 3.50 4.00 4.25 4.50 4.75 5.00 5.50}
set ydata {0    0    0    0    0    0    1    0    1    0    1    0    1    0    1    1    1    1    1    1   }

set coeffs [::math::statistics::logistic-model $xdata $ydata]

puts "Model fit: $coeffs"

puts "Probabilities:"

foreach x {1 2 3 4 5} {
    puts "$x - [::math::statistics::logistic-probability $coeffs $x]"
}
}

Added modules/math/stat_wasserstein.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
# stat-wasserstein.tcl --
#     Determine the Wasserstein distance between two probability distributions
#
#     Note:
#     This is an implementation for one-dimensional distributions (or better:
#     non-negative patterns)
#
#     Note 2:
#     The lower bound of 1.0e-10 is probably not at all necessary
#

# LastNonZero --
#     Auxiliary procedure to find the last non-zero entry
#
# Arguments:
#     prob           Probability distribution
#
# Result:
#     Index in the list of the last non-zero entry
#
# Note:
#     To avoid numerical problems any value smaller than 1.0e-10 is considered to
#     be zero
#
proc ::math::statistics::LastNonZero {prob} {
    set maxidx [expr {[llength $prob] - 1}]

    for {set idx $maxidx} {$idx >= 0} {incr idx -1} {
        if { [lindex $prob $idx] > 1.0e-10 } {
            return $idx
        }
    }

    return -1 ;# No non-zero entry
}

# Normalise --
#     Auxiliary procedure to normalise the probability distribution
#
# Arguments:
#     prob           Probability distribution
#
# Result:
#     Normalised distribution (i.e. the entries sum to 1)
#
# Note:
#     To avoid numerical problems any value smaller than 1.0e-10 is set to zero
#
proc ::math::statistics::Normalise {prob} {

    set newprob {}
    set sum     0.0

    foreach p $prob {
        set sum [expr {$sum + $p}]
    }

    if { $sum == 0.0 } {
        return -code error "Probability distribution should not consist of only zeroes"
    }

    foreach p $prob {
        lappend newprob [expr {$p > 1.0e-10? ($p/$sum) : 0.0}]
    }

    return $newprob
}

# wasserstein-distance --
#     Determine the Wasserstein distance using a "greedy" algorithm.
#
# Arguments:
#     prob1          First probability distribution, interpreted as a histogram
#                    with uniform bin width
#     prob2          Second probability distribution
#
# Result:
#     Distance between the two distributions
#
proc ::math::statistics::wasserstein-distance {prob1 prob2} {
    #
    # First step: make sure the histograms have the same length and the
    # same cumulative weight.
    #
    if { [llength $prob1] != [llength $prob2] } {
        return -code error "Lengths of the probability histograms must be the same"
    }

    set prob1 [Normalise $prob1]
    set prob2 [Normalise $prob2]

    set distance 0.0

    #
    # Determine the last non-zero bin - this bin will be shifted to the second
    # distribution
    #
    while {1} {
        set idx1 [LastNonZero $prob1]
        set idx2 [LastNonZero $prob2]

        if { $idx1 < 0 } {
            break ;# We are done
        }

        set bin1 [lindex $prob1 $idx1]
        set bin2 [lindex $prob2 $idx2]

        if { $bin1 <= $bin2 } {
            lset prob1 $idx1 0.0
            lset prob2 $idx2 [expr {$bin2 - $bin1}]
            set distance [expr {$distance + abs($idx2-$idx1) * $bin1}]
        } else {
            lset prob1 $idx1 [expr {$bin1 - $bin2}]
            lset prob2 $idx2 0.0
            set distance [expr {$distance + abs($idx2-$idx1) * $bin2}]
        }
    }

    return $distance
}

# kl-divergence --
#     Calculate the Kullback-Leibler (KL) divergence for two discrete distributions
#
# Arguments:
#     prob1          First probability distribution - the divergence is calculated
#                    with this one as the basis
#     prob2          Second probability distribution - the divergence of this
#                    distribution wrt the first is calculated
#
# Notes:
#     - The KL divergence is an asymmetric measure
#     - It is actually only defined if prob2 is only zero when prob1 is too
#     - The number of elements in the two distributions must be the same and
#       bins must be the same
#
proc ::math::statistics::kl-divergence {prob1 prob2} {
    if { [llength $prob1] != [llength $prob2] } {
        return -code error "Lengths of the two probability histograms must be the same"
    }

    #
    # Normalise the probability histograms
    #
    set prob1 [Normalise $prob1]
    set prob2 [Normalise $prob2]

    #
    # Check for well-definedness while going along
    #
    set sum 0.0
    foreach p1 $prob1 p2 $prob2 {
        if { $p2 == 0.0 && $p1 != 0.0 } {
            return -code error "Second probability histogram contains unmatched zeroes"
        }

        if { $p1 != 0.0 } {
            set sum [expr {$sum - $p1 * log($p2/$p1)}]
        }
    }

    return $sum
}

if {0} {
# tests --
#

# Almost trivial
set prob1 {0.0 0.0 0.0 1.0}
set prob2 {0.0 0.0 1.0 0.0}

puts "Expected distance: 1"
puts "Calculated: [wasserstein-distance $prob1 $prob2]"
puts "Symmetric:  [wasserstein-distance $prob2 $prob1]"

# Less trivial
set prob1 {0.0 0.75 0.25 0.0}
set prob2 {0.0 0.0  1.0  0.0}

puts "Expected distance: 0.75"
puts "Calculated: [wasserstein-distance $prob1 $prob2]"
puts "Symmetric:  [wasserstein-distance $prob2 $prob1]"

# Shift trivial
set prob1 {0.0 0.1 0.2 0.4 0.2 0.1 0.0 0.0}
set prob2 {0.0 0.0 0.0 0.1 0.2 0.4 0.2 0.1}

puts "Expected distance: 2"
puts "Calculated: [wasserstein-distance $prob1 $prob2]"
puts "Symmetric:  [wasserstein-distance $prob2 $prob1]"


# KL-divergence
set prob1 {0.0 0.1 0.2 0.4 0.2 0.1 0.0 0.0}
set prob2 {0.0 0.1 0.2 0.4 0.2 0.1 0.0 0.0}

puts "KL-divergence for equal distributions: 0"
puts "KL-divergence: [kl-divergence $prob1 $prob2]"

set prob1 {0.1e-8 0.1    0.2 0.4 0.2 0.1 0.0 0.0    0.0}
set prob2 {0.1e-8 0.1e-8 0.1 0.2 0.4 0.2 0.1 0.1e-8 0.1e-8}

puts "KL-divergence for shifted distributions: ??"
puts "KL-divergence: [kl-divergence $prob1 $prob2]"

# Hm, the normalisation proc causes a slight problem with elements of 1.0e-10
set prob1 {0.1e-8 0.1  0.2  0.4 0.2  0.1  0.0     0.0}
set prob2 {0.1e-8 0.11 0.19 0.4 0.24 0.06 0.1e-8  0.1e-8}

puts "KL-divergence slightly dififerent distributions: ??"
puts "KL-divergence: [kl-divergence $prob1 $prob2]"
}

Changes to modules/math/statistics.man.

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
...
614
615
616
617
618
619
620
















































621
622
623
624
625
626
627
[manpage_begin math::statistics n [vset VERSION]]
[keywords {data analysis}]
[keywords mathematics]
[keywords statistics]
[moddesc {Tcl Math Library}]
[titledesc {Basic statistical functions and procedures}]
[category  Mathematics]
[require Tcl 8.4]
[require math::statistics [vset VERSION]]
[description]
[para]

The [package math::statistics] package contains functions and procedures for
basic statistical data analysis, such as:

................................................................................
is returned (as a list of "sampleSize" values), otherwise a list of samples is returned.

[list_begin arguments]
[arg_def list data]           List of values to chose from
[arg_def int sampleSize]      Number of values per sample
[arg_def int numberSamples]   Number of samples (default: 1)
[list_end]

















































[list_end]

[section "MULTIVARIATE LINEAR REGRESSION"]

Besides the linear regression with a single independent variable, the
statistics package provides two procedures for doing ordinary







|







 







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







2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
...
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
[manpage_begin math::statistics n [vset VERSION]]
[keywords {data analysis}]
[keywords mathematics]
[keywords statistics]
[moddesc {Tcl Math Library}]
[titledesc {Basic statistical functions and procedures}]
[category  Mathematics]
[require Tcl 8.5]
[require math::statistics [vset VERSION]]
[description]
[para]

The [package math::statistics] package contains functions and procedures for
basic statistical data analysis, such as:

................................................................................
is returned (as a list of "sampleSize" values), otherwise a list of samples is returned.

[list_begin arguments]
[arg_def list data]           List of values to chose from
[arg_def int sampleSize]      Number of values per sample
[arg_def int numberSamples]   Number of samples (default: 1)
[list_end]

[call [cmd ::math::statistics::wasserstein-distance] [arg prob1] [arg prob2]]
Compute the Wasserstein distance or earth mover's distance for two equidstantly spaced histograms
or probability densities. The histograms need not to be normalised to sum to one,
but they must have the same number of entries.
[nl]
Note: the histograms are assumed to be based on the same equidistant intervals.
As the bounds are not passed, the value is expressed in the length of the intervals.

[list_begin arguments]
[arg_def list prob1]          List of values for the first histogram/probability density
[arg_def list prob2]          List of values for the second histogram/probability density
[list_end]

[call [cmd ::math::statistics::kl-divergence] [arg prob1] [arg prob2]]
Compute the Kullback-Leibler (KL) divergence for two equidstantly spaced histograms
or probability densities. The histograms need not to be normalised to sum to one,
but they must have the same number of entries.
[nl]
Note: the histograms are assumed to be based on the same equidistant intervals.
As the bounds are not passed, the value is expressed in the length of the intervals.
[nl]
Note also that the KL divergence is not symmetric and that the second histogram
should not contain zeroes in places where the first histogram has non-zero values.

[list_begin arguments]
[arg_def list prob1]          List of values for the first histogram/probability density
[arg_def list prob2]          List of values for the second histogram/probability density
[list_end]

[call [cmd ::math::statistics::logistic-model] [arg xdata] [arg ydata]]
Estimate the coefficients of the logistic model that fits the data best. The data consist
of independent x-values and the outcome 0 or 1 for each of the x-values. The result
can be used to estimate the probability that a certain x-value gives 1.

[list_begin arguments]
[arg_def list xdata]          List of values for which the success (1) or failure (0) is known
[arg_def list ydata]          List of successes or failures corresponding to each value in [term xdata].
[list_end]

[call [cmd ::math::statistics::logistic-probability] [arg coeffs] [arg x]]
Calculate the probability of success for the value [term x] given the coefficients of the
logistic model.

[list_begin arguments]
[arg_def list coeffs]         List of coefficients as determine by the [cmd logistic-model] command
[arg_def float x]             X-value for which the probability needs to be determined
[list_end]

[list_end]

[section "MULTIVARIATE LINEAR REGRESSION"]

Besides the linear regression with a single independent variable, the
statistics package provides two procedures for doing ordinary

Changes to modules/math/statistics.tcl.

17
18
19
20
21
22
23

24
25
26
27
28
29
30
31
32
33
....
1790
1791
1792
1793
1794
1795
1796


1797
1798
1799
1800
1801
1802
1803
# version 0.7:   added Kruskal-Wallis test (by Torsten Berg)
# version 0.8:   added Wilcoxon test and Spearman rank correlation
# version 0.9:   added kernel density estimation
# version 0.9.3: added histogram-alt, corrected test-normal
# version 1.0:   added test-anova-F
# version 1.0.1: correction in pdf-lognormal and cdf-lognormal
# version 1.1:   added test-Tukey-range and test-Dunnett


package require Tcl 8.5 ; # 8.5+ feature in test-anovo-F: **-operator
package provide math::statistics 1.2.0
package require math

if {![llength [info commands ::lrepeat]]} {
    # Forward portability, emulate lrepeat
    proc ::lrepeat {n args} {
	if {$n < 1} {
	    return -code error "must have a count of at least 1"
................................................................................
source [file join [file dirname [info script]] pdf_stat.tcl]
source [file join [file dirname [info script]] plotstat.tcl]
source [file join [file dirname [info script]] liststat.tcl]
source [file join [file dirname [info script]] mvlinreg.tcl]
source [file join [file dirname [info script]] kruskal.tcl]
source [file join [file dirname [info script]] wilcoxon.tcl]
source [file join [file dirname [info script]] stat_kernel.tcl]



#
# Define the tables
#
namespace eval ::math::statistics {
    variable tukey_table_05
    variable tukey_table_01







>


|







 







>
>







17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
....
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
# version 0.7:   added Kruskal-Wallis test (by Torsten Berg)
# version 0.8:   added Wilcoxon test and Spearman rank correlation
# version 0.9:   added kernel density estimation
# version 0.9.3: added histogram-alt, corrected test-normal
# version 1.0:   added test-anova-F
# version 1.0.1: correction in pdf-lognormal and cdf-lognormal
# version 1.1:   added test-Tukey-range and test-Dunnett
# version 1.3:   added wasserstein-distance, kl-divergence and logit regression

package require Tcl 8.5 ; # 8.5+ feature in test-anovo-F: **-operator
package provide math::statistics 1.3.0
package require math

if {![llength [info commands ::lrepeat]]} {
    # Forward portability, emulate lrepeat
    proc ::lrepeat {n args} {
	if {$n < 1} {
	    return -code error "must have a count of at least 1"
................................................................................
source [file join [file dirname [info script]] pdf_stat.tcl]
source [file join [file dirname [info script]] plotstat.tcl]
source [file join [file dirname [info script]] liststat.tcl]
source [file join [file dirname [info script]] mvlinreg.tcl]
source [file join [file dirname [info script]] kruskal.tcl]
source [file join [file dirname [info script]] wilcoxon.tcl]
source [file join [file dirname [info script]] stat_kernel.tcl]
source [file join [file dirname [info script]] stat_wasserstein.tcl]
source [file join [file dirname [info script]] stat_logit.tcl]

#
# Define the tables
#
namespace eval ::math::statistics {
    variable tukey_table_05
    variable tukey_table_01

Changes to modules/math/statistics.test.

14
15
16
17
18
19
20

21
22
23
24
25
26
27
....
1194
1195
1196
1197
1198
1199
1200
1201



















































































































































1202
1203

testsNeedTcl     8.5;# statistics,linalg!
testsNeedTcltest 2.1

support {
    useLocal math.tcl math
    useLocal linalg.tcl math::linearalgebra

}
testing {
    useLocal statistics.tcl math::statistics
}

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

................................................................................
            set result 0
        }
    }

    set result
} -result 1





















































































































































# End of test cases
testsuiteCleanup







>







 








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


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
....
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
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

testsNeedTcl     8.5;# statistics,linalg!
testsNeedTcltest 2.1

support {
    useLocal math.tcl math
    useLocal linalg.tcl math::linearalgebra
    useLocal optimize.tcl math::optimize
}
testing {
    useLocal statistics.tcl math::statistics
}

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

................................................................................
            set result 0
        }
    }

    set result
} -result 1


#
# Tests for Wasserstein distance and KL divergence
#
# Tests for error conditions
#
test "Wasserstein-1.1" "Error: lengths differ" -body {
    set distance [::math::statistics::wasserstein-distance {0 1} {1 0 0 0}]
} -returnCodes 1 -result {Lengths of the probability histograms must be the same}

#
# Check the symmetry for arbitrary histograms
#
test "Wasserstein-1.2" "Test symmetry" -body {
    set okay 1
    for {set i 0} {$i < 10} {incr i} {
        set histogram1 {}
        set histogram2 {}
        for {set j 0} {$j < 3*($i+1)} {incr j} {
            lappend histogram1 [expr {rand()}]
            lappend histogram2 [expr {rand()}]
        }

        set distance1 [::math::statistics::wasserstein-distance $histogram1 $histogram2]
        set distance2 [::math::statistics::wasserstein-distance $histogram2 $histogram1]

        if { abs($distance1-$distance2) > 1.0e-6 } {
            set okay 0
        }
    }

    return $okay

} -result 1

#
# Check the non-negativity for arbitrary histograms
#
test "Wasserstein-1.3" "Test non-negativity" -body {
    set okay 1
    for {set i 0} {$i < 10} {incr i} {
        set histogram1 {}
        set histogram2 {}
        for {set j 0} {$j < 3*($i+1)} {incr j} {
            lappend histogram1 [expr {rand()}]
            lappend histogram2 [expr {rand()}]
        }

        set distance1 [::math::statistics::wasserstein-distance $histogram1 $histogram2]

        if { $distance1 < 0.0 } {
            set okay 0
        }
    }

    return $okay

} -result 1

#
# Check the non-normalised histograms
#
test "Wasserstein-1.4" "Test non-normalised histograms" -match tolerant -body {
    return [list [::math::statistics::wasserstein-distance {2 0 0} {0 0 0.5}]  \
                 [::math::statistics::wasserstein-distance {1 0 0} {0 0 0.25}] ]
} -result {2.0 2.0}

#
# Check arbitrarily extended histograms
#
test "Wasserstein-1.5" "Test extended histograms" -match tolerant -body {
    return [list [::math::statistics::wasserstein-distance {1 0 0}     {0 0 1}]     \
                 [::math::statistics::wasserstein-distance {0 0 1 0 0} {0 0 0 0 1}] \
                 [::math::statistics::wasserstein-distance {1 0 0 0 0} {0 0 1 0 0}] ]
} -result {2.0 2.0 2.0}

#
# Check numerical results
#
test "Wasserstein-1.6" "Test numerical results" -match tolerant -body {
    return [list [::math::statistics::wasserstein-distance {1 0 0}     {0 0.5 0.5}]             \
                 [::math::statistics::wasserstein-distance {1 0 0 0 0} {0 0 0 0.5 0.5}]         \
                 [::math::statistics::wasserstein-distance {1 0 0 0 0} {0 0.25 0.25 0.25 0.25}] ]
} -result {1.5 3.5 2.5}

#
# Tests for error conditions
#
test "KL-divergence-1.1" "Error: lengths differ" -body {
    set distance [::math::statistics::kl-divergence {0 1} {1 0 0 0}]
} -returnCodes 1 -result {Lengths of the two probability histograms must be the same}

test "KL-divergence-1.2" "Error: unmatched zeroes" -body {
    set distance [::math::statistics::kl-divergence {0.3 0.3 0.4} {1 0 0}]
} -returnCodes 1 -result {Second probability histogram contains unmatched zeroes}


test "KL-divergence-1.3" "Matched zeroes should be accepted" -match tolerant -body {
    set distance [::math::statistics::kl-divergence {0.3 0.3 0.4 0} {0.7 0.2 0.1 0}]
} -returnCodes 0 -result 0.42196792

#
# Tests for equal histograms (not all normalised)
#
test "KL-divergence-1.4" "Equal histograms give zero divergence" -body {
    set distance [::math::statistics::kl-divergence {0.3 0.3 0.4} {0.3 0.3 0.4}]
} -result 0.0

test "KL-divergence-1.5" "Non-normalised but equal histograms give zero divergence" -body {
    set distance [::math::statistics::kl-divergence {0.3 0.3 0.4} {0.6 0.6 0.8}]
} -result 0.0

#
# Numerical tests - note: the expected values were taken from the implementation
#                         No independent source found
#
test "KL-divergence-1.6" "Shifted histograms" -match tolerant -body {
    set distance [::math::statistics::kl-divergence {1.0e-8 0.3 0.3 0.3 0.1} {0.3 0.3 0.3 0.1 1.0e-8}]
} -result 1.9413931

test "KL-divergence-1.7" "Arbitrary histograms" -match tolerant -body {
    set distance [::math::statistics::kl-divergence {0.4 0.2 0.3 0.1} {0.1 0.1 0.7 0.1}]
} -result 0.4389578


#
# Tests for logistic regression
#
set xdata {0.50 0.75 1.00 1.25 1.50 1.75 1.75 2.00 2.25 2.50 2.75 3.00 3.25 3.50 4.00 4.25 4.50 4.75 5.00 5.50}
set ydata {0    0    0    0    0    0    1    0    1    0    1    0    1    0    1    1    1    1    1    1   }

test "Logit-regression-1.0" "Logistic regression - coefficients" -match tolerant -body {
    set coeffs [::math::statistics::logistic-model $xdata $ydata]
} -result {-4.07679035286303 1.5045982920571572}

test "Logit-regression-1.1" "Logistic regression - probabilities" -match tolerant -body {
    set coeffs [::math::statistics::logistic-model $xdata $ydata]

    set probabilities {}
    foreach x {1 2 3 4 5} {
        lappend probabilities [::math::statistics::logistic-probability $coeffs $x]
    }

    return $probabilities

} -result {0.07094967663389527 0.2558609520815849 0.6075450376084848 0.8745281239093334 0.9691176473773739}


# End of test cases
testsuiteCleanup

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
...
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
...
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
...
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
...
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
...
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
...
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
[para]

The [package mime] library package provides the commands to create and
manipulate MIME body parts.

[list_begin definitions]

[call [cmd ::mime::initialize] [opt "[option -canonical] [arg type/subtype] [opt "[option -param] \{[arg {key value}]\}..."] [opt "[option -encoding] [arg value]"] [opt "[option -header] \{[arg {key value}]\}..."]"] "([option -file] [arg name] | [option -string] [arg value] | [option -parts] \{[arg token1] ... [arg tokenN]\})"]


This command creates a MIME part and returns a token representing it.

[list_begin itemized]

[item]

If the [option -canonical] option is present, then the body is in
canonical (raw) form and is found by consulting either the

[option -file], [option -string], or [option -parts] option.

[para]

In addition, both the [option -param] and [option -header] options may
occur zero or more times to specify [const Content-Type] parameters
(e.g., [const charset]) and header keyword/values (e.g.,







[const Content-Disposition]), respectively.

[para]

Also, [option -encoding], if present, specifies the

[const Content-Transfer-Encoding] when copying the body.

[item]

If the [option -canonical] option is not present, then the MIME part
contained in either the [option -file] or the [option -string] option
is parsed, dynamically generating subordinates as appropriate.

[list_end]

[call [cmd ::mime::finalize] [arg token] [opt "[option -subordinates] [const all] | [const dynamic] | [const none]"]]

This command destroys the MIME part represented by [arg token]. It
returns an empty string.

[para]

If the [option -subordinates] option is present, it specifies which
subordinates should also be destroyed. The default value is

[const dynamic], destroying all subordinates which were created by
[cmd ::mime::initialize] together with the containing body part.

[call [cmd ::mime::getproperty] [arg token] [opt "[arg property] | [option -names]"]]

This command returns a string or a list of strings containing the
properties of a MIME part. If the command is invoked with the name of
a specific property, then the corresponding value is returned;
instead, if [option -names] is specified, a list of all properties is
returned; otherwise, a serialized array of properties and values is
returned.

[para]
The possible properties are:

................................................................................

[def [const size]]

The approximate size of the content (unencoded)

[list_end]

[call [cmd ::mime::getheader] [arg token] [opt "[arg key] | [option -names]"]]

This command returns the header of a MIME part, as a list of strings.

[para]

A header consists of zero or more key/value pairs. Each value is a
list containing one or more strings.

[para]

If this command is invoked with the name of a specific [arg key], then
a list containing the corresponding value(s) is returned; instead, if
-names is specified, a list of all keys is returned; otherwise, a
serialized array of keys and values is returned. Note that when a key
is specified (e.g., "Subject"), the list returned usually contains
exactly one string; however, some keys (e.g., "Received") often occur
more than once in the header, accordingly the list returned usually
contains more than one string.

[call [cmd ::mime::setheader] [arg token] [arg {key value}] [opt "[option -mode] [const write] | [const append] | [const delete]"]]

This command writes, appends to, or deletes the [arg value] associated
with a [arg key] in the header. It returns a list of strings
containing the previous value associated with the key.














[para]

The value for [option -mode] is one of:

[list_begin definitions]

................................................................................
All values associated with the key are removed (the [arg value]
parameter is ignored).

[list_end]

[call [cmd ::mime::getbody] [arg token] [opt [option -decode]] [opt "[option -command] [arg callback] [opt "[option -blocksize] [arg octets]"]"]]

This command returns a string containing the body of the leaf MIME
part represented by [arg token] in canonical form.

[para]

If the [option -command] option is present, then it is repeatedly
invoked with a fragment of the body as this:

[example {
  uplevel #0 $callback [list "data" $fragment]
}]

[para]
................................................................................
[para]

Regardless, the return value of the final invocation of the callback
is propagated upwards by [cmd ::mime::getbody].

[para]

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

[para]

If the option [option -decode] is absent the return value computed
above is returned as is. This means that it will be in the charset
................................................................................

If the option [option -decode] is present however the command will use
the charset information associated with the token to convert the
string from its encoding into utf-8 before returning it.

[call [cmd ::mime::copymessage] [arg token] [arg channel]]

This command copies the MIME represented by [arg token] part to the
specified [arg channel]. The command operates synchronously, and uses
fileevent to allow asynchronous operations to proceed
independently. It returns an empty string.

[call [cmd ::mime::buildmessage] [arg token]]

This command returns the MIME part represented by [arg token] as a
string.  It is similar to [cmd ::mime::copymessage], only it returns
the data as a return string instead of writing to a channel.

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

This command takes a string containing one or more 822-style address
specifications and returns a list of serialized arrays, one element
for each address specified in the argument. If the string contains
more than one address they will be separated by commas.

[para]

Each serialized array contains the properties below. Note that one or
................................................................................

822-style route specification (obsolete)

[list_end]

[call [cmd ::mime::parsedatetime] ([arg string] | [option -now]) [arg property]]

This command takes a string containing an 822-style date-time
specification and returns the specified property as a serialized
array.

[para]

The list of properties and their ranges are:

................................................................................

-720 .. 720 (minutes east of GMT)

[list_end]

[call [cmd ::mime::mapencoding] [arg encoding_name]]

This commansd 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.

[call [cmd ::mime::reversemapencoding] [arg charset_type]]

This command maps MIME charset types onto tcl encoding names.  Those
that are unknown return "".

[list_end]

[section {KNOWN BUGS}]

[list_begin definitions]







|
>

|





|
|

|

|

|
|
|
>
>

>
>
>
>
|









|







|












|

|







 







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







 







|




|







 







|







 







|






|





|







 







|







 







|





|







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
...
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
...
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
...
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
...
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
...
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
...
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
[para]

The [package mime] library package provides the commands to create and
manipulate MIME body parts.

[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 -file] [arg name] | [option -string] [arg value] | [option -parts] \{[arg token1] ... [arg tokenN]\})"]]

Creates a MIME part and returns a token representing it.

[list_begin itemized]

[item]

If the [option -canonical] option is present the body is already well-formed
according to the provided [arg type/subtype].

If [option -file] is provided, the body of the message is read from the specified file.

If [option -string] is provided, the accompanying value is the body of the message.

If [option -parts] is provided, the media type is [const multipart] and the
tokens in the provided list, which were retuned from previous calls to
[cmd ::mime::initialize],  are used to produce the message body.  If
[option -canonical] is not provided, the default value of
[const multipart/mixed] is used.

[option -headers] is a dictionary of headers, with possibly redundant keys that
might specify for example, [const Content-Type].

[option -params] is a dictionary of parameters, with possibly redundant keys
that might specify, for example [const Content-Disposition].

[para]

Also, [option -encoding], if present, specifies the

[const Content-Transfer-Encoding] when copying the body.

[item]

If the [option -canonical] option is not present, the MIME part
contained in either the [option -file] or the [option -string] option
is parsed, dynamically generating subordinates as appropriate.

[list_end]

[call [cmd ::mime::finalize] [arg token] [opt "[option -subordinates] [const all] | [const dynamic] | [const none]"]]

Destroys the MIME part represented by [arg token]. It
returns an empty string.

[para]

If the [option -subordinates] option is present, it specifies which
subordinates should also be destroyed. The default value is

[const dynamic], destroying all subordinates which were created by
[cmd ::mime::initialize] together with the containing body part.

[call [cmd ::mime::getproperty] [arg token] [opt "[arg property] | [option -names]"]]

Returns a string or a list of strings containing the
properties of a MIME part. If the command is invoked with the name of
a specific property, the corresponding value is returned;
instead, if [option -names] is specified, a list of all properties is
returned; otherwise, a serialized array of properties and values is
returned.

[para]
The possible properties are:

................................................................................

[def [const size]]

The approximate size of the content (unencoded)

[list_end]

[call [cmd ::mime::header] [cmd serialize] [arg value] [arg parameters]]

Serializes a header value and its parameters.

[call [cmd ::mime::header] [cmd get] [arg token] [opt "[arg key] | [option -names]"]]

Returns the header of a MIME part as a dictionary with possibly-redundant keys,
where each value is a list containing the header value and any parameters for
that value.

[para]

If [arg key] is provided, a list of values of matching names, without
regard to case, is returned.

[para]

If [option -names] is provided, a list of all keys is returned.


[call [cmd ::mime::header] [cmd set] [arg token] [arg {key value}] [ \
    opt "[arg parameters] [opt "[option -mode] [const write] | [\
	const append] | [const delete]"]"]]

If [const append] is provided, creates a new header named [arg key] with the
value of [arg value] is added.

If [const write] is provided, deletes any existing headers whose names match
[arg key] and then creates a new header named [arg key] with the value of
[arg value].

If [const delete] is provided any existing header having a name that matches
[arg key] is deleted. 

[arg parameters] is a dictionary of parameters for the header.

Returns a list of strings containing the previous value associated with the
key.

[para]

The value for [option -mode] is one of:

[list_begin definitions]

................................................................................
All values associated with the key are removed (the [arg value]
parameter is ignored).

[list_end]

[call [cmd ::mime::getbody] [arg token] [opt [option -decode]] [opt "[option -command] [arg callback] [opt "[option -blocksize] [arg octets]"]"]]

Returns a string containing the body of the leaf MIME
part represented by [arg token] in canonical form.

[para]

If the [option -command] option is present, it is repeatedly
invoked with a fragment of the body as this:

[example {
  uplevel #0 $callback [list "data" $fragment]
}]

[para]
................................................................................
[para]

Regardless, the return value of the final invocation of the callback
is propagated upwards by [cmd ::mime::getbody].

[para]

If the [option -command] option is absent, the return value of
[cmd ::mime::getbody] is a string containing the MIME part's entire
body.

[para]

If the option [option -decode] is absent the return value computed
above is returned as is. This means that it will be in the charset
................................................................................

If the option [option -decode] is present however the command will use
the charset information associated with the token to convert the
string from its encoding into utf-8 before returning it.

[call [cmd ::mime::copymessage] [arg token] [arg channel]]

Copies the MIME represented by [arg token] part to the
specified [arg channel]. The command operates synchronously, and uses
fileevent to allow asynchronous operations to proceed
independently. It returns an empty string.

[call [cmd ::mime::buildmessage] [arg token]]

Returns the MIME part represented by [arg token] as a
string.  It is similar to [cmd ::mime::copymessage], only it returns
the data as a return string instead of writing to a channel.

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

Takes a string containing one or more 822-style address
specifications and returns a list of serialized arrays, one element
for each address specified in the argument. If the string contains
more than one address they will be separated by commas.

[para]

Each serialized array contains the properties below. Note that one or
................................................................................

822-style route specification (obsolete)

[list_end]

[call [cmd ::mime::parsedatetime] ([arg string] | [option -now]) [arg property]]

Takes a string containing an 822-style date-time
specification and returns the specified property as a serialized
array.

[para]

The list of properties and their ranges are:

................................................................................

-720 .. 720 (minutes east of GMT)

[list_end]

[call [cmd ::mime::mapencoding] [arg encoding_name]]

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.

[call [cmd ::mime::reversemapencoding] [arg charset_type]]

Maps MIME charset types onto tcl encoding names.  Those
that are unknown return "".

[list_end]

[section {KNOWN BUGS}]

[list_begin definitions]

Changes to modules/mime/mime.tcl.

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
..
64
65
66
67
68
69
70
71
72
73
74
75

76
77
78
79
80
81
82
..
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
...
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340

341


342
343
344
345
346
347
348
349
350
351
352
353

354
355
356
357
358
359
360
361
362
363
364
365
366
367
368

369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397

398
399
400






















401
402


403
404
405
406
407
408


409
410


411
412
413


414

415
416
417
418


419
420
421
422
423
424
425
426
427
428
429

430
431
432
433




434
435

436

437
438
439
440
441
442
443


444
445
446
447


448
449
450
451
452
453
454

455
456
457
458
459
460
461
462
463


464

465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485

486
487
488
489
490
491
492
...
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537




























538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640

641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704

705
706
707


708
709
710
711
712

713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
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
788
789
790
...
796
797
798
799
800
801
802
803
804
805
806
807

808
809
810
811
812
813
814
815
816
817
818
819
820
821
...
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
...
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
....
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
....
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222

1223



1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
....
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253



1254
1255
1256
1257
1258
1259
1260
....
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
....
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
....
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
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
....
1500
1501
1502
1503
1504
1505
1506
1507
1508

1509
1510
1511
1512
1513
1514
1515
....
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
....
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
....
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
....
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
....
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
....
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
....
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
1807
1808
1809
1810
1811


1812
1813
1814
1815
1816
1817
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
....
1913
1914
1915
1916
1917
1918
1919



1920
1921
1922
1923
1924
1925
1926
1927
....
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
....
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
....
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054

2055


2056
2057
2058
2059
2060
2061
2062
2063
....
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
....
2093
2094
2095
2096
2097
2098
2099
2100



2101
2102
2103
2104
2105
2106
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
....
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
....
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
....
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
....
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
....
2268
2269
2270
2271
2272
2273
2274























2275
2276
2277
2278
2279
2280
2281
....
2287
2288
2289
2290
2291
2292
2293
2294




2295

2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
....
2348
2349
2350
2351
2352
2353
2354

2355
2356
2357
2358
2359
2360
2361
....
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
....
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
....
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
....
2504
2505
2506
2507
2508
2509
2510

2511


2512
2513
2514
2515
2516
2517
2518
....
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
....
2672
2673
2674
2675
2676
2677
2678

2679
2680
2681
2682
2683
2684
2685
....
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
....
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
....
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
....
2846
2847
2848
2849
2850
2851
2852

2853
2854
2855
2856
2857
2858
2859
....
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
....
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
....
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
....
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
....
3111
3112
3113
3114
3115
3116
3117

3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
....
3145
3146
3147
3148
3149
3150
3151

3152
3153
3154
3155
3156
3157
3158
....
3168
3169
3170
3171
3172
3173
3174

3175
3176
3177
3178
3179
3180
3181
....
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
....
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
....
3394
3395
3396
3397
3398
3399
3400

3401
3402
3403
3404
3405
3406
3407
....
3408
3409
3410
3411
3412
3413
3414
3415


3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
....
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
....
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
....
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
....
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
....
3566
3567
3568
3569
3570
3571
3572

3573
3574
3575
3576
3577
3578
3579
....
3589
3590
3591
3592
3593
3594
3595

3596
3597
3598
3599
3600
3601
3602
....
3612
3613
3614
3615
3616
3617
3618

3619
3620
3621
3622
3623
3624
3625
....
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648

3649
3650
3651
3652
3653
3654
3655
3656
....
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674

3675
3676
3677
3678
3679
3680
3681
3682
....
3697
3698
3699
3700
3701
3702
3703

3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715

3716
3717
3718
3719
3720
3721
3722
3723
....
3737
3738
3739
3740
3741
3742
3743

3744
3745
3746
3747
3748
3749
3750
....
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
....
3794
3795
3796
3797
3798
3799
3800

3801
3802
3803
3804
3805
3806
3807
....
3833
3834
3835
3836
3837
3838
3839

3840
3841
3842



















3843
3844
3845
3846
3847
3848
3849
# (c) 2000      Dan Kuchler
# (c) 2000-2001 Eric Melski
# (c) 2001      Jeff Hobbs
# (c) 2001-2008 Andreas Kupries
# (c) 2002-2003 David Welton
# (c) 2003-2008 Pat Thoyts
# (c) 2005      Benjamin Riefenstahl
# (c) 2013      PoorYorick
#
#
# See the file "license.terms" for information on usage and redistribution
# 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.5

package require tcl::chan::memchan


package provide mime 1.6

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

    # Fall-back to tcl-based procedures of base64 and quoted-printable encoders
    # Warning!
................................................................................
    unset ::major
}

#
# state variables:
#
#     canonicalP: input is in its canonical form
#     content: type/subtype
#     params: seralized array of key/value pairs (keys are lower-case)
#     encoding: transfer encoding
#     version: MIME-version
#     header: serialized array of key/value pairs (keys are lower-case)

#     lowerL: list of header keys, lower-case
#     mixedL: list of header keys, mixed-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
................................................................................
#     string: input string
#
#     cid: last child-id assigned
#


namespace eval ::mime {

    variable mime
    array set mime {uid 0 cid 0}


    # RFC 822 lexemes
    variable addrtokenL
    lappend addrtokenL \; , < > : . ( ) @ \" \[ ] \\
    variable addrlexemeL {
        LX_SEMICOLON LX_COMMA
        LX_LBRACKET  LX_RBRACKET
................................................................................
        LX_COLON     LX_DOT
        LX_LPAREN    LX_RPAREN
        LX_ATSIGN    LX_QUOTE
        LX_LSQUARE   LX_RSQUARE
        LX_QUOTE
    }

    # RFC 2045 lexemes
    variable typetokenL
    lappend typetokenL \; , < > : ? ( ) @ \" \[ \] = / \\
    variable typelexemeL {
        LX_SEMICOLON LX_COMMA
        LX_LBRACKET  LX_RBRACKET
        LX_COLON     LX_QUESTION
        LX_LPAREN    LX_RPAREN
        LX_ATSIGN    LX_QUOTE
        LX_LSQUARE   LX_RSQUARE
        LX_EQUALS    LX_SOLIDUS
        LX_QUOTE
    }

    variable encList {
        ascii US-ASCII
        big5 Big5
        cp1250 Windows-1250
        cp1251 Windows-1251
        cp1252 Windows-1252
        cp1253 Windows-1253
................................................................................
        ksc5601 KSC5601
        ksc5601 korean
        shiftjis MS_Kanji
        utf-8 UTF8
    }

    namespace export {*}{
	copymessage finalize getbody getheader getproperty initialize
	mapencoding parseaddress parsedatetime reversemapencoding setheader
	uniqueID
    }
}

# ::mime::initialize --
#

#    Creates a MIME part, and returnes the MIME token for that part.


#
# Arguments:
#    args   Args can be any one of the following:
#                  ?-canonical type/subtype
#                  ?-param    {key value}?...
#                  ?-encoding value?
#                  ?-header   {key value}?... ?
#                  (-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.

#
#       In addition, both the -param and -header options may occur zero
#       or more times to specify "Content-Type" parameters (e.g.,
#       "charset") and header keyword/values (e.g.,
#       "Content-Disposition"), respectively.
#
#       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::initialize args {
    global errorCode errorInfo

    variable mime

    set token [namespace current]::[incr mime(uid)]
    # FRINK: nocheck
    variable $token
    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 --
#
#    Configures the MIME token created in mime::initialize based on
#       the arguments that mime::initialize supports.
#
# Arguments:
#       token  The MIME token to configure.
#    args   Args can be any one of the following:
#                  ?-canonical type/subtype
#                  ?-param    {key value}?...
#                  ?-encoding value?

#                  ?-header   {key value}?... ?
#                  (-file name | -string value | -parts {token1 ... tokenN})
#






















# Results:
#       Either configures the mime token, or throws an error.



proc ::mime::initializeaux {token args} {
    global errorCode errorInfo
    # FRINK: nocheck
    variable $token
    upvar 0 $token state



    array set params [set state(params) {}]


    set state(encoding) {}
    set state(version) 1.0



    set state(header) {}

    set state(lowerL) {}
    set state(mixedL) {}

    set state(cid) 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 {
            -canonical {

                set state(content) [string tolower $value]
            }

            -param {




                if {[llength $value] != 2} {
		    error "-param expects a key and a value, not $value"

                }

                set lower [string tolower [set mixed [lindex $value 0]]]
                if {[info exists params($lower)]} {
                    error "the $mixed parameter may be specified at most once"
                }

                set params($lower) [lindex $value 1]
                set state(params) [array get params]


            }

            -encoding {
                switch -- [set state(encoding) [string tolower $value]] {


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

                    default {
                        error "unknown value for -encoding $state(encoding)"
                    }
                }

            }

            -header {
                if {[llength $value] != 2} {
                    error "-header expects a key and a value, not $value"
                }
                set lower [string tolower [set mixed [lindex $value 0]]]
                if {$lower eq "content-type"} {
                    error "use -canonical instead of -header $value"


                }

                if {$lower eq "content-transfer-encoding"} {
                    error "use -encoding instead of -header $value"
                }
                if {$lower in {content-md5 mime-version}} {
                    error "don't go there..."
                }
                if {$lower ni $state(lowerL)} {
                    lappend state(lowerL) $lower
                    lappend state(mixedL) $mixed
                }

                array set header $state(header)
                lappend header($lower) [lindex $value 1]
                set state(header) [array get header]
            }

            -file {
                set state(file) $value
            }

            -parts {

                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
                #state(string) is needed, but will be built when required
                set state(string) {}
            }

            default {
                error "unknown option $option"
            }
        }
    }

    #We only want one of -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 "specify exactly one of -file, -parts, or -string"
    }

    if {[set state(canonicalP) [info exists state(content)]]} {




























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

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

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

        if {[lsearch -exact $state(lowerL) content-id] < 0} {
            lappend state(lowerL) content-id
            lappend state(mixedL) Content-ID

            array set header $state(header)
            lappend header(content-id) [uniqueID]
            set state(header) [array get header]
        }

        set state(version) 1.0

        return
    }

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

    if {[set fileP [info exists state(file)]]} {
        if {[set openP [info exists state(root)]]} {
            # FRINK: nocheck
            variable $state(root)
            upvar 0 $state(root) root

            set state(fd) $root(fd)
        } else {
            set state(root) $token
            set state(fd) [open $state(file) RDONLY]
            set state(offset) 0
            seek $state(fd) 0 end
            set state(count) [tell $state(fd)]

            fconfigure $state(fd) -translation binary
        }
    }

    set code [catch {mime::parsepart $token} result]
    set ecode $errorCode
    set einfo $errorInfo

    if {$fileP} {
        if {!$openP} {
            unset state(root)
            catch {close $state(fd)}
        }
        unset state(fd)
    }

    return -code $code -errorinfo $einfo -errorcode $ecode $result
}

# ::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.
#
# Results:
#       Throws an error if it has problems parsing the MIME token,
#       otherwise it just sets up the appropriate variables.

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


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

        if {!$blankP && (
	    [string first { } $line] == 0
	    ||
	    [string first \t $line] == 0
	)} {
            append vline \n $line
            continue
        }

        if {$vline eq {}} {
            if {$blankP} {
                break
            }

            set vline $line
            continue
        }

        if {
	    [set x [string first : $vline]] <= 0
	    ||
	    [set mixed [string trimright [
		string range $vline 0 [expr {$x - 1}]]]] eq {}
	} {
            error "improper line in header: $vline"
        }
        set value [string trim [string range $vline [expr {$x + 1}] end]]
        switch -- [set lower [string tolower $mixed]] {

            content-type {
                if {[info exists state(content)]} {
                    error "multiple Content-Type fields starting with $vline"


                }

                if {![catch {set x [parsetype $token $value]}]} {
                    set state(content) [lindex $x 0]
                    set state(params) [lindex $x 1]

                }
            }

            content-md5 {
            }

            content-transfer-encoding {
                if {
		    $state(encoding) ne {}
		    &&
		    $state(encoding) ne [string tolower $value]
		} {
                    error "multiple Content-Transfer-Encoding fields starting with $vline"
                }

                set state(encoding) [string tolower $value]
            }

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

            default {
                if {[lsearch -exact $state(lowerL) $lower] < 0} {
                    lappend state(lowerL) $lower
                    lappend state(mixedL) $mixed
                }

                array set header $state(header)
                lappend header($lower) $value
                set state(header) [array get header]
            }
        }

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

    if {![info exists state(content)]} {
        set state(content) text/plain
        set state(params) [list charset us-ascii]
    }

    if {![string match multipart/* $state(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/* $state(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 -string $strng
................................................................................
        }

        return
    }

    set state(value) parts

    set boundary {}
    foreach {k v} $state(params) {
        if {$k eq "boundary"} {
            set boundary $v
            break

        }
    }
    if {$boundary eq {}} {
        error "boundary parameter is missing in $state(content)"
    }
    if {[string trim $boundary] eq {}} {
        error "boundary parameter is empty in $state(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
................................................................................
                # 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 $state(content)"
                }
            }
            incr pos [expr {$x + 1}]
        } else {
            if {$state(lines.current) >= $state(lines.count)} {
                error "end-of-string encountered while parsing $state(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 {$forceoctet} {
                set ::errorInfo {}
                if {[catch {
                    mime::initializeaux $child \
                        -file $state(file) -root $state(root) \
                        -offset $start -count $count

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

            }
            seek $state(fd) [set start $pos] start
        } else {
            if {$forceoctet} {
                if {[catch {
                    mime::initializeaux $child -lineslist $start

                }]} {
                    set nochild 1
                    set state(parts) [lrange $state(parts) 0 end-1]
                }
            } else {
                mime::initializeaux $child -lineslist $start

            }
            set start {}
        }
        if {$forceoctet && !$nochild} {
            variable $child
            upvar 0  $child childstate
            set childstate(content) application/octet-stream
        }
        set forceoctet 0
    }
}

# ::mime::parsetype --
#
#       Parses the string passed in and identifies the content-type and
#       params strings.
#
# Arguments:
#       token  The MIME token to parse.
#       string The content-type string that should be parsed.
#
# Results:
#       Returns the content and params for the string as a two element
#       tcl list.

proc ::mime::parsetype {token string} {
    global errorCode errorInfo
    # FRINK: nocheck
    variable $token
    upvar 0 $token state

    variable typetokenL
    variable typelexemeL

    set state(input)   $string
    set state(buffer)  {}
    set state(lastC)   LX_END
    set state(comment) {}
    set state(tokenL)  $typetokenL
    set state(lexemeL) $typelexemeL

    set code [catch {mime::parsetypeaux $token $string} result]
    set ecode $errorCode
    set einfo $errorInfo

    unset {*}{
	state(input)
	state(buffer)
	state(lastC)
	state(comment)
	state(tokenL)
	state(lexemeL)
    }

    return -code $code -errorinfo $einfo -errorcode $ecode $result
}

# ::mime::parsetypeaux --
#
#       A helper function for mime::parsetype.  Parses the specified
#       string looking for the content type and params.
#
# Arguments:
#       token  The MIME token to parse.
#       string The content-type string that should be parsed.
#
# Results:
#       Returns the content and params for the string as a two element
#       tcl list.

proc ::mime::parsetypeaux {token string} {
    # FRINK: nocheck
    variable $token
    upvar 0 $token state

    if {[parselexeme $token] ne "LX_ATOM"} {
        error [format "expecting type (found %s)" $state(buffer)]
    }
    set type [string tolower $state(buffer)]

    switch -- [parselexeme $token] {
        LX_SOLIDUS {
        }

        LX_END {
            if {$type ne "message"} {
                error "expecting type/subtype (found $type)"
            }

            return [list message/rfc822 {}]
        }

        default {
            error [format "expecting \"/\" (found %s)" $state(buffer)]
        }
    }

    if {[parselexeme $token] ne "LX_ATOM"} {
        error [format "expecting subtype (found %s)" $state(buffer)]
    }
    append type [string tolower /$state(buffer)]

    array set params {}
    while 1 {
        switch -- [parselexeme $token] {
            LX_END {
                return [list $type [array get params]]
            }

            LX_SEMICOLON {
            }

            default {
                error [format "expecting \";\" (found %s)" $state(buffer)]
            }
        }

        switch -- [parselexeme $token] {
            LX_END {
                return [list $type [array get params]]
            }

            LX_ATOM {
            }

            default {
                error [format "expecting attribute (found %s)" $state(buffer)]
            }
        }

        set attribute [string tolower $state(buffer)]

        if {[parselexeme $token] ne "LX_EQUALS"} {
            error [format {expecting "=" (found %s)} $state(buffer)]
        }

        switch -- [parselexeme $token] {
            LX_ATOM {
            }

            LX_QSTRING {
                set state(buffer) [
                    string range $state(buffer) 1 [
                        expr {[string length $state(buffer)] - 2}]]
            }

            default {
                error [format "expecting value (found %s)" $state(buffer)]
            }
        }
        set params($attribute) $state(buffer)
    }
}

# ::mime::finalize --
#
#   mime::finalize destroys a MIME part.
#
#   If the -subordinates option is present, it specifies which
#   subordinates should also be destroyed. The default value is
................................................................................
#              ?-subordinates "all" | "dynamic" | "none"?
#
# Results:
#       Returns an empty string.

proc ::mime::finalize {token args} {
    # FRINK: nocheck
    variable $token
    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]
                }
            }
................................................................................
#
#   The "parts" property is present only if the MIME part has
#   subordinates.
#
#   If mime::getproperty 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;
#   otherwise, a serialized array of properties and values is returned.
#
# Arguments:
#       token      The MIME token to parse.
#       property   One of 'content', 'encoding', 'params', 'parts', and
#                  'size'. Defaults to returning a serialized array of
#                  properties and values.
#
# Results:
#       Returns the properties of a MIME part

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





    switch -- $property {
        {} {
            array set properties [list content  $state(content) \
                                       encoding $state(encoding) \
                                       params   $state(params) \
                                       size     [getsize $token]]
            if {[info exists state(parts)]} {
                set properties(parts) $state(parts)
            }

            return [array get properties]
        }
................................................................................
            }

            return $names
        }

        content
            -
        encoding
            -
        params {
            return $state($property)
        }




        parts {
            if {![info exists state(parts)]} {
                error "MIME part is a leaf"
            }

            return $state(parts)
        }
................................................................................
#       token      The MIME token to parse.
#
# Results:
#       Returns the size in bytes of the MIME token.

proc ::mime::getsize {token} {
    # FRINK: nocheck
    variable $token
    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 "Unknown combination \"$state(value)/$state(canonicalP)\""
        }
    }

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

    return $size
}













































































































































# ::mime::getheader --
#
#    mime::getheader returns the header of a MIME part.
#
#    A header consists of zero or more key/value pairs. Each value is a
#    list containing one or more strings.
#
#    If mime::getheader is invoked with the name of a specific key, then
#    a list containing the corresponding value(s) is returned; instead,
#    if -names is specified, a list of all keys is returned; otherwise, a
#    serialized array of keys and values is returned. Note that when a
#    key is specified (e.g., "Subject"), the list returned usually
#    contains exactly one string; however, some keys (e.g., "Received")
#    often occur more than once in the header, accordingly the list
#    returned usually contains more than one string.
#
# Arguments:
#       token      The MIME token to parse.
#       key        Either a key or '-names'.  If it is '-names' a list
#                  of all keys is returned.
#
# Results:
#       Returns the header of a MIME part.

proc ::mime::getheader {token {key {}}} {
    # FRINK: nocheck
    variable $token
    upvar 0 $token state



    array set header $state(header)
    switch -- $key {
        {} {
            set result {}

            foreach lower $state(lowerL) mixed $state(mixedL) {


                lappend result $mixed $header($lower)
            }





            return $result
        }

        -names {
            return $state(mixedL)
        }

        default {
            set lower [string tolower [set mixed $key]]









            if {![info exists header($lower)]} {
                error "key $mixed not in header"
            }
            return $header($lower)

        }
    }
}






































































































































































































































































































































































# ::mime::setheader --
#
#    mime::setheader writes, appends to, or deletes the value associated
#    with a key in the header.
#
#    The value for -mode is one of:
#
#       write: the key/value is either created or overwritten (the
#       default);
#
................................................................................
#       value      The value for the header key to be set to.
#       args       An optional argument of the form:
#                  ?-mode "write" | "append" | "delete"?
#
# Results:
#       Returns previous value associated with the specified key.

proc ::mime::setheader {token key value args} {

    # FRINK: nocheck
    variable $token
    upvar 0 $token state



    array set options [list -mode write]
    array set options $args





    switch -- [set lower [string tolower $key]] {
        content-md5
            -
        content-type
            -
        content-transfer-encoding
            -
        mime-version {
            error "key $key may not be set"
        }
        default {# Skip key}

    }





    array set header $state(header)
    if {[set x [lsearch -exact $state(lowerL) $lower]] < 0} {
        #TODO: this code path is not tested
        if {$options(-mode) eq "delete"} {
            error "key $key not in header"
        }

................................................................................
        lappend state(lowerL) $lower
        lappend state(mixedL) $key

        set result {}
    } else {
        set result $header($lower)
    }
    switch -- $options(-mode) {








































        append {
            lappend header($lower) $value

        }






        delete {
            unset header($lower)

            set state(lowerL) [lreplace $state(lowerL) $x $x]
            set state(mixedL) [lreplace $state(mixedL) $x $x]
        }

        write {
            set header($lower) [list $value]
        }

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

    set state(header) [array get header]

    return $result
}










# ::mime::getbody --
#
#    mime::getbody 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:
#
................................................................................
#       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::getbody {token args} {
    global errorCode errorInfo
    # FRINK: nocheck
    variable $token
    upvar 0 $token state


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

................................................................................
        error "-blocksize expects a positive integer, not $options(-blocksize)"
    }

    set code 0
    set ecode {}
    set einfo {}

    switch -- $state(value)/$state(canonicalP) {
        file/0 {
            set fd [open $state(file) RDONLY]

            set code [catch {
                fconfigure $fd -translation binary
                seek $fd [set pos $state(offset)] start
                set last [expr {$state(offset) + $state(count) - 1}]
................................................................................
                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
................................................................................
        parts/1 {
            error "MIME part isn't a leaf"
        }

        string/0
            -
        string/1 {
            switch -- $state(encoding)/$state(canonicalP) {
                base64/0
                    -
                quoted-printable/0 {
                    set fragment [
                        $state(encoding) -mode decode -- $state(string)]
                }

................................................................................
    set einfo $errorInfo

    if {$code} {
        return -code $code -errorinfo $einfo -errorcode $ecode $result
    }

    if {$decode} {
        array set params [mime::getproperty $token params]

        if {[info exists params(charset)]} {
            set charset $params(charset)
        } else {
            set charset US-ASCII
        }

        set enc [reversemapencoding $charset]
        if {$enc ne {}} {
            set result [::encoding convertfrom $enc $result]
................................................................................
#       Returns nothing, except when called with the 'end' argument
#       in which case it returns a string that contains all of the
#       data that 'getbodyaux' has been called with.  Will throw an
#       error if it is called with the reason of 'error'.

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

    switch $reason {
        data {
            append state(getbody) $fragment
            return {}
        }
................................................................................
# Results:
#       Returns nothing unless an error is thrown while the message
#       is being written to the channel.

proc ::mime::copymessage {token channel} {
    global errorCode errorInfo
    # FRINK: nocheck
    variable $token
    upvar 0 $token state

    set openP [info exists state(fd)]

    set code [catch {mime::copymessageaux $token $channel} result]
    set ecode $errorCode
    set einfo $errorInfo
................................................................................
#
# Results:
#       Returns nothing unless an error is thrown while the message
#       is being written to the channel.

proc ::mime::copymessageaux {token channel} {
    # FRINK: nocheck
    variable $token
    upvar 0 $token state


    array set header $state(header)

    set result {}
    if {$state(version) ne {}} {
        puts $channel "MIME-Version: $state(version)"
    }
    foreach lower $state(lowerL) mixed $state(mixedL) {
        foreach value $header($lower) {
            puts $channel "$mixed: $value"
        }
    }
    if {
		!$state(canonicalP)
		&&
		[set encoding $state(encoding)] ne {}
    } {
        puts $channel "Content-Transfer-Encoding: $encoding"
    }

    puts -nonewline $channel "Content-Type: $state(content)"
    set boundary {}
    foreach {k v} $state(params) {
        if {$k eq "boundary"} {
            set boundary $v
        }

        puts -nonewline $channel ";\n              $k=\"$v\""


    }

    set converter {}
    set encoding {}
    if {$state(value) ne "parts"} {
        #TODO: the path is not covered by tests
        puts $channel {}

        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\""
                }
            }
        }
    } elseif {([string match multipart/* $state(content)]) \
        && ($boundary eq {})} {
        # we're doing everything in one pass...
        set key [clock seconds]$token[info hostname][array get state]
        set seqno 8
        while {[incr seqno -1] >= 0} {
            set key [md5 -- $key]
        }
        set boundary "----- =_[string trim [base64 -mode encode -- $key]]"

        puts $channel ";\n              boundary=\"$boundary\""
    } else {
        puts $channel {}
    }

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

    switch -- $state(value) {
        file {
            set closeP 1
            if {[info exists state(root)]} {
                # FRINK: nocheck
                variable $state(root)
                upvar 0 $state(root) root

                if {[info exists root(fd)]} {
                    set fd $root(fd)
                    set closeP 0
                } else {
                    set fd [set state(fd) [open $state(file) RDONLY]]
................................................................................
		&&
		[info exists state(file)]
	    } {
                set state(fd) [open $state(file) RDONLY]
                fconfigure $state(fd) -translation binary
            }




            switch -glob -- $state(content) {
                message/* {
                    puts $channel {}
                    foreach part $state(parts) {
                        mime::copymessage $part $channel
                        break
                    }
                }
................................................................................
                    # 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 brnaches added CRLF after the
                    #   body parts.


                    foreach part $state(parts) {
                        puts $channel \n--$boundary
                        mime::copymessage $part $channel
                    }
................................................................................
#
# Results:
#       The message. 

proc ::mime::buildmessage token {
    global errorCode errorInfo
    # FRINK: nocheck
    variable $token
    upvar 0 $token state

    set openP [info exists state(fd)]

    set code [catch {mime::buildmessageaux $token} result]
    if {![info exists errorCode]} {
        set ecode {}
................................................................................
# 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
    variable $token
    upvar 0 $token state




    switch -glob -- $state(content) {
        audio/*
            -
        image/*
            -
        video/* {
            return base64
        }
................................................................................
            return {}
        }
        default {# Skip}
    }

    set asciiP 1
    set lineP 1
    switch -- $state(value) {
        file {
            set fd [open $state(file) RDONLY]
            fconfigure $fd -translation binary

            while {[gets $fd line] >= 0} {
                if {$asciiP} {
                    set asciiP [encodingasciiP $line]
................................................................................
        }

        parts {
            return {}
        }

        string {
            foreach line [split $state(string) "\n"] {



                if {$asciiP} {
                    set asciiP [encodingasciiP $line]
                }
                if {$lineP} {
                    set lineP [encodinglineP $line]
                }
                if {(!$asciiP) && (!$lineP)} {
                    break
                }
            }

        }
        default {
            error "Unknown value \"$state(value)\""

        }
    }

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

                        break
                    }
                }
            }

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

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

................................................................................
# Arguments:
#
# Results:
#

proc ::mime::fcopy {token count {error {}}} {
    # FRINK: nocheck
    variable $token
    upvar 0 $token state

    if {$error ne {}} {
        set state(error) $error
    }
    set state(doneP) 1
}
................................................................................
#
# Results:
#    The specified portion of the string in the mime token is
#       copied to the specified channel.

proc ::mime::scopy {token channel offset len blocksize} {
    # FRINK: nocheck
    variable $token
    upvar 0 $token state

    if {$len <= 0} {
        set state(doneP) 1
        fileevent $channel writable {}
        return
    }
................................................................................
    } {
        set state(error) $result
        set state(doneP) 1
        fileevent $channel writable {}
    }
    return
}
























# ::mime::qp_encode --
#
#    Tcl version of quote-printable encode
#
# Arguments:
#    string        The string to quote.
................................................................................

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

    regsub -all -- \




        {[\x00-\x08\x0B-\x1E\x21-\x24\x3D\x40\x5B-\x5E\x60\x7B-\xFF]} \

        $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
    set mapChars [
        list " \n" =20\n \t\n =09\n \n\.\n \=2E\n "\nFrom " "\n=46rom "]
    if {$encoded_word} {
        # Special processing for encoded words (RFC 2047)
        lappend mapChars { } _
    }
    set string [string map $mapChars $string]

    # Break long lines - ugh

    # Implementation of FR #503336
    if {$no_softbreak} {
        set result $string
................................................................................
        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.
................................................................................

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

    # process \u unicode mapped chars

    return [subst -novariables -nocommands $string]
}


# ::mime::parseaddress --
#
#       This was originally written circa 1982 in C. we're still using it
#       because it recognizes virtually every buggy address syntax ever
#       generated!
#
#       mime::parseaddress takes a string containing one or more 822-style
#       address specifications and returns a list of serialized arrays, one
#       element for each address specified in the argument.
#
#    Each serialized array contains these properties:
#
#       property    value
#       ========    =====
#       address     local@domain
#       comment     822-style comment
#       domain      the domain part (rhs)
#       error       non-empty on a parse error
................................................................................
#
#    Note that one or more of these properties may be empty.
#
# Arguments:
#    string        The address string to parse
#
# Results:
#    Returns a list of serialized arrays, one element for each address
#       specified in the argument.

proc ::mime::parseaddress {string} {
    global errorCode errorInfo

    variable mime

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














    set code [catch {mime::parseaddressaux $token $string} result]
    set ecode $errorCode
    set einfo $errorInfo

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

    return -code $code -errorinfo $einfo -errorcode $ecode $result
}


# ::mime::parseaddressaux --
#
#       This was originally written circa 1982 in C. we're still using it
#       because it recognizes virtually every buggy address syntax ever
#       generated!
#
#       mime::parseaddressaux does the actually parsing for mime::parseaddress
#
#    Each serialized array contains these properties:
#
#       property    value
#       ========    =====
#       address     local@domain
#       comment     822-style comment
#       domain      the domain part (rhs)
#       error       non-empty on a parse error
................................................................................
#       phrase      the phrase part
#       proper      822-style address specification
#       route       822-style route specification (obsolete)
#
#    Note that one or more of these properties may be empty.
#
# Arguments:
#       token         The MIME token to work from.
#    string        The address string to parse
#
# Results:
#    Returns a list of serialized arrays, one element for each address
#       specified in the argument.

proc ::mime::parseaddressaux {token string} {
    # FRINK: nocheck
    variable $token
    upvar 0 $token state

    variable addrtokenL
    variable addrlexemeL

    set state(input)   $string
    set state(glevel)  0
................................................................................
    set state(lexemeL) $addrlexemeL

    set result {}
    while {[addr_next $token]} {
        if {[set tail $state(domain)] ne {}} {
            set tail @$state(domain)
        } else {

            set tail @[info hostname]


        }
        if {[set address $state(local)] ne {}} {
            #TODO: this path is not covered by tests
            append address $tail
        }

        if {$state(phrase) ne {}} {
................................................................................
	state(lastC)
	state(tokenL)
	state(lexemeL)
    }

    return $result
}


# ::mime::addr_next --
#
#       Locate the next address in a mime token.
#
# Arguments:
#       token         The MIME token to work from.
#
# Results:
#    Returns 1 if there is another address, and 0 if there is not.

proc ::mime::addr_next {token} {
    global errorCode errorInfo
    # FRINK: nocheck
    variable $token
    upvar 0 $token state
    set nocomplain [package vsatisfies [package provide Tcl] 8.4]
    foreach prop {comment domain error group local memberP phrase route} {
        if {$nocomplain} {
            unset -nocomplain state($prop)
        } else {
            if {[catch {unset state($prop)}]} {set ::errorInfo {}}
        }
    }

    switch -- [set code [catch {mime::addr_specification $token} result]] {
        0 {
            if {!$result} {
                return 0
            }

            switch -- $state(lastC) {
                LX_COMMA
                    -
                LX_END {
                }
                default {
                    # catch trailing comments...
                    set lookahead $state(input)
                    mime::parselexeme $token
                    set state(input) $lookahead
                }
            }
        }

        7 {
            set state(error) $result

            while {1} {
                switch -- $state(lastC) {
                    LX_COMMA
                        -
                    LX_END {
                        break
                    }

                    default {
                        mime::parselexeme $token
                    }
                }
            }
        }

        default {
            set ecode $errorCode
................................................................................
        if {![info exists state($prop)]} {
            set state($prop) {}
        }
    }

    return 1
}


# ::mime::addr_specification --
#
#   Uses lookahead parsing to determine whether there is another
#   valid e-mail address or not.  Throws errors if unrecognized
#   or invalid e-mail address syntax is used.
#
................................................................................
#       token         The MIME token to work from.
#
# Results:
#    Returns 1 if there is another address, and 0 if there is not.

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

    set lookahead $state(input)
    switch -- [parselexeme $token] {
        LX_ATOM
            -
        LX_QSTRING {
            set state(phrase) $state(buffer)
        }

        LX_SEMICOLON {
................................................................................
        default {
            return -code 7 [
		format "unexpected character at beginning (found %s)" \
		   $state(buffer)]
        }
    }

    switch -- [parselexeme $token] {
        LX_ATOM
            -
        LX_QSTRING {
            append state(phrase) " " $state(buffer)

            return [addr_phrase $token]
        }
................................................................................
            return -code 7 [
                format "expecting mailbox (found %s)" $state(buffer)]
        }
    }

    return 1
}


# ::mime::addr_routeaddr --
#
#       Parses the domain portion of an e-mail address.  Finds the '@'
#       sign and then calls mime::addr_route to verify the domain.
#
# Arguments:
................................................................................
#       token         The MIME token to work from.
#
# Results:
#    Returns 1 if there is another address, and 0 if there is not.

proc ::mime::addr_routeaddr {token {checkP 1}} {
    # FRINK: nocheck
    variable $token
    upvar 0 $token state

    set lookahead $state(input)
    if {[parselexeme $token] eq "LX_ATSIGN"} {
        #TODO: this path is not covered by tests
        mime::addr_route $token
    } else {
        set state(input) $lookahead
    }

    mime::addr_local $token

    switch -- $state(lastC) {
        LX_ATSIGN {
            mime::addr_domain $token
        }

        LX_SEMICOLON
            -
        LX_RBRACKET
................................................................................
    if {($checkP) && ($state(lastC) ne "LX_RBRACKET")} {
        return -code 7 [
            format "expecting right-bracket (found %s)" $state(buffer)]
    }

    return 1
}


# ::mime::addr_route --
#
#    Attempts to parse the portion of the e-mail address after the @.
#    Tries to verify that the domain definition has a valid form.
#
# Arguments:
................................................................................
#
# Results:
#    Returns nothing if successful, and throws an error if invalid
#       syntax is found.

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

    set state(route) @

    while 1 {
        switch -- [parselexeme $token] {
            LX_ATOM
                -
            LX_DLITERAL {
                append state(route) $state(buffer)
            }

            default {
                return -code 7 \
                       [format "expecting sub-route in route-part (found %s)" \
                               $state(buffer)]
            }
        }

        switch -- [parselexeme $token] {
            LX_COMMA {
                append state(route) $state(buffer)
                while 1 {
                    switch -- [parselexeme $token] {
                        LX_COMMA {
                        }

                        LX_ATSIGN {
                            append state(route) $state(buffer)
                            break
                        }
................................................................................
                return -code 7 [
		    format "expecting colon to terminate route (found %s)" \
			$state(buffer)]
            }
        }
    }
}


# ::mime::addr_domain --
#
#    Attempts to parse the portion of the e-mail address after the @.
#    Tries to verify that the domain definition has a valid form.
#
# Arguments:
#       token         The MIME token to work from.
#
# Results:
#    Returns nothing if successful, and throws an error if invalid
#       syntax is found.

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

    while 1 {
        switch -- [parselexeme $token] {
            LX_ATOM
                -
            LX_DLITERAL {
                append state(domain) $state(buffer)
            }

            default {
                return -code 7 [
		    format "expecting sub-domain in domain-part (found %s)" \
			$state(buffer)]
            }
        }

        switch -- [parselexeme $token] {
            LX_DOT {
                append state(domain) $state(buffer)
            }

            LX_ATSIGN {
                append state(local) % $state(domain)
                unset state(domain)
................................................................................

            default {
                return
            }
        }
    }
}


# ::mime::addr_local --
#
#
# Arguments:
#       token         The MIME token to work from.
#
# Results:
#    Returns nothing if successful, and throws an error if invalid
#       syntax is found.

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

    set state(memberP) $state(glevel)

    while 1 {
        switch -- [parselexeme $token] {
            LX_ATOM
                -
            LX_QSTRING {
                append state(local) $state(buffer)
            }

            default {
                return -code 7 \
                       [format "expecting mailbox in local-part (found %s)" \
                               $state(buffer)]
            }
        }

        switch -- [parselexeme $token] {
            LX_DOT {
                append state(local) $state(buffer)
            }

            default {
                return
            }
        }
    }
}


# ::mime::addr_phrase --
#
#
# Arguments:
#       token         The MIME token to work from.
#
................................................................................
# Results:
#    Returns nothing if successful, and throws an error if invalid
#       syntax is found.


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

    while {1} {
        switch -- [parselexeme $token] {
            LX_ATOM
                -
            LX_QSTRING {
                append state(phrase) " " $state(buffer)
            }

            default {
                break
            }
        }
    }

    switch -- $state(lastC) {
        LX_LBRACKET {
            return [addr_routeaddr $token]
        }

        LX_COLON {
            return [addr_group $token]
        }
................................................................................
        default {
            return -code 7 [
		format "found phrase instead of mailbox (%s%s)" \
		    $state(phrase) $state(buffer)]
        }
    }
}


# ::mime::addr_group --
#
#
# Arguments:
#       token         The MIME token to work from.
#
# Results:
#    Returns nothing if successful, and throws an error if invalid
#       syntax is found.

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

    if {[incr state(glevel)] > 1} {
        return -code 7 [
	    format "nested groups not allowed (found %s)" $state(phrase)]
    }

    set state(group) $state(phrase)
    unset state(phrase)

    set lookahead $state(input)
    while 1 {
        switch -- [parselexeme $token] {
            LX_SEMICOLON
                -
            LX_END {
                set state(glevel) 0
                return 1
            }

................................................................................
            default {
                set state(input) $lookahead
                return [addr_specification $token]
            }
        }
    }
}


# ::mime::addr_end --
#
#
# Arguments:
#       token         The MIME token to work from.
#
# Results:
#    Returns nothing if successful, and throws an error if invalid
#       syntax is found.

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

    switch -- $state(lastC) {
        LX_SEMICOLON {
            if {[incr state(glevel) -1] < 0} {
                return -code 7 "extraneous semi-colon"
            }
        }

        LX_COMMA
................................................................................

        default {
            return -code 7 [
		format "junk after local@domain (found %s)" $state(buffer)]
        }
    }
}


# ::mime::addr_x400 --
#
#
# Arguments:
#       token         The MIME token to work from.
#
................................................................................

    if {[set x [string first / $mbox]] > 0} {
        set mbox [string range $mbox 0 [expr {$x - 1}]]
    }

    return [string trim $mbox \"]
}


# ::mime::parsedatetime --
#
#    Fortunately the clock command in the Tcl 8.x core does all the heavy
#    lifting for us (except for timezone calculations).
#
#    mime::parsedatetime takes a string containing an 822-style date-time
................................................................................
            }
            incr clock $zone
        }
    } else {
        set clock [clock scan $value]
    }

    switch -- $property {
        clock {
            return $clock
        }

        hour {
            set value [clock format $clock -format %H]
        }
................................................................................

        zone {
            set value [string trim [string map [list \t { }] $value]]
            if {[set x [string last { } $value]] < 0} {
                return 0
            }
            set value [string range $value [expr {$x + 1}] end]
            switch -- [set s [string index $value 0]] {
                + - - {
                    if {$s eq "+"} {
                        #TODO: This path is not covered by tests
                        set s {}
                    }
                    set value [string trim [string range $value 1 end]]
                    if {(
................................................................................

    if {[set value [string trimleft $value 0]] eq {}} {
        #TODO: this path is not covered by tests
        set value 0
    }
    return $value
}


# ::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.
#
................................................................................
# Arguments:
#
# Results:
#    Returns the a string that contains the globally unique identifier
#       that should be used for the Content-ID of an e-mail message.

proc ::mime::uniqueID {} {
    variable mime



    return <[pid].[clock seconds].[incr mime(cid)]@[info hostname]>
}

# ::mime::parselexeme --
#
#    Used to implement a lookahead parser.
#
# Arguments:
#       token    The MIME token to operate on.
#
# Results:
#    Returns the next token found by the parser.

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

    set state(input) [string trimleft $state(input)]

    set state(buffer) {}
    if {$state(input) eq {}} {
        set state(buffer) end-of-input
................................................................................
        set noteP 0
        set quoteP 0

        while 1 {
            append state(buffer) $c

            #TODO: some of these paths are not covered by tests
            switch -- $c/$quoteP {
                (/0 {
                    incr noteP
                }

                \\/0 {
                    set quoteP 1
                }
................................................................................
    if {$c eq "\""} {
        set firstP 1
        set quoteP 0

        while 1 {
            append state(buffer) $c

            switch -- $c/$quoteP {
                "\\/0" {
                    set quoteP 1
                }

                "\"/0" {
                    if {!$firstP} {
                        return [set state(lastC) LX_QSTRING]
................................................................................

    if {$c eq {[}} {
        set quoteP 0

        while 1 {
            append state(buffer) $c

            switch -- $c/$quoteP {
                \\/0 {
                    set quoteP 1
                }

                ]/0 {
                    return [set state(lastC) LX_DLITERAL]
                }
................................................................................
            }
            set state(input) [string range $state(input) 1 end]
        }
    }

    if {[set x [lsearch -exact $state(tokenL) $c]] >= 0} {
        append state(buffer) $c

        return [set state(lastC) [lindex $state(lexemeL) $x]]
    }

    while 1 {
        append state(buffer) $c

        switch -- [set c [string index $state(input) 0]] {
            {} - " " - "\t" - "\n" {
                break
            }

            default {
                if {[lsearch -exact $state(tokenL) $c] >= 0} {
                    break
................................................................................
        }

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

    return [set state(lastC) LX_ATOM]
}


# ::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.
#
................................................................................
    variable encodings

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


# ::mime::reversemapencoding --
#
#    mime::reversemapencodings maps MIME charset types onto tcl encoding names.
#    Those that are unknown return {}.
#
# Arguments:
................................................................................

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


# ::mime::word_encode --
#
#    Word encodes strings as per RFC 2047.
#
# Arguments:
#       charset   The character set to encode the message to.
................................................................................
#    Returns a word encoded string.

proc ::mime::word_encode {charset method string {args}} {

    variable encodings

    if {![info exists encodings($charset)]} {
        error "unknown charset '$charset'"
    }

    if {$encodings($charset) eq {}} {
        error "invalid charset '$charset'"
    }

    if {$method ne "base64" && $method ne "quoted-printable"} {

        error "unknown method '$method', must be base64 or 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

    if {$options(-charset_encoded)} {
................................................................................
        return {}
    }

    set string_bytelength [string bytelength $unencoded_string]

    # the 7 is for =?, ?Q?, ?= delimiters of the encoded word
    set maxlength [expr {$options(-maxlength) - [string length $encodings($charset)] - 7}]
    switch -exact -- $method {
        base64 {
            if {$maxlength < 4} {

                error "maxlength $options(-maxlength) too short for chosen charset and encoding"
            }
            set count 0
            set maxlength [expr {($maxlength / 4) * 3}]
            while {$count < $string_length} {
                set length 0
                set enc_string {}
                while {$length < $maxlength && $count < $string_length} {
................................................................................
            # Trim off last "\n ", since the above code has the side-effect
            # of adding an extra "\n " to the encoded string.

            set result [string range $result 0 end-2]
        }
        quoted-printable {
            if {$maxlength < 1} {

                error "maxlength $options(-maxlength) too short for chosen charset and encoding"
            }
            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 "maxlength $options(-maxlength) too short for chosen charset and encoding"
                    }
                    if {
			$length + [string length $qp_enc_char] > $maxlength
		    } {
                        set length $maxlength
                    } else {
                        append encoded_word $qp_enc_char
................................................................................
        }
        default {
            error "Can't handle content encoding \"$method\""
        }
    }
    return $result
}


# ::mime::word_decode --
#
#    Word decodes strings that have been word encoded as per RFC 2047.
#
# Arguments:
#       encoded   The word encoded string to decode.
................................................................................
    }

    set enc [reversemapencoding $charset]
    if {$enc eq {}} {
        error "unknown charset '$charset'"
    }

    switch -exact -- $method {
        b -
        B {
            set method base64
        }
        q -
        Q {
            set method quoted-printable
        }
        default {
            error "unknown method '$method', must be B or Q"
        }
    }

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

    return [list $enc $method $result]
}


# ::mime::field_decode --
#
#    Word decodes strings that have been word encoded as per RFC 2047
#    and converts the string from the original encoding/charset to UTF.
#
# Arguments:
................................................................................
        }

        set decoded [word_decode $encoded]
        foreach {charset - string} $decoded break

        append result [::encoding convertfrom $charset $string]
    }

    append result $field
    return $result
}




















## One-Shot Initialization

::apply {{} {
    variable encList
    variable encAliasList
    variable reversemap







|













>







 







<
<


<
>







 







>


>







 







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







 







|





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

<
<
<
<
<
<
<
<
<
<
<
<
<
<
>








<











|
<


<


|

>
|


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

<
>
>




<

>
>

|
>
>



>
>

>




>
>









|

>
|


|
>
>
>
>
|
<
>

>
|
|
|
|

<
<
>
>



|
>
>







>


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

<
<
<
<
<
<
<
<
|
<
<







>







 







|













|


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





|







|












<
<
<
<
<
<
<
<
<

<



|





|


<
<
<




<













|
<
<
<

<
<
<
<
|
<
<
<
<
<
<












|

<

>

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

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










|













|







 







|
<
<
|
<
>
|
|
<
<
<

|







 







|





|







 







>



>
|



>






>
|





>




|
<
<





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







 







<





|







 







|




|
|






<

>

>
>
>
|

|

|







 







<
<

|


>
>
>







 







<


|







 







<











|



|






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

|




|


|













|

<

>
>


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

|
|
|

|
|

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

|







 







|
>

<

>
>

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







 







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


>




<
<
<
<










>
>
>
>
>
>
>
>
>







 







<

>







 







|







 







|







 







|







 







|

|
|







 







<







 







<







 







<

>

<
<

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>
>





<
<
<







|







 







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






|




<







 







>
>
>
|







 







|







 







<







 







|

<

>

>
>
|







 







|







 







|
>
>
>










>


<
>



|



|
<
|
|
|
|
|
|
<
<
<







 







|

|







 







|







 







<







 







<







 







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







 







|
>
>
>
>
|
>
|







<
|
<
<
<
|







 







>







 







>








|
|

|







 







|


|



<


<

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













>









|







 







|



|
|



<







 







>
|
>
>







 







>











|


<










|





|







|








|
|







|







 







>







 







<



|







 







|







 







>







 







<












|







 







>







 







<





|













|



|







 







>













|

<



|













|







 







>













<





|













|










>







 







<


|
|












|







 







>













<












|







 







>













<


|







 







>







 







>







 







|







 







|







 







>







 







|
>
>
|
<
|











|

<







 







|







 







|







 







|







 







<






|







 







>







 







>







 







>







 







|



|



>
|







 







|


>
|







 







>
|











>
|







 







>







 







|













|







 







>







 







>



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







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
..
65
66
67
68
69
70
71


72
73

74
75
76
77
78
79
80
81
..
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
...
313
314
315
316
317
318
319
320
321
322
323
324
325

326
327
328
329
330
331







332



333
334














335
336
337
338
339
340
341
342
343

344
345
346
347
348
349
350
351
352
353
354
355

356
357

358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388

389
390
391
392
393
394

395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435

436
437
438
439
440
441
442
443


444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462

463


464

465
466
467
468
469

470








471


472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
...
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586









587

588
589
590
591
592
593
594
595
596
597
598
599



600
601
602
603

604
605
606
607
608
609
610
611
612
613
614
615
616
617



618




619






620
621
622
623
624
625
626
627
628
629
630
631
632
633

634
635
636































































637
638


639
640
641
642



643
644







































645




646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
...
684
685
686
687
688
689
690
691


692

693
694
695



696
697
698
699
700
701
702
703
704
...
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
...
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
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
...
889
890
891
892
893
894
895

896
897
898
899
900
901
902
903
904
905
906
907
908
...
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
...
988
989
990
991
992
993
994


995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
....
1025
1026
1027
1028
1029
1030
1031

1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
....
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
1217
1218
1219
1220
1221
1222
1223
1224
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
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
1645
1646
1647
1648
1649
1650
....
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
1762
1763
1764




1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
....
1815
1816
1817
1818
1819
1820
1821

1822
1823
1824
1825
1826
1827
1828
1829
1830
....
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
....
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
....
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
....
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
....
2008
2009
2010
2011
2012
2013
2014

2015
2016
2017
2018
2019
2020
2021
....
2056
2057
2058
2059
2060
2061
2062

2063
2064
2065
2066
2067
2068
2069
....
2088
2089
2090
2091
2092
2093
2094

2095
2096
2097


2098
























2099
2100
2101
2102
2103
2104
2105



2106
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
....
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
....
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
....
2273
2274
2275
2276
2277
2278
2279

2280
2281
2282
2283
2284
2285
2286
....
2318
2319
2320
2321
2322
2323
2324
2325
2326

2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
....
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
....
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
....
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
....
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
....
2490
2491
2492
2493
2494
2495
2496

2497
2498
2499
2500
2501
2502
2503
....
2516
2517
2518
2519
2520
2521
2522

2523
2524
2525
2526
2527
2528
2529
....
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
....
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
....
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
....
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
....
2724
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
....
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804

2805
2806
2807
2808
2809
2810
2811
....
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
....
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
....
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
....
3002
3003
3004
3005
3006
3007
3008

3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
....
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
....
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
....
3120
3121
3122
3123
3124
3125
3126

3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
....
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
....
3176
3177
3178
3179
3180
3181
3182

3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
....
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258

3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
....
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305

3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
....
3344
3345
3346
3347
3348
3349
3350

3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
....
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
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
....
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
....
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
....
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
....
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
....
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
....
3710
3711
3712
3713
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
....
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
....
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
....
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
....
3859
3860
3861
3862
3863
3864
3865

3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
....
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
....
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
....
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
....
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
....
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
....
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
....
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
....
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
....
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
....
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
# (c) 2000      Dan Kuchler
# (c) 2000-2001 Eric Melski
# (c) 2001      Jeff Hobbs
# (c) 2001-2008 Andreas Kupries
# (c) 2002-2003 David Welton
# (c) 2003-2008 Pat Thoyts
# (c) 2005      Benjamin Riefenstahl
# (c) 2013-2018 PoorYorick
#
#
# See the file "license.terms" for information on usage and redistribution
# 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.5

package require tcl::chan::memchan
package require sha256

package provide mime 1.6

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

    # Fall-back to tcl-based procedures of base64 and quoted-printable encoders
    # Warning!
................................................................................
    unset ::major
}

#
# state variables:
#
#     canonicalP: input is in its canonical form


#     encoding: transfer encoding
#     version: MIME-version

#     header: dicttionary (keys are lower-case)
#     lowerL: list of header keys, lower-case
#     mixedL: list of header keys, mixed-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
................................................................................
#     string: input string
#
#     cid: last child-id assigned
#


namespace eval ::mime {

    variable mime
    array set mime {uid 0 cid 0}


    # RFC 822 lexemes
    variable addrtokenL
    lappend addrtokenL \; , < > : . ( ) @ \" \[ ] \\
    variable addrlexemeL {
        LX_SEMICOLON LX_COMMA
        LX_LBRACKET  LX_RBRACKET
................................................................................
        LX_COLON     LX_DOT
        LX_LPAREN    LX_RPAREN
        LX_ATSIGN    LX_QUOTE
        LX_LSQUARE   LX_RSQUARE
        LX_QUOTE
    }















    variable encList {
        ascii US-ASCII
        big5 Big5
        cp1250 Windows-1250
        cp1251 Windows-1251
        cp1252 Windows-1252
        cp1253 Windows-1253
................................................................................
        ksc5601 KSC5601
        ksc5601 korean
        shiftjis MS_Kanji
        utf-8 UTF8
    }

    namespace export {*}{
	copymessage finalize getbody header getproperty initialize
	mapencoding parseaddress parsedatetime reversemapencoding setheader
	uniqueID
    }
}



proc ::mime::contentid {} {
    set unique [uniqueID]
    return $unique@|
}












# ::mime::initialize --
#














#    the public interface for initializeaux

proc ::mime::initialize args {
    global errorCode errorInfo

    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 returnes 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} {
    global errorCode errorInfo
    # FRINK: nocheck

    upvar 0 $token state
    upvar 0 state(canonicalP) canonicalP
    upvar 0 state(params) params

    set params {}

    set state(hparams) {}
    set state(encoding) {}
    set state(version) 1.0

    set state(bodyparsed) 0
    set canonicalP 0
    set state(header) {}
    set state(headerparsed) 0
    set state(lowerL) {}
    set state(mixedL) {}

    set state(cid) 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 {
            -canonical {
		set canonicalP 1
		set type [string tolower $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
                #state(string) is needed, but will be built when required
                set state(string) {}
            }

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

    #We only want one of -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 {$canonicalP} {
        if {![header exists $token content-id]} {
	    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]} {
	    foreach {name hvalue} $headers {
		set lname [string tolower $name]
		if {$lname eq {content-type}} {
		    error [list {use -canonical instead of -headers} $hkey $name]
		}
		if {$lname eq {content-transfer-encoding}} {
		    error [list {use -encoding instead of -headers} $hkey $name]
		}
		if {$lname in {content-md5 mime-version}} {
		    error [list {don't go there...}]
		}
		header::setinternal $token $name $hvalue
	    }
	}

	lassign [header get $token content-type] content

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




    if {[set fileP [info exists state(file)]]} {
        if {[set openP [info exists state(root)]]} {
            # FRINK: nocheck

            upvar 0 $state(root) root

            set state(fd) $root(fd)
        } else {
            set state(root) $token
            set state(fd) [open $state(file) RDONLY]
            set state(offset) 0
            seek $state(fd) 0 end
            set state(count) [tell $state(fd)]

            fconfigure $state(fd) -translation binary
        }
    }
}















# ::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.
#
# Results:
#       Throws an error if it has problems parsing the MIME token,
#       otherwise it just sets up the appropriate variables.

proc ::mime::parsepartaux token {
    # FRINK: nocheck

    upvar 0 $token state
    upvar 0 state(last) last
































































    header parse $token
    if {![header exists $token content-type]} {


	header setinternal $token Content-Type text/plain [
	    dict create charset us-ascii]
    }




    lassign [header get $token content-type] 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 -string $strng
................................................................................
        }

        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
................................................................................
                # 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 {$forceoctet} {
                set ::errorInfo {}
                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 -lineslist $start
		    parsepart $child
                } cres copts]} {
                    set nochild 1
                    set state(parts) [lrange $state(parts) 0 end-1]
                }
            } else {
                mime::initializeaux $child -lineslist $start
		parsepart $child
            }
            set start {}
        }
        if {$forceoctet && !$nochild} {
	    header setinternal $child Content-Type application/octet-stream


        }
        set forceoctet 0
    }
}















































































































































# ::mime::finalize --
#
#   mime::finalize destroys a MIME part.
#
#   If the -subordinates option is present, it specifies which
#   subordinates should also be destroyed. The default value is
................................................................................
#              ?-subordinates "all" | "dynamic" | "none"?
#
# Results:
#       Returns an empty string.

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

    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]
                }
            }
................................................................................
#
#   The "parts" property is present only if the MIME part has
#   subordinates.
#
#   If mime::getproperty 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;
#   otherwise, a dictionary of properties is returned.
#
# Arguments:
#       token      The MIME token to parse.
#       property   One of 'content', 'encoding', 'params', 'parts', and
#                  'size'. Defaults to returning a dictionary of
#                  properties.
#
# Results:
#       Returns the properties of a MIME part

proc ::mime::getproperty {token {property {}}} {
    # FRINK: nocheck

    upvar 0 $token state
    parsepart $token


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

    switch $property {
        {} {
            array set properties [list content  $content \
                                       encoding $state(encoding) \
                                       params   $params \
                                       size     [getsize $token]]
            if {[info exists state(parts)]} {
                set properties(parts) $state(parts)
            }

            return [array get properties]
        }
................................................................................
            }

            return $names
        }

        content
            -


        params {
	    return [set $property]
        }

        encoding {
            return $state($property)
	}
        parts {
            if {![info exists state(parts)]} {
                error "MIME part is a leaf"
            }

            return $state(parts)
        }
................................................................................
#       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
	parse parse
	serialize serialize
	set set_
	setinternal setinternal
    }

    variable tchar
    # hypen is first for inclusion in brackets
    variable tchar_re {-!#$%&'*+.^`|~0-9A-Za-z}
    variable token_re "^(\[$tchar_re]*)\\s*(?:;|$)?"
    variable notattchar_re "\[^[string map {* {} ' {} % {}} $tchar_re]]"

    # RFC 2045 lexemes
    variable typetokenL
    lappend typetokenL \; , < > : ? ( ) @ \" \[ ] = / \\
    variable typelexemeL {
        LX_SEMICOLON LX_COMMA
        LX_LBRACKET  LX_RBRACKET
        LX_COLON     LX_QUESTION
        LX_LPAREN    LX_RPAREN
        LX_ATSIGN    LX_QUOTE
        LX_LSQUARE   LX_RSQUARE
        LX_EQUALS    LX_SOLIDUS
        LX_QUOTE
    }

    variable internal 0
}


proc ::mime::header::boundary {} {
    return [uniqueID]
}


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]
    dict exists $state(header) $lname
}


# ::mime::header get --
#
#    [mime::header get] returns the header of a MIME part.
#
#    A header consists of zero or more key/value pairs. Each value is a
#    list containing one or more strings.
#
#    If [mime::header get] is invoked with the name of a specific key, then
#    a list containing the corresponding value(s) is returned; instead,
#    if -names is specified, a list of all keys is returned; otherwise, a
#    dictionary is returned. Note that when a
#    key is specified (e.g., "Subject"), the list returned usually
#    contains exactly one string; however, some keys (e.g., "Received")
#    often occur more than once in the header, accordingly the list
#    returned usually contains more than one string.
#
# Arguments:
#       token      The MIME token to parse.
#       key        Either a key or '-names'.  If it is '-names' a list
#                  of all keys is returned.
#
# Results:
#       Returns the header of a MIME part.

proc ::mime::header::get {token {key {}}} {
    # FRINK: nocheck

    upvar 0 $token state
    upvar 0 state(hparams) hparams
    parse $token

    array set header $state(header)
    switch $key {
	{} {
	    set result {}
	    lappend result MIME-Version [list $state(version) {}]
	    foreach lower $state(lowerL) mixed $state(mixedL) {
		foreach value $header($lower) hparam [
		    dict get $hparams $lower] {
		    lappend result $mixed [list $value $hparam]
		}
	    }
	    set tencoding [getTransferEncoding $token]
	    if {$tencoding ne {}} {
		lappend result Content-Transfer-Encoding [list $tencoding {}]
	    }
	    return $result
	}

	-names {
	    return $state(mixedL)
	}

	default {
	    set lower [string tolower $key]

	    switch $lower {
		content-transfer-encoding {
		    return [list [getTransferEncoding $token] {}]
		}
		mime-version {
		    return [list $state(version) {}]
		}
		default {
		    if {![info exists header($lower)]} {
			error "key $key not in header"
		    }
		    return [list $header($lower) [lindex [
			dict get $hparams $lower] end]]
		}
	    }
	}
    }
}


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

	# there is a space and a tab between the brackets in next line
        if {!$blankP && [string match {[ 	]*} $line]} {
            append vline { } [string trimleft $line " \t"]
            continue
        }

        if {$vline eq {}} {
            if {$blankP} {
                break
            }

            set vline $line
            continue
        }

        if {
	    [set x [string first : $vline]] <= 0
	    ||
	    [set mixed [string trimright [
		string range $vline 0 [expr {$x - 1}]]]] eq {}
	} {
            error [list {improper line in header} $vline]
        }
        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]
		setinternal $token Content-Type {*}$x
            }

            content-md5 {
            }

            content-transfer-encoding {
                if {
		    $state(encoding) ne {}
		    &&
		    $state(encoding) ne [string tolower $value]
		} {
                    error [list [list multiple Content-Transfer-Encoding \
			fields starting with] $vline]
                }

                set state(encoding) [string tolower $value]
            }

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

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

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


proc ::mime::header::parseparams token {
    # FRINK: nocheck
    upvar 0 $token state
    set params {}

    while 1 {
        switch [parselexeme $token] {
            LX_END {
		return [processparams $params[set params {}]]
            }

	    LX_SEMICOLON {
		if {[dict size $params]} {
		    continue
		} else {
		    error [list {expecting attribute} not $state(buffer)]
		}
	    }

            LX_ATOM {
            }

            default {
                error [list {expecting attribute} not $state(buffer)]
            }
        }

        set attribute [string tolower $state(buffer)]

        if {[parselexeme $token] ne {LX_EQUALS}} {
            error [list expecting = found  $state(buffer)]
        }

        switch [parselexeme $token] {
            LX_ATOM {
            }

            LX_QSTRING {
                set state(buffer) [
                    string range $state(buffer) 1 [
                        expr {[string length $state(buffer)] - 2}]]
            }

            default {
                error [list expecting value found $state(buffer)]
            }
        }
        dict set params $attribute $state(buffer)
    }
}


proc ::mime::header::parseparts {token value} {
    variable token_re
    upvar 0 $token state

    if {![regexp $token_re $value match type]} {
	error [list {expected disposition-type}]
    }

    variable typetokenL
    variable typelexemeL

    set value [string range $value[set value {}] [string length $match] end]

    set state(input)   $value
    set state(buffer)  {}
    set state(lastC)   LX_END
    set state(comment) {}
    set state(tokenL)  $typetokenL
    set state(lexemeL) $typelexemeL

    set code [catch {parseparams $token} result copts]

    unset {*}{
	state(input)
	state(buffer)
	state(lastC)
	state(comment)
	state(tokenL)
	state(lexemeL)
    }

    return -options $copts [list $type $result]
}


# ::mime::header::parsetype --
#
#       Parses the string passed in and identifies the content-type and
#       params strings.
#
# Arguments:
#       token  The MIME token to parse.
#       string The content-type string that should be parsed.
#
# Results:
#       Returns the content and params for the string as a two element
#       tcl list.

proc ::mime::header::parsetype {token string} {
    global errorCode errorInfo
    # FRINK: nocheck
    upvar 0 $token state

    variable typetokenL
    variable typelexemeL

    set state(input)   $string
    set state(buffer)  {}
    set state(lastC)   LX_END
    set state(comment) {}
    set state(tokenL)  $typetokenL
    set state(lexemeL) $typelexemeL

    set code [catch {parsetypeaux $token} result]
    set ecode $errorCode
    set einfo $errorInfo

    unset {*}{
	state(input)
	state(buffer)
	state(lastC)
	state(comment)
	state(tokenL)
	state(lexemeL)
    }

    return -code $code -errorinfo $einfo -errorcode $ecode $result
}

# ::mime::header::parsetypeaux --
#
#       A helper function for mime::parsetype.  Parses the specified
#       string looking for the content type and params.
#
# Arguments:
#       token  The MIME token to parse.
#       string The content-type string that should be parsed.
#
# Results:
#       Returns the content and params for the string as a two element
#       tcl list.

proc ::mime::header::parsetypeaux token {
    # FRINK: nocheck
    upvar 0 $token state
    set params {}

    if {[parselexeme $token] ne {LX_ATOM}} {
        error [list expecting type found $state(buffer)]
    }
    set type [string tolower $state(buffer)]

    switch [parselexeme $token] {
        LX_SOLIDUS {
        }

        LX_END {
            if {$type ne {message}} {
                error [list expecting type/subtype found $type]
            }

            return [list message/rfc822 {}]
        }

        default {
            error [list expecting / found  $state(buffer)]
        }
    }

    if {[parselexeme $token] ne {LX_ATOM}} {
        error [list expecting subtype found $state(buffer)]
    }
    append type [string tolower /$state(buffer)]

    switch [parselexeme $token] {
	LX_END {
	}

	LX_SEMICOLON {
	    set params [parseparams $token]
	}

	default {
	    error [list expecting  {;  or end} found $state(buffer)]
	}
    }

    list $type $params
}


proc ::mime::header::processparams params {
    set info {}
    foreach key [lsort -dictionary [dict keys $params]] {
	set pvalue [dict get $params $key]
	# a trailing asterisk is ignored if this is not the first field in an
	# identically-named series

	# this expression can't fail
	regexp {^([^*]+?)(?:([*])([0-9]+))?([*])?$} $key -> name star1 counter star2
	dict update info $name dict1 {
	    if {![info exists dict1]} {
		set dict1 {}
	    }
	    dict update dict1 encoding encoding value value {
		if {$star1 ne {}} {
		    if {$star2 ne {} || $counter eq {}} {
			if {![regexp {^([^']*)'([^']*)'(.*)$} $pvalue \
			    -> charset lang pvalue]} {

			    error [list [list malformed language information in \
				extended parameter name]]
			}
			if {$charset ne {}} {
			    set encoding [reversemapencoding $charset]
			}
		    }
		}
		append value $pvalue
	    }
	}
    }

    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:
#
#       write: the key/value is either created or overwritten (the
#       default);
#
................................................................................
#       value      The value for the header key to be set to.
#       args       An optional argument of the form:
#                  ?-mode "write" | "append" | "delete"?
#
# 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(hparams) hparams
    parse $token



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




	0 - 2 {
	    # carry on



	}
	default {
	    error [list {wrong # args}]
	}
    }
    array set options [list -mode write]
    array set options $args

    set lower [string tolower $key]
    array set header $state(header)
    if {[set x [lsearch -exact $state(lowerL) $lower]] < 0} {
        #TODO: this code path is not tested
        if {$options(-mode) eq "delete"} {
            error "key $key not in header"
        }

................................................................................
        lappend state(lowerL) $lower
        lappend state(mixedL) $key

        set result {}
    } else {
        set result $header($lower)
    }
    switch $options(-mode) {
	append - write {
	    switch $lower {
		content-md5
		    -
		content-transfer-encoding
		    -
		mime-version
		    -
		content-type {
		    if {!$internal} {
			switch $lower {
			    content-type {
				error [list key $key {may not be set} \
				    {use -params instead}]
			    }
			    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]
				&&
				![dict exists $params boundary]
			    } {
				dict set params boundary [boundary]
			    }
			} 
			default {
			    #carry on
			}
		    }
		}
	    }
	    switch $options(-mode) {
		append {
		    lappend header($lower) $value
		    dict lappend hparams $lower $params
		}
		write {
		    set header($lower) [list $value]
		    dict set hparams $lower [list $params]
		}
	    }
	}
        delete {
            unset header($lower)
	    unset hparams($lower)
            set state(lowerL) [lreplace $state(lowerL) $x $x]
            set state(mixedL) [lreplace $state(mixedL) $x $x]
        }





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

    set state(header) [array get header]

    return $result
}


proc ::mime::header::setinternal args {
    variable internal 1
    try {
	set_ {*}$args
    } finally {
	set internal 0
    }
}
# ::mime::getbody --
#
#    mime::getbody 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:
#
................................................................................
#       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::getbody {token args} {
    global errorCode errorInfo
    # FRINK: nocheck

    upvar 0 $token state
    parsepart $token

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

................................................................................
        error "-blocksize expects a positive integer, not $options(-blocksize)"
    }

    set code 0
    set ecode {}
    set einfo {}

    switch $state(value)/$state(canonicalP) {
        file/0 {
            set fd [open $state(file) RDONLY]

            set code [catch {
                fconfigure $fd -translation binary
                seek $fd [set pos $state(offset)] start
                set last [expr {$state(offset) + $state(count) - 1}]
................................................................................
                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
................................................................................
        parts/1 {
            error "MIME part isn't a leaf"
        }

        string/0
            -
        string/1 {
            switch $state(encoding)/$state(canonicalP) {
                base64/0
                    -
                quoted-printable/0 {
                    set fragment [
                        $state(encoding) -mode decode -- $state(string)]
                }

................................................................................
    set einfo $errorInfo

    if {$code} {
        return -code $code -errorinfo $einfo -errorcode $ecode $result
    }

    if {$decode} {
        set params [mime::getproperty $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 {}} {
            set result [::encoding convertfrom $enc $result]
................................................................................
#       Returns nothing, except when called with the 'end' argument
#       in which case it returns a string that contains all of the
#       data that 'getbodyaux' has been called with.  Will throw an
#       error if it is called with the reason of 'error'.

proc ::mime::getbodyaux {token reason {fragment {}}} {
    # FRINK: nocheck

    upvar 0 $token state

    switch $reason {
        data {
            append state(getbody) $fragment
            return {}
        }
................................................................................
# Results:
#       Returns nothing unless an error is thrown while the message
#       is being written to the channel.

proc ::mime::copymessage {token channel} {
    global errorCode errorInfo
    # FRINK: nocheck

    upvar 0 $token state

    set openP [info exists state(fd)]

    set code [catch {mime::copymessageaux $token $channel} result]
    set ecode $errorCode
    set einfo $errorInfo
................................................................................
#
# Results:
#       Returns nothing unless an error is thrown while the message
#       is being written to the channel.

proc ::mime::copymessageaux {token channel} {
    # FRINK: nocheck

    upvar 0 $token state
    parsepart $token



    set result {}
























    foreach {mixed value} [header get $token] {
	puts $channel [header serialize $token $mixed {*}$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 {
            set closeP 1
            if {[info exists state(root)]} {
                # FRINK: nocheck

                upvar 0 $state(root) root

                if {[info exists root(fd)]} {
                    set fd $root(fd)
                    set closeP 0
                } else {
                    set fd [set state(fd) [open $state(file) RDONLY]]
................................................................................
		&&
		[info exists state(file)]
	    } {
                set state(fd) [open $state(file) RDONLY]
                fconfigure $state(fd) -translation binary
            }

	    lassign [header get $token content-type] content params
	    set boundary [dict get $params boundary]

            switch -glob $content {
                message/* {
                    puts $channel {}
                    foreach part $state(parts) {
                        mime::copymessage $part $channel
                        break
                    }
                }
................................................................................
                    # 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::copymessage $part $channel
                    }
................................................................................
#
# Results:
#       The message. 

proc ::mime::buildmessage token {
    global errorCode errorInfo
    # FRINK: nocheck

    upvar 0 $token state

    set openP [info exists state(fd)]

    set code [catch {mime::buildmessageaux $token} result]
    if {![info exists errorCode]} {
        set ecode {}
................................................................................
# 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 [header get $token content-type] content

    switch -glob $content {
        audio/*
            -
        image/*
            -
        video/* {
            return base64
        }
................................................................................
            return {}
        }
        default {# Skip}
    }

    set asciiP 1
    set lineP 1
    switch $state(value) {
        file {
            set fd [open $state(file) RDONLY]
            fconfigure $fd -translation binary

            while {[gets $fd line] >= 0} {
                if {$asciiP} {
                    set asciiP [encodingasciiP $line]
................................................................................
        }

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

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

................................................................................
# Arguments:
#
# Results:
#

proc ::mime::fcopy {token count {error {}}} {
    # FRINK: nocheck

    upvar 0 $token state

    if {$error ne {}} {
        set state(error) $error
    }
    set state(doneP) 1
}
................................................................................
#
# Results:
#    The specified portion of the string in the mime token is
#       copied to the specified channel.

proc ::mime::scopy {token channel offset len blocksize} {
    # FRINK: nocheck

    upvar 0 $token state

    if {$len <= 0} {
        set state(doneP) 1
        fileevent $channel writable {}
        return
    }
................................................................................
    } {
        set state(error) $result
        set state(doneP) 1
        fileevent $channel writable {}
    }
    return
}


proc ::mime::parsepart token {
    upvar 0 $token state
    if {$state(canonicalP) || $state(bodyparsed)} {
	return
    }
    set state(bodyparsed) 1
    global errorCode errorInfo
    set code [catch {parsepartaux $token} result]
    set ecode $errorCode
    set einfo $errorInfo

    if {[info exists state(file)]} {
        if {![info exists state(root)]} {
            unset state(root)
            catch {close $state(fd)}
        }
	unset state(fd)
    }
    return -code $code -errorinfo $einfo -errorcode $ecode $result
}


# ::mime::qp_encode --
#
#    Tcl version of quote-printable encode
#
# Arguments:
#    string        The string to quote.
................................................................................

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

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

    # process \u unicode mapped chars

    return [subst -novariables -nocommands $string]
}


# ::mime::parseaddress --
#
#       This was originally written circa 1982 in C. we're still using it
#       because it recognizes virtually every buggy address syntax ever
#       generated!
#
#       mime::parseaddress takes a string containing one or more 822-style
#       address specifications and returns a list of dictionaries, for each
#       address specified in the argument.
#
#    Each dictionary contains these properties:
#
#       property    value
#       ========    =====
#       address     local@domain
#       comment     822-style comment
#       domain      the domain part (rhs)
#       error       non-empty on a parse error
................................................................................
#
#    Note that one or more of these properties may be empty.
#
# Arguments:
#    string        The address string to parse
#
# Results:
#    Returns a list of dictionaries, one element for each address
#       specified in the argument.

proc ::mime::parseaddress {string args} {
    global errorCode errorInfo

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

    set code [catch {mime::parseaddressaux $token $string} result]
    set ecode $errorCode
    set einfo $errorInfo

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

    return -code $code -errorinfo $einfo -errorcode $ecode $result
}


# ::mime::parseaddressaux --
#
#       This was originally written circa 1982 in C. we're still using it
#       because it recognizes virtually every buggy address syntax ever
#       generated!
#
#       mime::parseaddressaux does the actually parsing for mime::parseaddress
#
#    Each dictionary contains these properties:
#
#       property    value
#       ========    =====
#       address     local@domain
#       comment     822-style comment
#       domain      the domain part (rhs)
#       error       non-empty on a parse error
................................................................................
#       phrase      the phrase part
#       proper      822-style address specification
#       route       822-style route specification (obsolete)
#
#    Note that one or more of these properties may be empty.
#
# Arguments:
#    token         The MIME token to work from.
#    string        The address string to parse
#
# Results:
#    Returns a list of dictionaries, one for each address specified in the
#    argument.

proc ::mime::parseaddressaux {token string} {
    # FRINK: nocheck

    upvar 0 $token state

    variable addrtokenL
    variable addrlexemeL

    set state(input)   $string
    set state(glevel)  0
................................................................................
    set state(lexemeL) $addrlexemeL

    set result {}
    while {[addr_next $token]} {
        if {[set tail $state(domain)] ne {}} {
            set tail @$state(domain)
        } else {
			if {![info exists state(default_host)]} {
				set state(default_host) [info hostname]
			}
            set tail @$state(default_host)
        }
        if {[set address $state(local)] ne {}} {
            #TODO: this path is not covered by tests
            append address $tail
        }

        if {$state(phrase) ne {}} {
................................................................................
	state(lastC)
	state(tokenL)
	state(lexemeL)
    }

    return $result
}


# ::mime::addr_next --
#
#       Locate the next address in a mime token.
#
# Arguments:
#       token         The MIME token to work from.
#
# Results:
#    Returns 1 if there is another address, and 0 if there is not.

proc ::mime::addr_next token {
    global errorCode errorInfo
    # FRINK: nocheck

    upvar 0 $token state
    set nocomplain [package vsatisfies [package provide Tcl] 8.4]
    foreach prop {comment domain error group local memberP phrase route} {
        if {$nocomplain} {
            unset -nocomplain state($prop)
        } else {
            if {[catch {unset state($prop)}]} {set ::errorInfo {}}
        }
    }

    switch [set code [catch {mime::addr_specification $token} result]] {
        0 {
            if {!$result} {
                return 0
            }

            switch $state(lastC) {
                LX_COMMA
                    -
                LX_END {
                }
                default {
                    # catch trailing comments...
                    set lookahead $state(input)
                    parselexeme $token
                    set state(input) $lookahead
                }
            }
        }

        7 {
            set state(error) $result

            while 1 {
                switch $state(lastC) {
                    LX_COMMA
                        -
                    LX_END {
                        break
                    }

                    default {
                        parselexeme $token
                    }
                }
            }
        }

        default {
            set ecode $errorCode
................................................................................
        if {![info exists state($prop)]} {
            set state($prop) {}
        }
    }

    return 1
}


# ::mime::addr_specification --
#
#   Uses lookahead parsing to determine whether there is another
#   valid e-mail address or not.  Throws errors if unrecognized
#   or invalid e-mail address syntax is used.
#
................................................................................
#       token         The MIME token to work from.
#
# Results:
#    Returns 1 if there is another address, and 0 if there is not.

proc ::mime::addr_specification {token} {
    # FRINK: nocheck

    upvar 0 $token state

    set lookahead $state(input)
    switch [parselexeme $token] {
        LX_ATOM
            -
        LX_QSTRING {
            set state(phrase) $state(buffer)
        }

        LX_SEMICOLON {
................................................................................
        default {
            return -code 7 [
		format "unexpected character at beginning (found %s)" \
		   $state(buffer)]
        }
    }

    switch [parselexeme $token] {
        LX_ATOM
            -
        LX_QSTRING {
            append state(phrase) " " $state(buffer)

            return [addr_phrase $token]
        }
................................................................................
            return -code 7 [
                format "expecting mailbox (found %s)" $state(buffer)]
        }
    }

    return 1
}


# ::mime::addr_routeaddr --
#
#       Parses the domain portion of an e-mail address.  Finds the '@'
#       sign and then calls mime::addr_route to verify the domain.
#
# Arguments:
................................................................................
#       token         The MIME token to work from.
#
# Results:
#    Returns 1 if there is another address, and 0 if there is not.

proc ::mime::addr_routeaddr {token {checkP 1}} {
    # FRINK: nocheck

    upvar 0 $token state

    set lookahead $state(input)
    if {[parselexeme $token] eq "LX_ATSIGN"} {
        #TODO: this path is not covered by tests
        mime::addr_route $token
    } else {
        set state(input) $lookahead
    }

    mime::addr_local $token

    switch $state(lastC) {
        LX_ATSIGN {
            mime::addr_domain $token
        }

        LX_SEMICOLON
            -
        LX_RBRACKET
................................................................................
    if {($checkP) && ($state(lastC) ne "LX_RBRACKET")} {
        return -code 7 [
            format "expecting right-bracket (found %s)" $state(buffer)]
    }

    return 1
}


# ::mime::addr_route --
#
#    Attempts to parse the portion of the e-mail address after the @.
#    Tries to verify that the domain definition has a valid form.
#
# Arguments:
................................................................................
#
# Results:
#    Returns nothing if successful, and throws an error if invalid
#       syntax is found.

proc ::mime::addr_route {token} {
    # FRINK: nocheck

    upvar 0 $token state

    set state(route) @

    while 1 {
        switch [parselexeme $token] {
            LX_ATOM
                -
            LX_DLITERAL {
                append state(route) $state(buffer)
            }

            default {
                return -code 7 \
                       [format "expecting sub-route in route-part (found %s)" \
                               $state(buffer)]
            }
        }

        switch [parselexeme $token] {
            LX_COMMA {
                append state(route) $state(buffer)
                while 1 {
                    switch [parselexeme $token] {
                        LX_COMMA {
                        }

                        LX_ATSIGN {
                            append state(route) $state(buffer)
                            break
                        }
................................................................................
                return -code 7 [
		    format "expecting colon to terminate route (found %s)" \
			$state(buffer)]
            }
        }
    }
}


# ::mime::addr_domain --
#
#    Attempts to parse the portion of the e-mail address after the @.
#    Tries to verify that the domain definition has a valid form.
#
# Arguments:
#       token         The MIME token to work from.
#
# Results:
#    Returns nothing if successful, and throws an error if invalid
#       syntax is found.

proc ::mime::addr_domain token {
    # FRINK: nocheck

    upvar 0 $token state

    while 1 {
        switch [parselexeme $token] {
            LX_ATOM
                -
            LX_DLITERAL {
                append state(domain) $state(buffer)
            }

            default {
                return -code 7 [
		    format "expecting sub-domain in domain-part (found %s)" \
			$state(buffer)]
            }
        }

        switch [parselexeme $token] {
            LX_DOT {
                append state(domain) $state(buffer)
            }

            LX_ATSIGN {
                append state(local) % $state(domain)
                unset state(domain)
................................................................................

            default {
                return
            }
        }
    }
}


# ::mime::addr_local --
#
#
# Arguments:
#       token         The MIME token to work from.
#
# Results:
#    Returns nothing if successful, and throws an error if invalid
#       syntax is found.

proc ::mime::addr_local {token} {
    # FRINK: nocheck

    upvar 0 $token state

    set state(memberP) $state(glevel)

    while 1 {
        switch [parselexeme $token] {
            LX_ATOM
                -
            LX_QSTRING {
                append state(local) $state(buffer)
            }

            default {
                return -code 7 \
                       [format "expecting mailbox in local-part (found %s)" \
                               $state(buffer)]
            }
        }

        switch [parselexeme $token] {
            LX_DOT {
                append state(local) $state(buffer)
            }

            default {
                return
            }
        }
    }
}


# ::mime::addr_phrase --
#
#
# Arguments:
#       token         The MIME token to work from.
#
................................................................................
# Results:
#    Returns nothing if successful, and throws an error if invalid
#       syntax is found.


proc ::mime::addr_phrase {token} {
    # FRINK: nocheck

    upvar 0 $token state

    while 1 {
        switch [parselexeme $token] {
            LX_ATOM
                -
            LX_QSTRING {
                append state(phrase) " " $state(buffer)
            }

            default {
                break
            }
        }
    }

    switch $state(lastC) {
        LX_LBRACKET {
            return [addr_routeaddr $token]
        }

        LX_COLON {
            return [addr_group $token]
        }
................................................................................
        default {
            return -code 7 [
		format "found phrase instead of mailbox (%s%s)" \
		    $state(phrase) $state(buffer)]
        }
    }
}


# ::mime::addr_group --
#
#
# Arguments:
#       token         The MIME token to work from.
#
# Results:
#    Returns nothing if successful, and throws an error if invalid
#       syntax is found.

proc ::mime::addr_group {token} {
    # FRINK: nocheck

    upvar 0 $token state

    if {[incr state(glevel)] > 1} {
        return -code 7 [
	    format "nested groups not allowed (found %s)" $state(phrase)]
    }

    set state(group) $state(phrase)
    unset state(phrase)

    set lookahead $state(input)
    while 1 {
        switch [parselexeme $token] {
            LX_SEMICOLON
                -
            LX_END {
                set state(glevel) 0
                return 1
            }

................................................................................
            default {
                set state(input) $lookahead
                return [addr_specification $token]
            }
        }
    }
}


# ::mime::addr_end --
#
#
# Arguments:
#       token         The MIME token to work from.
#
# Results:
#    Returns nothing if successful, and throws an error if invalid
#       syntax is found.

proc ::mime::addr_end {token} {
    # FRINK: nocheck

    upvar 0 $token state

    switch $state(lastC) {
        LX_SEMICOLON {
            if {[incr state(glevel) -1] < 0} {
                return -code 7 "extraneous semi-colon"
            }
        }

        LX_COMMA
................................................................................

        default {
            return -code 7 [
		format "junk after local@domain (found %s)" $state(buffer)]
        }
    }
}


# ::mime::addr_x400 --
#
#
# Arguments:
#       token         The MIME token to work from.
#
................................................................................

    if {[set x [string first / $mbox]] > 0} {
        set mbox [string range $mbox 0 [expr {$x - 1}]]
    }

    return [string trim $mbox \"]
}


# ::mime::parsedatetime --
#
#    Fortunately the clock command in the Tcl 8.x core does all the heavy
#    lifting for us (except for timezone calculations).
#
#    mime::parsedatetime takes a string containing an 822-style date-time
................................................................................
            }
            incr clock $zone
        }
    } else {
        set clock [clock scan $value]
    }

    switch $property {
        clock {
            return $clock
        }

        hour {
            set value [clock format $clock -format %H]
        }
................................................................................

        zone {
            set value [string trim [string map [list \t { }] $value]]
            if {[set x [string last { } $value]] < 0} {
                return 0
            }
            set value [string range $value [expr {$x + 1}] end]
            switch [set s [string index $value 0]] {
                + - - {
                    if {$s eq "+"} {
                        #TODO: This path is not covered by tests
                        set s {}
                    }
                    set value [string trim [string range $value 1 end]]
                    if {(
................................................................................

    if {[set value [string trimleft $value 0]] eq {}} {
        #TODO: this path is not covered by tests
        set value 0
    }
    return $value
}


# ::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.
#
................................................................................
# Arguments:
#
# Results:
#    Returns the a string that contains the globally unique identifier
#       that should be used for the Content-ID of an e-mail message.

proc ::mime::uniqueID {} {
    set id [base64 -mode encode -- [
	sha2::sha256 -bin [expr {rand()}][pid][clock clicks][array get state]]]
    return $id 
}



# ::mime::parselexeme --
#
#    Used to implement a lookahead parser.
#
# Arguments:
#       token    The MIME token to operate on.
#
# Results:
#    Returns the next token found by the parser.

proc ::mime::parselexeme token {
    # FRINK: nocheck

    upvar 0 $token state

    set state(input) [string trimleft $state(input)]

    set state(buffer) {}
    if {$state(input) eq {}} {
        set state(buffer) end-of-input
................................................................................
        set noteP 0
        set quoteP 0

        while 1 {
            append state(buffer) $c

            #TODO: some of these paths are not covered by tests
            switch $c/$quoteP {
                (/0 {
                    incr noteP
                }

                \\/0 {
                    set quoteP 1
                }
................................................................................
    if {$c eq "\""} {
        set firstP 1
        set quoteP 0

        while 1 {
            append state(buffer) $c

            switch $c/$quoteP {
                "\\/0" {
                    set quoteP 1
                }

                "\"/0" {
                    if {!$firstP} {
                        return [set state(lastC) LX_QSTRING]
................................................................................

    if {$c eq {[}} {
        set quoteP 0

        while 1 {
            append state(buffer) $c

            switch $c/$quoteP {
                \\/0 {
                    set quoteP 1
                }

                ]/0 {
                    return [set state(lastC) LX_DLITERAL]
                }
................................................................................
            }
            set state(input) [string range $state(input) 1 end]
        }
    }

    if {[set x [lsearch -exact $state(tokenL) $c]] >= 0} {
        append state(buffer) $c

        return [set state(lastC) [lindex $state(lexemeL) $x]]
    }

    while 1 {
        append state(buffer) $c

        switch [set c [string index $state(input) 0]] {
            {} - " " - "\t" - "\n" {
                break
            }

            default {
                if {[lsearch -exact $state(tokenL) $c] >= 0} {
                    break
................................................................................
        }

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

    return [set state(lastC) LX_ATOM]
}


# ::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.
#
................................................................................
    variable encodings

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


# ::mime::reversemapencoding --
#
#    mime::reversemapencodings maps MIME charset types onto tcl encoding names.
#    Those that are unknown return {}.
#
# Arguments:
................................................................................

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


# ::mime::word_encode --
#
#    Word encodes strings as per RFC 2047.
#
# Arguments:
#       charset   The character set to encode the message to.
................................................................................
#    Returns a word encoded string.

proc ::mime::word_encode {charset method string {args}} {

    variable encodings

    if {![info exists encodings($charset)]} {
        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

    if {$options(-charset_encoded)} {
................................................................................
        return {}
    }

    set string_bytelength [string bytelength $unencoded_string]

    # the 7 is for =?, ?Q?, ?= delimiters of the encoded word
    set maxlength [expr {$options(-maxlength) - [string length $encodings($charset)] - 7}]
    switch -exact $method {
        base64 {
            if {$maxlength < 4} {
                error [list maxlength $options(-maxlength) \
		    {too short for chosen charset and encoding}]
            }
            set count 0
            set maxlength [expr {($maxlength / 4) * 3}]
            while {$count < $string_length} {
                set length 0
                set enc_string {}
                while {$length < $maxlength && $count < $string_length} {
................................................................................
            # Trim off last "\n ", since the above code has the side-effect
            # of adding an extra "\n " to the encoded string.

            set result [string range $result 0 end-2]
        }
        quoted-printable {
            if {$maxlength < 1} {
                error [list maxlength $options(-maxlength) \
		    {too short for chosen charset and encoding}]
            }
            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
		    } {
                        set length $maxlength
                    } else {
                        append encoded_word $qp_enc_char
................................................................................
        }
        default {
            error "Can't handle content encoding \"$method\""
        }
    }
    return $result
}


# ::mime::word_decode --
#
#    Word decodes strings that have been word encoded as per RFC 2047.
#
# Arguments:
#       encoded   The word encoded string to decode.
................................................................................
    }

    set enc [reversemapencoding $charset]
    if {$enc eq {}} {
        error "unknown charset '$charset'"
    }

    switch -exact $method {
        b -
        B {
            set method base64
        }
        q -
        Q {
            set method quoted-printable
        }
        default {
            error "unknown method '$method', must be B or Q"
        }
    }

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

    return [list $enc $method $result]
}


# ::mime::field_decode --
#
#    Word decodes strings that have been word encoded as per RFC 2047
#    and converts the string from the original encoding/charset to UTF.
#
# Arguments:
................................................................................
        }

        set decoded [word_decode $encoded]
        foreach {charset - string} $decoded break

        append result [::encoding convertfrom $charset $string]
    }

    append result $field
    return $result
}

namespace eval ::mime::header {
    ::apply [list {} {
	set saved [namespace eval [namespace parent] {
	    namespace export
	}]
	namespace eval [namespace parent] {
	    namespace export *
	}
	namespace import [namespace parent]::getTransferEncoding
	namespace import [namespace parent]::parselexeme
	namespace import [namespace parent]::reversemapencoding
	namespace import [namespace parent]::uniqueID
	namespace eval [namespace parent] [
	    list namespace export -clear {*}$saved
	]
    } [namespace current]]
}


## One-Shot Initialization

::apply {{} {
    variable encList
    variable encAliasList
    variable reversemap

Changes to modules/mime/mime.test.

1
2
3
4
5
6
7
8
9
10
11
12
..
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
...
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
...
138
139
140
141
142
143
144

145
146
147
148
149
150
151

152
153


154
155
156
157
158
159
160
...
163
164
165
166
167
168
169
170

171
172
173
174
175
176
177
178
179
180
181

182
183
184
185
186
187
188
189
190
191
192

193
194
195
196
197
198
199
200
201
202
203

204
205
206
207
208
209
210
211
212
213

214
215
216
217
218
219
220
221
222
223

224
225
226
227
228
229
230
231
232
233
234

235
236
237
238
239
240
241
242
243
244

245
246
247
248
249

250
251
252
253
254
255
256

257
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
...
362
363
364
365
366
367
368
369

370
371
372
373

374
375
376
377

378
379
380
381

382
383
384
385

386
387
388
389

390
391
392
393

394
395
396
397
398

399
400
401
402
403

404
405
406
407

408

409
410
411
412
413

414
415
416
417
418

419
420
421
422

423
424
425
426
427
428
429

430
431
432
433

434
435
436
437

438
439
440
441

442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469

470
471
472
473
474
475
476
477
478
479
480
481
482
483

484
485
486
487
488

489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
...
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
...
572
573
574
575
576
577
578
579
580
581
582
583

584
585
586
587
588

589
590
591
592
593
594
595
...
596
597
598
599
600
601
602
603

604
605
606
607
608
609
610
...
616
617
618
619
620
621
622
623




















































































624
625
# mime.test - Test suite for TclMIME                     -*- tcl -*-
#
# This file contains a collection of tests for one or more of the Tcl
# built-in commands.  Sourcing this file into Tcl runs the tests and
# generates output for errors.  No output means no errors were found.
#
# Copyright (c) 2000 by Ajuba Solutions
# All rights reserved.
#
# RCS: @(#) $Id: mime.test,v 1.31 2012/02/23 17:35:17 andreas_kupries Exp $

# -------------------------------------------------------------------------
................................................................................
}

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

namespace import mime::*

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


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


test mime-2.1 {Generate a MIME message} {
    set tok [initialize -canonical "Text/plain" -string "jack and jill"]
    set msg [mime::buildmessage $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


test mime-2.2 {Generate a multi-part MIME message} {
    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 \
	    -param [list MyParam foo] \
	    -param [list boundary bndry] \
	    -header [list Content-Description "Test Multipart"] \
	    -parts [list $tok1 $tok2]]
    set msg [mime::buildmessage $bigTok]
    # The generated message is predictable except for the Content-ID

    list [regexp "MIME-Version: 1.0\r




Content-Description: Test Multipart\r



Content-ID: \[^\n]+\r


























Content-Type: multipart/mytype;\r
              \[^\n]+;\r
              \[^\n]+\r

\r
--bndry\r
MIME-Version: 1.0\r
Content-ID: \[^\n]+\r
Content-Type: text/plain\r
\r
jack and jill\r
................................................................................
--bndry\r
MIME-Version: 1.0\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} {
    set msg {MIME-Version: 1.0
Content-Type: Text/plain

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


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

--bar
MIME-Version: 1.0
................................................................................
part3
--bar--
}

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

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


test mime-3.3 {Try to parse a totally invalid message} {
    catch {mime::initialize -string "blah"} err0

    set err0
} {improper line in header: blah}


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

msg1}

................................................................................
    catch {mime::getbody $tok} err1
    catch {mime::buildmessage $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} {
    set msg2 {MIME-Version: 1.0
Content-Type: foobar
data without newline}

    catch {mime::initialize -string $msg2} err2

    set err2
} {improper line in header: data without newline}



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

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

foo}
................................................................................
    catch {mime::getbody $tok} err3
    catch {mime::buildmessage $tok} err3a
    list $err3 $err3a
} "foo {MIME-Version: 1.0\r
Content-Type: text/plain\r
\r
foo}"


test mime-3.7 {Test mime with a bad email [SF Bug 631314 ]} {
    set tok [mime::initialize -file \
		 [file join $tcltest::testsDirectory badmail1.txt]]

    set res {}
    set ctok [lindex [mime::getproperty $tok parts] 0]
    lappend res [dictsort [mime::getproperty $tok]]
    lappend res [dictsort [mime::getproperty $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 {charset us-ascii} size 0}}


test mime-3.8 {Test mime with another bad email [SF Bug 631314 ]} {
    set tok [mime::initialize -file \
		 [file join $tcltest::testsDirectory badmail2.txt]]
    set res {}
    set ctok [lindex [mime::getproperty $tok parts] 0]
    lappend res [dictsort [mime::getproperty $tok]]
    lappend res [dictsort [mime::getproperty $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 getbody -decode to get it back} {
    set msg {MIME-Version: 1.0
Content-Type: text/plain; charset=ISO-8859-1

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


test mime-3.10 {Parse a MIME message with a charset encoded body and use getbody -decode to get it back (example from encoding man page)} {
    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::getbody $tok -decode
} "\u306F"


test mime-3.11 {Parse a MIME message without a charset encoded body and use getbody -decode to get it back} {
    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::getbody $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 getbody -decode to attempt to get it back} {
    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::getbody $tok -decode} errmsg
    set errmsg
} "-decode failed: can't 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} {
    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::getbody $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.} {
    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} {
    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} {
    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.} {
    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} {
    set str1 [string repeat abc 40]
    mime::qp_encode $str1
} "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca=
bcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc"


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






































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


test mime-5.2 {Test word_encode with base64 method} {
    mime::word_encode iso8859-1 base64 "Test de contrôle effectué"
} "=?ISO-8859-1?B?VGVzdCBkZSBjb250cvRsZSBlZmZlY3R16Q==?="


test mime-5.3 {Test encode+decode with quoted-printable method} {
    set enc [mime::word_encode iso8859-1 quoted-printable "Test de contrôle effectué"]
    mime::word_decode $enc
} {iso8859-1 quoted-printable {Test de contrôle effectué}}


test mime-5.4 {Test encode+decode with base64 method} {
    set enc [mime::word_encode iso8859-1 base64 "Test de contrôle effectué"]
    mime::word_decode $enc
} {iso8859-1 base64 {Test de contrôle effectué}}


test mime-5.5 {Test decode with lowercase quoted-printable method} {
	mime::word_decode "=?ISO-8859-1?q?Test_lowercase_q?="
} {iso8859-1 quoted-printable {Test lowercase q}}


test mime-5.6 {Test decode with lowercase base64 method} {
	mime::word_decode "=?ISO-8859-1?b?VGVzdCBsb3dlcmNhc2UgYg==?="
} {iso8859-1 base64 {Test lowercase b}}


test mime-5.7 {Test word_encode with quoted-printable method across encoded word boundaries} {
    mime::word_encode iso8859-1 quoted-printable "Test de contrôle effectué" -maxlength 31







} "=?ISO-8859-1?Q?Test_de_contr?=
 =?ISO-8859-1?Q?=F4le_effectu?=
 =?ISO-8859-1?Q?=E9?="

test mime-5.8 {Test word_encode with quoted-printable method across encoded word boundaries} {
    mime::word_encode iso8859-1 quoted-printable "Test de contrôle effectué" -maxlength 32
} "=?ISO-8859-1?Q?Test_de_contr?=
 =?ISO-8859-1?Q?=F4le_effectu?=
 =?ISO-8859-1?Q?=E9?="

test mime-5.9 {Test word_encode with quoted-printable method and multibyte character} {
    mime::word_encode euc-jp quoted-printable "Following me is a multibyte character \xA4\xCF"
} "=?EUC-JP?Q?Following_me_is_a_multibyte_character_=A4=CF?="

set n 10
while {$n < 14} {
    test mime-5.$n {Test word_encode with quoted-printable method and multibyte character across encoded word boundary} {
        mime::word_encode euc-jp quoted-printable "Following me is a multibyte character \xA4\xCF" -maxlength [expr 42 + $n]
    } "=?EUC-JP?Q?Following_me_is_a_multibyte_character_?=
 =?EUC-JP?Q?=A4=CF?="
    incr n
}


test mime-5.14 {Test word_encode with quoted-printable method and multibyte character (triple)} {
    mime::word_encode utf-8 quoted-printable "Here is a triple byte encoded character \xE3\x81\xAF"
} "=?UTF-8?Q?Here_is_a_triple_byte_encoded_character_=E3=81=AF?="

set n 15
while {$n < 23} {
    test mime-5.$n {Test word_encode with quoted-printable method and triple byte character across encoded word boundary} {
        mime::word_encode utf-8 quoted-printable "Here is a triple byte encoded character \xE3\x81\xAF" -maxlength [expr 38 + $n]
    } "=?UTF-8?Q?Here_is_a_triple_byte_encoded_character_?=
 =?UTF-8?Q?=E3=81=AF?="
    incr n
}

while {$n < 25} {
    test mime-5.$n {Test word_encode with quoted-printable method and triple byte character across encoded word boundary} {
        mime::word_encode utf-8 quoted-printable "Here is a triple byte encoded character \xE3\x81\xAF" -maxlength [expr 38 + $n]
    } "=?UTF-8?Q?Here_is_a_triple_byte_encoded_character_=E3=81=AF?="
    incr n
}

while {$n < 29} {
    test mime-5.$n {Test word_encode with base64 method across encoded word boundaries} {
        mime::word_encode euc-jp base64 "There is a multibyte character \xA4\xCF" -maxlength [expr 28 + $n]
    } "=?EUC-JP?B?VGhlcmUgaXMgYSBtdWx0aWJ5dGUgY2hhcmFjdGVy?=
................................................................................
while {$n < 33} {
    test mime-5.$n {Test word_encode with base64 method and triple byte character across encoded word boundary} {
        mime::word_encode utf-8 base64 "Here is a multibyte character \xE3\x81\xAF" -maxlength [expr 23 + $n]
    } "=?UTF-8?B?SGVyZSBpcyBhIG11bHRpYnl0ZSBjaGFyYWN0ZXIg?=
 =?UTF-8?B?44Gv?="
    incr n
}


test mime-5.33 {Test word_encode with quoted-printable method and -maxlength set to same length as will the result} {
    mime::word_encode iso8859-1 quoted-printable "123" -maxlength 20
} "=?ISO-8859-1?Q?123?="


test mime-5.34 {Test word_encode with base64 method and -maxlength set to same length as will the result} {
    mime::word_encode iso8859-1 base64 "123" -maxlength 21
} "=?ISO-8859-1?B?MTIz?="


test mime-5.35 {Test word_encode with quoted-printable method and non charset encoded string} {
    mime::word_encode utf-8 quoted-printable "\u306F" -charset_encoded 0
} "=?UTF-8?Q?=E3=81=AF?="


test mime-5.36 {Test word_encode with base64 method and non charset encoded string} {
    mime::word_encode utf-8 base64 "\u306F" -charset_encoded 0
} "=?UTF-8?B?44Gv?="


test mime-5.36 {Test word_encode with base64 method and one byte} {
    mime::word_encode iso8859-1 base64 "a"
} "=?ISO-8859-1?B?YQ==?="


test mime-5.37 {Test word_encode with base64 method and two bytes} {
    mime::word_encode euc-jp base64 "\xA4\xCF"
} "=?EUC-JP?B?pM8=?="


test mime-5.38 {Test word_encode with unknown charset} {
    catch {mime::word_encode scribble  quoted-printable "scribble is an unknown charset"} errmsg
    set errmsg
} "unknown charset 'scribble'"


test mime-5.39 {Test word_encode with invalid charset} {
    catch {mime::word_encode unicode quoted-printable "unicode is not a valid charset"} errmsg
    set errmsg
} "invalid charset 'unicode'"


test mime-5.40 {Test word_encode with invalid method} {
    catch {mime::word_encode iso8859-1 tea-leaf "tea-leaf is not a valid method"} errmsg
    set errmsg
} "unknown method 'tea-leaf', must be base64 or quoted-printable"



test mime-5.41 {Test word_encode with maxlength to short for method quoted-printable} {
    catch {mime::word_encode iso8859-1 quoted-printable "1" -maxlength 17} errmsg
    set errmsg
} "maxlength 17 too short for chosen charset and encoding"


test mime-5.42 {Test word_encode with maxlength on the limit for quoted_printable and an unquoted character} {
   catch {mime::word_encode iso8859-1 quoted-printable "_" -maxlength 18} errmsg
   set errmsg
} "=?ISO-8859-1?Q?_?="


test mime-5.43 {Test word_encode with maxlength to short for method quoted_printable and a character to be quoted} {
   catch {mime::word_encode iso8859-1 quoted-printable "=" -maxlength 18} errmsg
   set errmsg
} "maxlength 18 too short for chosen charset and encoding"



test mime-5.44 {Test word_encode with maxlength to short for method quoted-printable and multibyte character} {
    catch {mime::word_encode euc-jp quoted-printable "\xA4\xCF" -maxlength 17} errmsg
    set errmsg
} "maxlength 17 too short for chosen charset and encoding"


test mime-5.45 {Test word_encode with maxlength to short for method base64} {
    catch {mime::word_encode iso8859-1 base64 "1" -maxlength 20} errmsg
    set errmsg
} "maxlength 20 too short for chosen charset and encoding"


test mime-6.1 {Test field_decode (from RFC 2047, part 8)} {
    mime::field_decode {=?US-ASCII?Q?Keith_Moore?= <moore@cs.utk.edu>}
} {Keith Moore <moore@cs.utk.edu>}


test mime-6.2 {Test field_decode (from RFC 2047, part 8)} {
    mime::field_decode {=?ISO-8859-1?Q?Patrik_F=E4ltstr=F6m?= <paf@nada.kth.se>}
} {Patrik Fältström <paf@nada.kth.se>}


test mime-6.3 {Test field_decode (from RFC 2047, part 8)} {
    mime::field_decode {=?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=
			=?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=}
} {If you can read this you understand the example.}

foreach {n encoded expected} {
    4 "(=?ISO-8859-1?Q?a?=)"
    "(a)"
    5 "(=?ISO-8859-1?Q?a?= b)"
    "(a b)"
    6 "(=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=)"
    "(ab)"
    7 "(=?ISO-8859-1?Q?a?=  =?ISO-8859-1?Q?b?=)"
    "(ab)"
    8 "(=?ISO-8859-1?Q?a?=
    =?ISO-8859-1?Q?b?=)"
    "(ab)"
    9 "(=?ISO-8859-1?Q?a_b?=)"
    "(a b)"
    10 "(=?ISO-8859-1?Q?a?= =?ISO-8859-2?Q?_b?=)"
    "(a b)"
    11 "(=?ISO-8859-1?Q?a?=x=?ISO-8859-2?Q?_b?=)"
    "(ax b)"
    12 "a         b         c"
    "a         b         c"
    13 ""
    ""

} {
    test mime-6.$n {Test field_decode (from RFC 2047, part 8)} {
	mime::field_decode $encoded
    } $expected ; # {}
}

foreach {bug n encoded expected} {
    764702 1 "(=?utf-8?Q?H=C3=BCrz?=)" "(Hürz)"
} {
    test mime-7.$n "Test field_decode (from SF Tcllib bug $bug)" {
	mime::field_decode $encoded
    } $expected ; # {}
}


test mime-8.1 {Test reversemapencoding+mapencoding with preferred name} {
    set charset [mime::reversemapencoding "US-ASCII"]
    mime::mapencoding $charset
} {US-ASCII}


test mime-8.2 {Test reversemapencoding+mapencoding with alias} {
    set charset [mime::reversemapencoding "UTF8"]
    mime::mapencoding $charset
} {UTF-8}


test mime-9.0 {Test chunk handling of copymessage and helpers} {
    set in [makeFile [set data [string repeat [string repeat "123456789 " 10]\n 350]] input.txt]
    set mi [makeFile {} mime.txt]

    set token [mime::initialize -canonical text/plain -file $in]

    set f [open $mi w]
    fconfigure $f -translation binary
    mime::copymessage $token $f
................................................................................

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

set ::env(TZ) "UTC0"
set epoch [clock scan 2000-01-01]
foreach {n stamp date} {
    1     86340 {Sat, 01 Jan 2000 23:59:00 +0000}
    2   5176620 {Tue, 29 Feb 2000 21:57:00 +0000}
    3  31610520 {Sun, 31 Dec 2000 20:42:00 +0000}
    4  31708740 {Mon, 01 Jan 2001 23:59:00 +0000}
    5  68248620 {Thu, 28 Feb 2002 21:57:00 +0000}
................................................................................
    mime::copymessage $attachment $ofh
    close $ofh

    set data [viewFile $out]
    file delete $in $out
    set data
} {MIME-Version: 1.0
Content-Disposition: attachment;
 filename="a0036.dss"
Content-Transfer-Encoding: base64
Content-Type: application/octet-stream;
              name="a0036.dss"


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

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


test mime-12.0 {Bug 3483716} {
    set token [mime::initialize -string {Content-Type: message/delivery-status; name="deliverystatus.txt"
Content-Disposition: attachment; filename="deliverystatus.txt"; size=138;
creation-date="Thu, 02 Feb 2012 13:50:05 GMT";
modification-date="Thu, 02 Feb 2012 13:50:05 GMT"
Content-Description: deliverystatus.txt
................................................................................
Content-Transfer-Encoding: base64

T3JpZ2luYWwtUmVjaXBpZW50OiA8L2ZheD1ibHViYkBndW1taS5ib290PgpBY3Rpb246IGZhaWxl
ZApEaWFnbm9zdGljLUNvZGU6IHNtdHA7IDU1MCAjNS4xLjAgQWRkcmVzcyByZWplY3RlZC4KUmVt
b3RlLU1UQTogNTMuMjQuMjgyLjE1MA==
}]
    set parts [mime::getproperty $token parts]
    mime::getheader [lindex $parts end] Remote-MTA

} 53.24.282.150

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


test mime-13.0 {
    issue a16b1095974e071d
................................................................................
"

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

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





















































































testsuiteCleanup
return




|







 







>




|

>

|

>








>

|
|

|
<
|



>

>
>
>
>

>
>
>

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







 







|

>








|
>







 







|






>

|
>

|
>







 







>






|
>

<
>
>







 








>

|
<







|
>











>











>









|
>









|
>










|
>









|
>





>






|
>





>












>







>
>
>
>


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

|
|

>

|
|

>

|



>

|



>

|


>

|


>

|
>
>
>
>
>
>
>




<
<
<
<
<



|









>



|













|







 








>

|
|

>

|
|

>

|
|

>

|
|

>

|
|

>

|
|

>

|

|

>

|

|

>

|

<
>

>

|

|

>

|

|

>

|

|
>



|

|

>

|

|
>




>




>







|
|
|
|
|
|
|
|


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







|






>

|

|

>

|

|



|







 







|







 







|
|
<
|
|
>





>







 







|
>







 








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


1
2
3
4
5
6
7
8
9
10
11
12
..
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
...
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
...
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
...
209
210
211
212
213
214
215
216
217
218
219

220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418





419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
...
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515

516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585

586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
...
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
...
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
...
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
# mime.test - Test suite for TclMIME                     -*- tcl -*-
#
# This file contains a collection of tests for one or more of the Tcl
# built-in commands.  Sourcing this file into Tcl runs the tests and
# genere totes output for errors.  No output means no errors were found.
#
# Copyright (c) 2000 by Ajuba Solutions
# All rights reserved.
#
# RCS: @(#) $Id: mime.test,v 1.31 2012/02/23 17:35:17 andreas_kupries Exp $

# -------------------------------------------------------------------------
................................................................................
}

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

namespace import mime::*

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


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


test mime-2.1 {Generate a MIME message} {
    set tok [initialize -canonical Text/plain -string {jack and jill}]
    set msg [mime::buildmessage $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


test mime-2.2 {Generate a multi-part MIME message} {
    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::buildmessage $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
MIME-Version: 1.0\r
Content-ID: \[^\n]+\r
Content-Type: text/plain\r
\r
jack and jill\r
--bndry\r
MIME-Version: 1.0\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} {
    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::buildmessage $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
MIME-Version: 1.0\r
Content-ID: \[^\n]+\r
Content-Type: text/plain\r
\r
jack and jill\r
................................................................................
--bndry\r
MIME-Version: 1.0\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} {
    set msg {MIME-Version: 1.0
Content-Type: Text/plain

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


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

--bar
MIME-Version: 1.0
................................................................................
part3
--bar--
}

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

    set res {} 
    foreach childTok $partToks {
	lappend res [mime::getbody $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} {
    set msg1 {MIME-Version: 2.0
Content-Type: text/plain

msg1}

................................................................................
    catch {mime::getbody $tok} err1
    catch {mime::buildmessage $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} {
    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} {

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

foo}
................................................................................
    catch {mime::getbody $tok} err3
    catch {mime::buildmessage $tok} err3a
    list $err3 $err3a
} "foo {MIME-Version: 1.0\r
Content-Type: text/plain\r
\r
foo}"


test mime-3.7 {Test mime with a bad email [SF Bug 631314 ]} {
    set tok [mime::initialize -file $tcltest::testsDirectory/badmail1.txt]


    set res {}
    set ctok [lindex [mime::getproperty $tok parts] 0]
    lappend res [dictsort [mime::getproperty $tok]]
    lappend res [dictsort [mime::getproperty $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 ]} {
    set tok [mime::initialize -file \
		 [file join $tcltest::testsDirectory badmail2.txt]]
    set res {}
    set ctok [lindex [mime::getproperty $tok parts] 0]
    lappend res [dictsort [mime::getproperty $tok]]
    lappend res [dictsort [mime::getproperty $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 getbody -decode to get it back} {
    set msg {MIME-Version: 1.0
Content-Type: text/plain; charset=ISO-8859-1

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


test mime-3.10 {Parse a MIME message with a charset encoded body and use getbody -decode to get it back (example from encoding man page)} {
    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::getbody $tok -decode
} \u306F


test mime-3.11 {Parse a MIME message without a charset encoded body and use getbody -decode to get it back} {
    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::getbody $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 getbody -decode to attempt to get it back} {
    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::getbody $tok -decode} errmsg
    set errmsg
} {-decode failed: can't 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} {
    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::getbody $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.} {
    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} {
    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} {
    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.} {
    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} {
    set str1 [string repeat abc 40]
    mime::qp_encode $str1
} "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca=
bcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc"


test mime-4.6 {Test qp_encode with softbreak} {
    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} {
    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} {
    mime::qp_encode 1and1=2 1
} 1and1=3D2

test mime-4.9 {Test qp_encode in encoded_word mode with tabs and spaces} {
    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} {
    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} {
    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} {
    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} {
    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} {
    mime::word_encode iso8859-1 quoted-printable {Test de contrôle effectué}
} =?ISO-8859-1?Q?Test_de_contr=F4le_effectu=E9?=


test mime-5.2 {Test word_encode with base64 method} {
    mime::word_encode iso8859-1 base64 {Test de contrôle effectué}
} =?ISO-8859-1?B?VGVzdCBkZSBjb250cvRsZSBlZmZlY3R16Q==?=


test mime-5.3 {Test encode+decode with quoted-printable method} {
    set enc [mime::word_encode iso8859-1 quoted-printable {Test de contrôle effectué}]
    mime::word_decode $enc
} {iso8859-1 quoted-printable {Test de contrôle effectué}}


test mime-5.4 {Test encode+decode with base64 method} {
    set enc [mime::word_encode iso8859-1 base64 {Test de contrôle effectué}]
    mime::word_decode $enc
} {iso8859-1 base64 {Test de contrôle effectué}}


test mime-5.5 {Test decode with lowercase quoted-printable method} {
	mime::word_decode =?ISO-8859-1?q?Test_lowercase_q?=
} {iso8859-1 quoted-printable {Test lowercase q}}


test mime-5.6 {Test decode with lowercase base64 method} {
	mime::word_decode =?ISO-8859-1?b?VGVzdCBsb3dlcmNhc2UgYg==?=
} {iso8859-1 base64 {Test lowercase b}}


test mime-5.7 {Test word_encode with quoted-printable method across encoded word boundaries} {
    mime::word_encode iso8859-1 quoted-printable {Test de contrôle effectué} -maxlength 31
} "=?ISO-8859-1?Q?Test_de_contr?=
 =?ISO-8859-1?Q?=F4le_effectu?=
 =?ISO-8859-1?Q?=E9?="


test mime-5.8 {Test word_encode with quoted-printable method across encoded word boundaries} {
    mime::word_encode iso8859-1 quoted-printable {Test de contrôle effectué} -maxlength 32
} "=?ISO-8859-1?Q?Test_de_contr?=
 =?ISO-8859-1?Q?=F4le_effectu?=
 =?ISO-8859-1?Q?=E9?="







test mime-5.9 {Test word_encode with quoted-printable method and multibyte character} {
    mime::word_encode euc-jp quoted-printable "Following me is a multibyte character \xA4\xCF"
} =?EUC-JP?Q?Following_me_is_a_multibyte_character_=A4=CF?=

set n 10
while {$n < 14} {
    test mime-5.$n {Test word_encode with quoted-printable method and multibyte character across encoded word boundary} {
        mime::word_encode euc-jp quoted-printable "Following me is a multibyte character \xA4\xCF" -maxlength [expr 42 + $n]
    } "=?EUC-JP?Q?Following_me_is_a_multibyte_character_?=
 =?EUC-JP?Q?=A4=CF?="
    incr n
}


test mime-5.14 {Test word_encode with quoted-printable method and multibyte character (triple)} {
    mime::word_encode utf-8 quoted-printable "Here is a triple byte encoded character \xE3\x81\xAF"
} =?UTF-8?Q?Here_is_a_triple_byte_encoded_character_=E3=81=AF?=

set n 15
while {$n < 23} {
    test mime-5.$n {Test word_encode with quoted-printable method and triple byte character across encoded word boundary} {
        mime::word_encode utf-8 quoted-printable "Here is a triple byte encoded character \xE3\x81\xAF" -maxlength [expr 38 + $n]
    } "=?UTF-8?Q?Here_is_a_triple_byte_encoded_character_?=
 =?UTF-8?Q?=E3=81=AF?="
    incr n
}

while {$n < 25} {
    test mime-5.$n {Test word_encode with quoted-printable method and triple byte character across encoded word boundary} {
        mime::word_encode utf-8 quoted-printable "Here is a triple byte encoded character \xE3\x81\xAF" -maxlength [expr 38 + $n]
    } =?UTF-8?Q?Here_is_a_triple_byte_encoded_character_=E3=81=AF?=
    incr n
}

while {$n < 29} {
    test mime-5.$n {Test word_encode with base64 method across encoded word boundaries} {
        mime::word_encode euc-jp base64 "There is a multibyte character \xA4\xCF" -maxlength [expr 28 + $n]
    } "=?EUC-JP?B?VGhlcmUgaXMgYSBtdWx0aWJ5dGUgY2hhcmFjdGVy?=
................................................................................
while {$n < 33} {
    test mime-5.$n {Test word_encode with base64 method and triple byte character across encoded word boundary} {
        mime::word_encode utf-8 base64 "Here is a multibyte character \xE3\x81\xAF" -maxlength [expr 23 + $n]
    } "=?UTF-8?B?SGVyZSBpcyBhIG11bHRpYnl0ZSBjaGFyYWN0ZXIg?=
 =?UTF-8?B?44Gv?="
    incr n
}


test mime-5.33 {Test word_encode with quoted-printable method and -maxlength set to same length as will the result} {
    mime::word_encode iso8859-1 quoted-printable 123 -maxlength 20
} =?ISO-8859-1?Q?123?=


test mime-5.34 {Test word_encode with base64 method and -maxlength set to same length as will the result} {
    mime::word_encode iso8859-1 base64 123 -maxlength 21
} =?ISO-8859-1?B?MTIz?=


test mime-5.35 {Test word_encode with quoted-printable method and non charset encoded string} {
    mime::word_encode utf-8 quoted-printable \u306F -charset_encoded 0
} =?UTF-8?Q?=E3=81=AF?=


test mime-5.36 {Test word_encode with base64 method and non charset encoded string} {
    mime::word_encode utf-8 base64 \u306F -charset_encoded 0
} =?UTF-8?B?44Gv?=


test mime-5.36 {Test word_encode with base64 method and one byte} {
    mime::word_encode iso8859-1 base64 a
} =?ISO-8859-1?B?YQ==?=


test mime-5.37 {Test word_encode with base64 method and two bytes} {
    mime::word_encode euc-jp base64 \xA4\xCF
} =?EUC-JP?B?pM8=?=


test mime-5.38 {Test word_encode with unknown charset} {
    catch {mime::word_encode scribble  quoted-printable {scribble is an unknown charset}} errmsg
    set errmsg
} {{unknown charset} scribble}


test mime-5.39 {Test word_encode with invalid charset} {
    catch {mime::word_encode unicode quoted-printable {unicode is not a valid charset}} errmsg
    set errmsg
} {{invalid charset} unicode}


test mime-5.40 {Test word_encode with invalid method} {
    catch {mime::word_encode iso8859-1 tea-leaf {tea-leaf is not a valid method}} errmsg
    set errmsg

} {{unknown method} tea-leaf {must be one of} {base64 quoted-printable}}


test mime-5.41 {Test word_encode with maxlength to short for method quoted-printable} {
    catch {mime::word_encode iso8859-1 quoted-printable 1 -maxlength 17} errmsg
    set errmsg
} {maxlength 17 {too short for chosen charset and encoding}}


test mime-5.42 {Test word_encode with maxlength on the limit for quoted_printable and an unquoted character} {
   catch {mime::word_encode iso8859-1 quoted-printable _ -maxlength 20} errmsg
   set errmsg
} =?ISO-8859-1?Q?=5F?=


test mime-5.43 {Test word_encode with maxlength to short for method quoted_printable and a character to be quoted} {
   catch {mime::word_encode iso8859-1 quoted-printable = -maxlength 18} errmsg
   set errmsg
} {maxlength 18 {too short for chosen charset and encoding}}



test mime-5.44 {Test word_encode with maxlength to short for method quoted-printable and multibyte character} {
    catch {mime::word_encode euc-jp quoted-printable \xA4\xCF -maxlength 17} errmsg
    set errmsg
} {maxlength 17 {too short for chosen charset and encoding}}


test mime-5.45 {Test word_encode with maxlength to short for method base64} {
    catch {mime::word_encode iso8859-1 base64 1 -maxlength 20} errmsg
    set errmsg
} {maxlength 20 {too short for chosen charset and encoding}}


test mime-6.1 {Test field_decode (from RFC 2047, part 8)} {
    mime::field_decode {=?US-ASCII?Q?Keith_Moore?= <moore@cs.utk.edu>}
} {Keith Moore <moore@cs.utk.edu>}


test mime-6.2 {Test field_decode (from RFC 2047, part 8)} {
    mime::field_decode {=?ISO-8859-1?Q?Patrik_F=E4ltstr=F6m?= <paf@nada.kth.se>}
} {Patrik Fältström <paf@nada.kth.se>}


test mime-6.3 {Test field_decode (from RFC 2047, part 8)} {
    mime::field_decode {=?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=
			=?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=}
} {If you can read this you understand the example.}

foreach {n encoded expected} {
    4 (=?ISO-8859-1?Q?a?=)
    (a)
    5 {(=?ISO-8859-1?Q?a?= b)}
    {(a b)}
    6 {(=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=)}
    (ab)
    7 {(=?ISO-8859-1?Q?a?=  =?ISO-8859-1?Q?b?=)}
    (ab)
    8 "(=?ISO-8859-1?Q?a?=
    =?ISO-8859-1?Q?b?=)"
    (ab)
    9 (=?ISO-8859-1?Q?a_b?=)
    {(a b)}
    10 {(=?ISO-8859-1?Q?a?= =?ISO-8859-2?Q?_b?=)}
    {(a b)}
    11 {(=?ISO-8859-1?Q?a?=x=?ISO-8859-2?Q?_b?=)}
    {(ax b)}
    12 {a         b         c}
    {a         b         c}
    13 {} 

    {}
} {
    test mime-6.$n {Test field_decode (from RFC 2047, part 8)} {
	mime::field_decode $encoded
    } $expected ; # {}
}

foreach {bug n encoded expected} {
    764702 1 {(=?utf-8?Q?H=C3=BCrz?=)} {(Hürz)}
} {
    test mime-7.$n "Test field_decode (from SF Tcllib bug $bug)" {
	mime::field_decode $encoded
    } $expected ; # {}
}


test mime-8.1 {Test reversemapencoding+mapencoding with preferred name} {
    set charset [mime::reversemapencoding US-ASCII]
    mime::mapencoding $charset
} US-ASCII


test mime-8.2 {Test reversemapencoding+mapencoding with alias} {
    set charset [mime::reversemapencoding UTF8]
    mime::mapencoding $charset
} UTF-8


test mime-9.0 {Test chunk handling of copymessage and helpers} {
    set in [makeFile [set data [string repeat [string repeat {123456789 } 10]\n 350]] input.txt]
    set mi [makeFile {} mime.txt]

    set token [mime::initialize -canonical text/plain -file $in]

    set f [open $mi w]
    fconfigure $f -translation binary
    mime::copymessage $token $f
................................................................................

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

set ::env(TZ) UTC0
set epoch [clock scan 2000-01-01]
foreach {n stamp date} {
    1     86340 {Sat, 01 Jan 2000 23:59:00 +0000}
    2   5176620 {Tue, 29 Feb 2000 21:57:00 +0000}
    3  31610520 {Sun, 31 Dec 2000 20:42:00 +0000}
    4  31708740 {Mon, 01 Jan 2001 23:59:00 +0000}
    5  68248620 {Thu, 28 Feb 2002 21:57:00 +0000}
................................................................................
    mime::copymessage $attachment $ofh
    close $ofh

    set data [viewFile $out]
    file delete $in $out
    set data
} {MIME-Version: 1.0
Content-Disposition: attachment
	; filename=a0036.dss

Content-Type: application/octet-stream
	; name=a0036.dss
Content-Transfer-Encoding: base64

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

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


test mime-12.0 {Bug 3483716} {
    set token [mime::initialize -string {Content-Type: message/delivery-status; name="deliverystatus.txt"
Content-Disposition: attachment; filename="deliverystatus.txt"; size=138;
creation-date="Thu, 02 Feb 2012 13:50:05 GMT";
modification-date="Thu, 02 Feb 2012 13:50:05 GMT"
Content-Description: deliverystatus.txt
................................................................................
Content-Transfer-Encoding: base64

T3JpZ2luYWwtUmVjaXBpZW50OiA8L2ZheD1ibHViYkBndW1taS5ib290PgpBY3Rpb246IGZhaWxl
ZApEaWFnbm9zdGljLUNvZGU6IHNtdHA7IDU1MCAjNS4xLjAgQWRkcmVzcyByZWplY3RlZC4KUmVt
b3RlLU1UQTogNTMuMjQuMjgyLjE1MA==
}]
    set parts [mime::getproperty $token parts]
    lassign [mime::header get [lindex $parts end] Remote-MTA] result
    return $result
} 53.24.282.150

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


test mime-13.0 {
    issue a16b1095974e071d
................................................................................
"

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

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

test mime-14.0 {
	hostname argument to parseaddress
} {
	set parsed [mime::parseaddress hostname fakedomain.fake {Here <h>}] 
    list [llength $parsed] [lindex $parsed 0]
} [list 1 [list address h@fakedomain.fake comment {} domain {} error {} \
	friendly Here group {} local h memberP 0 phrase Here \
	proper {Here <h@fakedomain.fake>} route {}]]



test mime-14.1 {
	special characters in local part
} {
	set parsed [mime::parseaddress hostname fakedomain.fake foo<>bar@grill.com]
    list [llength $parsed] [lindex $parsed 0]
} [list 1 [list address {} comment {} domain {} \
	error {expecting mailbox in local-part (found >)} friendly foo group {} \
	local {} memberP 0 phrase foo proper {foo <>} route {}]]


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


test mime-15.0 {
	a multipart/mixed message with an invalid body
} {
    set msg "MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=\"something\"\r
\r
so plain
"

    set tok [mime::initialize -string $msg]
    mime::header get $tok
} [list MIME-Version {1.0 {}} Content-Type \
    {multipart/mixed {boundary something}}]


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


test mime-16.0 {
} {
    set msg "MIME-Version: 1.0
Content-Type: text/plain\r
Content-Disposition: attachment
    ; param1=\"a parameter value\";  param2*1=\"another param\";
	param2*2=\"eter value\" \r
\r
so plain
"

    set tok [mime::initialize -string $msg]
	mime::header get $tok
} [list MIME-Version {1.0 {}} Content-Type {text/plain {}} Content-Disposition [
    list attachment [list param1 {a parameter value} \
	param2 {another parameter value}]]]

set char [encoding convertfrom utf-8 \xE3\x81\xAF]
test mime-16.1 {
} {
    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::buildmessage $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 MIME-Version {1.0 {}} Content-ID {<> {}} Content-Type {text/plain {}} \
    Content-Disposition [list attachment [list param1 $char]]]

]

testsuiteCleanup
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.6 [list source [file join $dir mime.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]]

Changes to modules/namespacex/namespacex.man.

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
[call [cmd {::namespacex hook add}]  [opt [arg namespace]] [arg cmdprefix]]
[call [cmd {::namespacex hook proc}] [opt [arg namespace]] [arg arguments] [arg body]]
[call [cmd {::namespacex hook on}]   [opt [arg namespace]] [arg guardcmdprefix] [arg actioncmdprefix]]
[call [cmd {::namespacex hook next}] [arg arg]...]

[call [cmd {::namespacex info allchildren}] [arg namespace]]

This command returns a list containing the names of all child
namespaces in the specified [arg namespace] and its children. The
names are all fully qualified.

[call [cmd {::namespacex info allvars}] [arg namespace]]

This command returns a list containing the names of all variables in
the specified [arg namespace] and its children. The names are all
relative to [arg namespace], and [emph not] fully qualified.

[call [cmd {::namespacex info vars}] [arg namespace] [opt [arg pattern]]]

This command returns a list containing the names of all variables in
the specified [arg namespace].






[call [cmd {::namespacex state get}] [arg namespace]]

This command returns a dictionary holding the names and values of all
variables in the specified [arg namespace] and its child namespaces.

[para]
Note that the names are all relative to [arg namespace],
and [emph not] fully qualified.

[call [cmd {::namespacex state set}] [arg namespace] [arg dict]]

This command takes a dictionary holding the names and values for a set
of variables and replaces the current state of the specified
[arg namespace] and its child namespaces with this state.

The result of the command is the empty string.

[call [cmd {::namespacex state drop}] [arg namespace]]

This command unsets all variables in the specified [arg namespace] and
its child namespaces.

The result of the command is the empty string.








[list_end]
[manpage_end]







|





|





|


>
>
>
>
>


|








|







|




>
>
>
>
>
>
>


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
[call [cmd {::namespacex hook add}]  [opt [arg namespace]] [arg cmdprefix]]
[call [cmd {::namespacex hook proc}] [opt [arg namespace]] [arg arguments] [arg body]]
[call [cmd {::namespacex hook on}]   [opt [arg namespace]] [arg guardcmdprefix] [arg actioncmdprefix]]
[call [cmd {::namespacex hook next}] [arg arg]...]

[call [cmd {::namespacex info allchildren}] [arg namespace]]

Returns a list containing the names of all child
namespaces in the specified [arg namespace] and its children. The
names are all fully qualified.

[call [cmd {::namespacex info allvars}] [arg namespace]]

Returns a list containing the names of all variables in
the specified [arg namespace] and its children. The names are all
relative to [arg namespace], and [emph not] fully qualified.

[call [cmd {::namespacex info vars}] [arg namespace] [opt [arg pattern]]]

Returns a list containing the names of all variables in
the specified [arg namespace].

[call [cmd {::namespacex normalize}] [arg namespace]]

Returns the absolute name of [arg namespace], which is resolved relative
to the namespace of the caller, with all unneeded colon characters removed.

[call [cmd {::namespacex state get}] [arg namespace]]

Returns a dictionary holding the names and values of all
variables in the specified [arg namespace] and its child namespaces.

[para]
Note that the names are all relative to [arg namespace],
and [emph not] fully qualified.

[call [cmd {::namespacex state set}] [arg namespace] [arg dict]]

Takes a dictionary holding the names and values for a set
of variables and replaces the current state of the specified
[arg namespace] and its child namespaces with this state.

The result of the command is the empty string.

[call [cmd {::namespacex state drop}] [arg namespace]]

Unsets all variables in the specified [arg namespace] and
its child namespaces.

The result of the command is the empty string.


[call [cmd {::namespacex strip}] [arg namespace] [arg namespaces]]

Each item in [arg namespaces] must be the absolute normalized name of a child
namespace of [arg prefix].  Returns the corresponding list of relative names of
child namespaces.

[list_end]
[manpage_end]

Changes to modules/namespacex/namespacex.tcl.

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
...
179
180
181
182
183
184
185

186
187

188
189
190
191
192
193
194

195
196

197
198
199
200
201
202
203
204

205

206
207
208


209












210
211
212
213

214
215
216
217
218
219
220
221
222


223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249

250
251
252
253
254

# # ## ### ##### ######## ############# ######################
## Requisites

package require Tcl 8.5  ; # namespace ensembles, {*}

namespace eval ::namespacex {
    namespace export add hook info 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
................................................................................
        return -code $rc $result
    }
}

# # ## ### ##### ######## ############# ######################
## Implementation :: Info - Visible API


proc ::namespacex::info::allvars {ns} {
    if {![string match {::*} $ns]} { set ns ::$ns }

    ::set result [::info vars ${ns}::*]
    foreach cns [allchildren $ns] {
	lappend result {*}[::info vars ${cns}::*]
    }
    return [Strip $ns $result]
}


proc ::namespacex::info::allchildren {ns} {
    if {![string match {::*} $ns]} { set ns ::$ns }

    ::set result [list]
    foreach cns [::namespace children $ns] {
	lappend result {*}[allchildren $cns]
	lappend result $cns
    }
    return $result
}


proc ::namespacex::info::vars {ns {pattern *}} {

    return [Strip $ns [::info vars ${ns}::$pattern]]
}



proc ::namespacex::info::Strip {ns itemlist} {












    set n [string length $ns]
    if {![string match {::*} $ns]} {
	incr n 4
    } else {

	incr n 2
    }

    set result {}
    foreach i $itemlist {
	lappend result [string range $i $n end]
    }
    return $result
}



# # ## ### ##### ######## ############# ######################
## Implementation :: State - Visible API

proc ::namespacex::state::drop {ns} {
    if {![string match {::*} $ns]} { ::set ns ::$ns }
    namespace eval $ns [list ::unset {*}[::namespacex info allvars $ns]]
    return
}

proc ::namespacex::state::get {ns} {
    if {![string match {::*} $ns]} { ::set ns ::$ns }
    ::set result {}
    foreach v [::namespacex info allvars $ns] {
	namespace upvar $ns $v value
	lappend result $v $value
    }
    return $result
}

proc ::namespacex::state::set {ns state} {
    if {![string match {::*} $ns]} { ::set ns ::$ns }
    # Inlined 'state drop'.
    namespace eval $ns [list ::unset  {*}[::namespacex info allvars $ns]]
    namespace eval $ns [list variable {*}$state]
    return
}


# # ## ### ##### ######## ############# ######################
## Ready

package provide namespacex 0.1







|







 







>
|
<
>




|


>
|
<
>








>

>
|


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

<
<
<
>









>
>




|
|




|
|









|





>





11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
...
179
180
181
182
183
184
185
186
187

188
189
190
191
192
193
194
195
196
197

198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273

# # ## ### ##### ######## ############# ######################
## 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
................................................................................
        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}::*]
    }
    return [[namespace parent] strip $ns $result]
}


proc ::namespacex::info::allchildren ns {

    set ns [uplevel 1 [list [namespace parent] normalize $ns]]
    ::set result [list]
    foreach cns [::namespace children $ns] {
	lappend result {*}[allchildren $cns]
	lappend result $cns
    }
    return $result
}


proc ::namespacex::info::vars {ns {pattern *}} {
    set ns [uplevel 1 [list [namespace parent] normalize $ns]]
    return [[namespace parent] strip $ns [::info vars ${ns}::$pattern]]
}


# this implementation avoids string operations
proc ::namespacex::normalize ns {
    if {[uplevel 1 [list ::namespace exists $ns]]} {
	return [uplevel 1 [list namespace eval $ns {namespace current}]]
    }
    if {![string match ::* $ns]} {
	set ns [uplevel 1 {namespace current}]::$ns
    }
    regsub {::+} $ns :: ns
    return $ns
}


proc ::namespacex::strip {ns itemlist} {
    set n [string length $ns]



    if {$ns ne {::}} {
	incr n 2
    }

    set result {}
    foreach i $itemlist {
	lappend result [string range $i $n end]
    }
    return $result
}



# # ## ### ##### ######## ############# ######################
## Implementation :: State - Visible API

proc ::namespacex::state::drop ns {
    ::set ns [uplevel 1 [list [namespace parent] normalize $ns]]
    namespace eval $ns [list ::unset {*}[::namespacex info allvars $ns]]
    return
}

proc ::namespacex::state::get ns {
    ::set ns [uplevel 1 [list [namespace parent] normalize $ns]]
    ::set result {}
    foreach v [::namespacex info allvars $ns] {
	namespace upvar $ns $v value
	lappend result $v $value
    }
    return $result
}

proc ::namespacex::state::set {ns state} {
    ::set ns [uplevel 1 [list [namespace parent] normalize $ns]]
    # Inlined 'state drop'.
    namespace eval $ns [list ::unset  {*}[::namespacex info allvars $ns]]
    namespace eval $ns [list variable {*}$state]
    return
}


# # ## ### ##### ######## ############# ######################
## Ready

package provide namespacex 0.1

Changes to modules/namespacex/namespacex.test.

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












































testing {
    useLocal namespacex.tcl namespacex
}

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

proc ns_setup {} {
    namespace eval ::X {
        namespace eval A {}
        namespace eval B {
            namespace eval D {}
        }
        namespace eval C {}
    }
}

proc ns2_setup {} {
    namespace eval ::X {
        variable vXa 1
        variable vXb aleph
        namespace eval B {
            variable vB 3
        }
    }
}

proc ns3_setup {} {
    namespace eval ::X {
        namespace eval B {
            variable vB mjolnir
        }
    }
}

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

test namespacex-info-allchildren-1.0 {namespacex info allchildren, wrong\#args} -body {
    namespacex info allchildren
} -returnCodes error -result {wrong # args: should be "namespacex info allchildren ns"}

test namespacex-info-allchildren-1.1 {namespacex info allchildren, wrong\#args} -body {
    namespacex info allchildren N X
} -returnCodes error -result {wrong # args: should be "namespacex info allchildren ns"}

test namespacex-info-allchildren-2.0.0 {namespacex info allchildren} -setup {
    ns_setup
} -body {
    lsort -dict [namespacex info allchildren ::X]
} -cleanup {
    namespace delete ::X
} -result {::X::A ::X::B ::X::B::D ::X::C}

test namespacex-info-allchildren-2.0.1 {namespacex info allchildren} -setup {
    ns_setup
} -body {
    lsort -dict [namespacex info allchildren X]
} -cleanup {
    namespace delete ::X
} -result {::X::A ::X::B ::X::B::D ::X::C}

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

test namespacex-info-vars-1.0 {namespacex info vars, wrong\#args} -body {
    namespacex info vars
} -returnCodes error -result {wrong # args: should be "namespacex info vars ns ?pattern?"}

test namespacex-info-vars-1.1 {namespacex info vars, wrong\#args} -body {
    namespacex info vars N P X
} -returnCodes error -result {wrong # args: should be "namespacex info vars ns ?pattern?"}

test namespacex-info-vars-2.0 {namespacex info vars} -setup {
    ns2_setup
} -body {
    lsort -dict [namespacex info vars ::X]
} -cleanup {
    namespace delete ::X
} -result {vXa vXb}

test namespacex-info-vars-2.1 {namespacex info vars} -setup {
    namespace eval ::X {}
} -body {
    lsort -dict [namespacex info vars ::X]
} -cleanup {
    namespace delete ::X
} -result {}

test namespacex-info-vars-2.2 {namespacex info vars} -setup {
    ns3_setup
} -body {
    lsort -dict [namespacex info vars ::X]
} -cleanup {
    namespace delete ::X
} -result {}

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

test namespacex-info-allvars-1.0 {namespacex info allvars, wrong\#args} -body {
    namespacex info allvars
} -returnCodes error -result {wrong # args: should be "namespacex info allvars ns"}

test namespacex-info-allvars-1.1 {namespacex info allvars, wrong\#args} -body {
    namespacex info allvars N X
} -returnCodes error -result {wrong # args: should be "namespacex info allvars ns"}

test namespacex-info-allvars-2.0.0 {namespacex info allvars} -setup {
    ns2_setup
} -body {
    lsort -dict [namespacex info allvars ::X]
} -cleanup {
    namespace delete ::X
} -result {B::vB vXa vXb}

test namespacex-info-allvars-2.0.1 {namespacex info allvars} -setup {
    ns2_setup
} -body {
    lsort -dict [namespacex info allvars X]
} -cleanup {
    namespace delete ::X
} -result {B::vB vXa vXb}

test namespacex-info-allvars-2.1.0 {namespacex info allvars} -setup {
    namespace eval ::X {}
} -body {
    lsort -dict [namespacex info allvars ::X]
} -cleanup {
    namespace delete ::X
} -result {}

test namespacex-info-allvars-2.1.1 {namespacex info allvars} -setup {
    namespace eval ::X {}
} -body {
    lsort -dict [namespacex info allvars X]
} -cleanup {
    namespace delete ::X
} -result {}

test namespacex-info-allvars-2.2.0 {namespacex info allvars} -setup {
    ns3_setup
} -body {
    lsort -dict [namespacex info allvars ::X]
} -cleanup {
    namespace delete ::X
} -result {B::vB}

test namespacex-info-allvars-2.2.1 {namespacex info allvars} -setup {
    ns3_setup
} -body {
    lsort -dict [namespacex info allvars X]
} -cleanup {
    namespace delete ::X
} -result {B::vB}

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

test namespacex-state-get-1.0 {namespacex state get, wrong\#args} -body {
    namespacex state get
} -returnCodes error -result {wrong # args: should be "namespacex state get ns"}

test namespacex-state-get-1.1 {namespacex state get, wrong\#args} -body {
    namespacex state get N X
} -returnCodes error -result {wrong # args: should be "namespacex state get ns"}

test namespacex-state-get-2.0.0 {namespacex state get} -setup {
    ns2_setup
} -body {
    dictsort [namespacex state get ::X]
} -cleanup {
    namespace delete ::X
} -result {B::vB 3 vXa 1 vXb aleph}

test namespacex-state-get-2.0.1 {namespacex state get} -setup {
    ns2_setup
} -body {
    dictsort [namespacex state get X]
} -cleanup {
    namespace delete ::X
} -result {B::vB 3 vXa 1 vXb aleph}

test namespacex-state-get-2.1.0 {namespacex state get} -setup {
    namespace eval ::X {}
} -body {
    dictsort [namespacex state get ::X]
} -cleanup {
    namespace delete ::X
} -result {}

test namespacex-state-get-2.1.1 {namespacex state get} -setup {
    namespace eval ::X {}
} -body {
    dictsort [namespacex state get X]
} -cleanup {
    namespace delete ::X
} -result {}

test namespacex-state-get-2.2.0 {namespacex state get} -setup {
    ns3_setup
} -body {
    dictsort [namespacex state get ::X]
} -cleanup {
    namespace delete ::X
} -result {B::vB mjolnir}

test namespacex-state-get-2.2.1 {namespacex state get} -setup {
    ns3_setup
} -body {
    dictsort [namespacex state get X]
} -cleanup {
    namespace delete ::X
} -result {B::vB mjolnir}

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

test namespacex-state-drop-1.0 {namespacex state drop, wrong\#args} -body {
    namespacex state drop
} -returnCodes error -result {wrong # args: should be "namespacex state drop ns"}

test namespacex-state-drop-1.1 {namespacex state drop, wrong\#args} -body {
    namespacex state drop N X
} -returnCodes error -result {wrong # args: should be "namespacex state drop ns"}

test namespacex-state-drop-2.0.0 {namespacex state drop} -setup {
    ns2_setup
} -body {
    namespacex state drop ::X
    dictsort [namespacex state get ::X]
} -cleanup {
    namespace delete ::X
} -result {}

test namespacex-state-drop-2.0.1 {namespacex state drop} -setup {
    ns2_setup
} -body {
    namespacex state drop X
    dictsort [namespacex state get X]
} -cleanup {
    namespace delete ::X
} -result {}

test namespacex-state-drop-2.1.0 {namespacex state drop} -setup {
    namespace eval ::X {}
} -body {
    namespacex state drop X
    dictsort [namespacex state get ::X]
} -cleanup {
    namespace delete ::X
} -result {}

test namespacex-state-drop-2.1.1 {namespacex state drop} -setup {
    namespace eval ::X {}
} -body {
    namespacex state drop X
    dictsort [namespacex state get X]
} -cleanup {
    namespace delete ::X
} -result {}

test namespacex-state-drop-2.2.0 {namespacex state drop} -setup {
    ns3_setup
} -body {
    namespacex state drop X
    dictsort [namespacex state get ::X]
} -cleanup {
    namespace delete ::X
} -result {}

test namespacex-state-drop-2.2.1 {namespacex state drop} -setup {
    ns3_setup
} -body {
    namespacex state drop X
    dictsort [namespacex state get X]
} -cleanup {
    namespace delete ::X
} -result {}

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

test namespacex-state-set-1.0 {namespacex state set, wrong\#args} -body {
    namespacex state set
} -returnCodes error -result {wrong # args: should be "namespacex state set ns state"}

test namespacex-state-set-1.1 {namespacex state set, wrong\#args} -body {
    namespacex state set N
} -returnCodes error -result {wrong # args: should be "namespacex state set ns state"}

test namespacex-state-set-1.2 {namespacex state set, wrong\#args} -body {
    namespacex state set N S X
} -returnCodes error -result {wrong # args: should be "namespacex state set ns state"}

test namespacex-state-set-2.0.0 {namespacex state set} -setup {
    ns2_setup
    set ST [namespacex state get ::X]
    ns3_setup
} -body {
    namespacex state set ::X $ST
    dictsort [namespacex state get ::X]
} -cleanup {
    namespace delete ::X
} -result {B::vB 3 vXa 1 vXb aleph}

test namespacex-state-set-2.0.1 {namespacex state set} -setup {
    ns2_setup
    set ST [namespacex state get ::X]
    ns3_setup
} -body {
    namespacex state set X $ST
    dictsort [namespacex state get X]
} -cleanup {
    namespace delete ::X
} -result {B::vB 3 vXa 1 vXb aleph}

test namespacex-state-set-2.1.0 {namespacex state set} -setup {
    ns3_setup
    set ST [namespacex state get ::X]
    ns2_setup
} -body {
    namespacex state set ::X $ST
    dictsort [namespacex state get ::X]
} -cleanup {
    namespace delete ::X
} -result {B::vB mjolnir}

test namespacex-state-set-2.1.1 {namespacex state set} -setup {
    ns3_setup
    set ST [namespacex state get ::X]
    ns2_setup
} -body {
    namespacex state set X $ST
    dictsort [namespacex state get X]
} -cleanup {
    namespace delete ::X
} -result {B::vB mjolnir}

# -------------------------------------------------------------------------
testsuiteCleanup

# Local variables:
# mode: tcl
# indent-tabs-mode: nil
# End:


















































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

testing {
    useLocal namespacex.tcl namespacex
}

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


namespace eval Q {
    proc ns_setup {} {
	namespace eval X {
	    namespace eval A {}
	    namespace eval B {
		namespace eval D {}
	    }
	    namespace eval C {}
	}
    }

    proc ns2_setup {} {
	namespace eval X::Y {
	    variable vXa 1
	    variable vXb aleph
	    namespace eval B {
		variable vB 3
	    }
	}
    }

    proc ns3_setup {} {
	namespace eval X {
	    namespace eval B {
		variable vB mjolnir
	    }
	}
    }

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


    test namespacex-info-allchildren-1.0 {namespacex info allchildren, wrong\#args} -body {
	namespacex info allchildren
    } -returnCodes error -result {wrong # args: should be "namespacex info allchildren ns"}


    test namespacex-info-allchildren-1.1 {namespacex info allchildren, wrong\#args} -body {
	namespacex info allchildren N X
    } -returnCodes error -result {wrong # args: should be "namespacex info allchildren ns"}


    test namespacex-info-allchildren-2.0.0 {namespacex info allchildren} -setup {
	ns_setup
    } -body {
	lsort -dict [namespacex strip [namespace current] [namespacex info allchildren X]]
    } -cleanup {
	namespace delete X
    } -result {X::A X::B X::B::D X::C}


    test namespacex-info-allchildren-2.0.1 {namespacex info allchildren} -setup {
	ns_setup
    } -body {
	lsort -dict [namespacex strip [namespace current] [namespacex info allchildren X]]
    } -cleanup {
	namespace delete X
    } -result {X::A X::B X::B::D X::C}

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


    test namespacex-info-vars-1.0 {namespacex info vars, wrong\#args} -body {
	namespacex info vars
    } -returnCodes error -result {wrong # args: should be "namespacex info vars ns ?pattern?"}


    test namespacex-info-vars-1.1 {namespacex info vars, wrong\#args} -body {
	namespacex info vars N P X
    } -returnCodes error -result {wrong # args: should be "namespacex info vars ns ?pattern?"}


    test namespacex-info-vars-2.0 {namespacex info vars} -setup {
	ns2_setup
    } -body {
	lsort -dict [namespacex info vars X::::Y]
    } -cleanup {
	namespace delete X
    } -result {vXa vXb}


    test namespacex-info-vars-2.1 {namespacex info vars} -setup {
	namespace eval X {}
    } -body {
	lsort -dict [namespacex info vars X]
    } -cleanup {
	namespace delete X
    } -result {}


    test namespacex-info-vars-2.2 {namespacex info vars} -setup {
	ns3_setup
    } -body {
	lsort -dict [namespacex info vars X]
    } -cleanup {
	namespace delete X
    } -result {}

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


    test namespacex-info-allvars-1.0 {namespacex info allvars, wrong\#args} -body {
	namespacex info allvars
    } -returnCodes error -result {wrong # args: should be "namespacex info allvars ns"}


    test namespacex-info-allvars-1.1 {namespacex info allvars, wrong\#args} -body {
	namespacex info allvars N X
    } -returnCodes error -result {wrong # args: should be "namespacex info allvars ns"}


    test namespacex-info-allvars-2.0.0 {namespacex info allvars} -setup {
	ns2_setup
    } -body {
	lsort -dict [namespacex info allvars X::::Y]
    } -cleanup {
	namespace delete X
    } -result {B::vB vXa vXb}


    test namespacex-info-allvars-2.0.1 {namespacex info allvars} -setup {
	ns2_setup
    } -body {
	lsort -dict [namespacex info allvars X::Y]
    } -cleanup {
	namespace delete X
    } -result {B::vB vXa vXb}


    test namespacex-info-allvars-2.1.0 {namespacex info allvars} -setup {
	namespace eval X {}
    } -body {
	lsort -dict [namespacex info allvars X]
    } -cleanup {
	namespace delete X
    } -result {}


    test namespacex-info-allvars-2.1.1 {namespacex info allvars} -setup {
	namespace eval X {}
    } -body {
	lsort -dict [namespacex info allvars X]
    } -cleanup {
	namespace delete X
    } -result {}


    test namespacex-info-allvars-2.2.0 {namespacex info allvars} -setup {
	ns3_setup
    } -body {
	lsort -dict [namespacex info allvars X]
    } -cleanup {
	namespace delete X
    } -result {B::vB}


    test namespacex-info-allvars-2.2.1 {namespacex info allvars} -setup {
	ns3_setup
    } -body {
	lsort -dict [namespacex info allvars X]
    } -cleanup {
	namespace delete X
    } -result {B::vB}

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


    test namespacex-state-get-1.0 {namespacex state get, wrong\#args} -body {
	namespacex state get
    } -returnCodes error -result {wrong # args: should be "namespacex state get ns"}


    test namespacex-state-get-1.1 {namespacex state get, wrong\#args} -body {
	namespacex state get N X
    } -returnCodes error -result {wrong # args: should be "namespacex state get ns"}


    test namespacex-state-get-2.0.0 {namespacex state get} -setup {
	ns2_setup
    } -body {
	dictsort [namespacex state get X::Y]
    } -cleanup {
	namespace delete X
    } -result {B::vB 3 vXa 1 vXb aleph}


    test namespacex-state-get-2.0.1 {namespacex state get} -setup {
	ns2_setup
    } -body {
	dictsort [namespacex state get X::Y]
    } -cleanup {
	namespace delete X
    } -result {B::vB 3 vXa 1 vXb aleph}


    test namespacex-state-get-2.1.0 {namespacex state get} -setup {
	namespace eval ::X {}
    } -body {
	dictsort [namespacex state get ::X]
    } -cleanup {
	namespace delete ::X
    } -result {}


    test namespacex-state-get-2.1.1 {namespacex state get} -setup {
	namespace eval X {}
    } -body {
	dictsort [namespacex state get X]
    } -cleanup {
	namespace delete X
    } -result {}


    test namespacex-state-get-2.2.0 {namespacex state get} -setup {
	ns3_setup
    } -body {
	dictsort [namespacex state get X]
    } -cleanup {
	namespace delete X
    } -result {B::vB mjolnir}


    test namespacex-state-get-2.2.1 {namespacex state get} -setup {
	ns3_setup
    } -body {
	dictsort [namespacex state get X]
    } -cleanup {
	namespace delete X
    } -result {B::vB mjolnir}

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


    test namespacex-state-drop-1.0 {namespacex state drop, wrong\#args} -body {
	namespacex state drop
    } -returnCodes error -result {wrong # args: should be "namespacex state drop ns"}


    test namespacex-state-drop-1.1 {namespacex state drop, wrong\#args} -body {
	namespacex state drop N X
    } -returnCodes error -result {wrong # args: should be "namespacex state drop ns"}


    test namespacex-state-drop-2.0.0 {namespacex state drop} -setup {
	ns2_setup
    } -body {
	namespacex state drop X
	dictsort [namespacex state get X]
    } -cleanup {
	namespace delete X
    } -result {}


    test namespacex-state-drop-2.0.1 {namespacex state drop} -setup {
	ns2_setup
    } -body {
	namespacex state drop X
	dictsort [namespacex state get X]
    } -cleanup {
	namespace delete X
    } -result {}


    test namespacex-state-drop-2.1.0 {namespacex state drop} -setup {
	namespace eval X {}
    } -body {
	namespacex state drop X
	dictsort [namespacex state get X]
    } -cleanup {
	namespace delete X
    } -result {}


    test namespacex-state-drop-2.1.1 {namespacex state drop} -setup {
	namespace eval X {}
    } -body {
	namespacex state drop X
	dictsort [namespacex state get X]
    } -cleanup {
	namespace delete X
    } -result {}


    test namespacex-state-drop-2.2.0 {namespacex state drop} -setup {
	ns3_setup
    } -body {
	namespacex state drop X
	dictsort [namespacex state get X]
    } -cleanup {
	namespace delete X
    } -result {}


    test namespacex-state-drop-2.2.1 {namespacex state drop} -setup {
	ns3_setup
    } -body {
	namespacex state drop X
	dictsort [namespacex state get X]
    } -cleanup {
	namespace delete X
    } -result {}

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


    test namespacex-state-set-1.0 {namespacex state set, wrong\#args} -body {
	namespacex state set
    } -returnCodes error -result {wrong # args: should be "namespacex state set ns state"}


    test namespacex-state-set-1.1 {namespacex state set, wrong\#args} -body {
	namespacex state set N
    } -returnCodes error -result {wrong # args: should be "namespacex state set ns state"}


    test namespacex-state-set-1.2 {namespacex state set, wrong\#args} -body {
	namespacex state set N S X
    } -returnCodes error -result {wrong # args: should be "namespacex state set ns state"}


    test namespacex-state-set-2.0.0 {namespacex state set} -setup {
	ns2_setup
	set ST [namespacex state get X::Y]
	ns3_setup
    } -body {
	namespacex state set X::Y $ST
	dictsort [namespacex state get X::Y]
    } -cleanup {
	namespace delete X
    } -result {B::vB 3 vXa 1 vXb aleph}


    test namespacex-state-set-2.0.1 {namespacex state set} -setup {
	ns2_setup
	set ST [namespacex state get X::Y]
	ns3_setup
    } -body {
	namespacex state set X::Y $ST
	dictsort [namespacex state get X::Y]
    } -cleanup {
	namespace delete X::Y
    } -result {B::vB 3 vXa 1 vXb aleph}


    test namespacex-state-set-2.1.0 {namespacex state set} -setup {
	ns3_setup
	set ST [namespacex state get X]
	ns2_setup
    } -body {
	namespacex state set X $ST
	dictsort [namespacex state get X]
    } -cleanup {
	namespace delete X
    } -result {B::vB mjolnir}


    test namespacex-state-set-2.1.1 {namespacex state set} -setup {
	ns3_setup
	set ST [namespacex state get X]
	ns2_setup
    } -body {
	namespacex state set X $ST
	dictsort [namespacex state get X]
    } -cleanup {
	namespace delete X
    } -result {B::vB mjolnir}

    # -------------------------------------------------------------------------
    testsuiteCleanup

    # Local variables:
    # mode: tcl
    # indent-tabs-mode: nil
    # End:
}