Changes On Branch errors_and_callbacks

Changes In Branch errors_and_callbacks Excluding Merge-Ins

This is equivalent to a diff from 1924dcd361 to cdb51c799e

2023-07-30
03:21
Merged errors_and_callbacks branch into master check-in: dbe759a0f2 user: bohagan tags: trunk
02:53
Updated default callbacks in tls.tcl file Leaf check-in: cdb51c799e user: bohagan tags: errors_and_callbacks
02:09
Add match result to ALPN callback parameters. This indicates if a common protocol was found or not. check-in: 75f1cfb376 user: bohagan tags: errors_and_callbacks
2023-07-16
15:21
Created error handler and callback updates branch check-in: 0d1d711916 user: bohagan tags: errors_and_callbacks
15:05
Merge status and X509 updates branch check-in: 1924dcd361 user: bohagan tags: trunk
03:33
X509 status optimizations to reduce number of buffers and reordered parameters to match certificate order. check-in: 335b04b2fe user: bohagan tags: status_x509
2023-05-13
20:25
Merged TEA branch into master check-in: 6c02d4d029 user: bohagan tags: trunk

Modified doc/tls.html from [a1837c5221] to [3c88bc4018].

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







-
+




-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







</head>

<body bgcolor="#FFFFFF">

<dl>
    <dd><a href="#NAME">NAME</a>
    <dl>
        <dd><b>tls</b> - binding to <b>OpenSSL</b> toolkit.</dd>
	<dd><b>tls</b> - binding to <b>OpenSSL</b> toolkit.</dd>
    </dl>
    </dd>
    <dd><a href="#SYNOPSIS">SYNOPSIS</a> </dd>
    <dd><dl>
            <dd><b>package require Tcl</b> <em>?8.4?</em></dd>
            <dd><b>package require tls</b></dd>
            <dt>&nbsp;</dt>
            <dd><b>tls::init</b> <em>?options?</em> </dd>
            <dd><b>tls::socket</b> <em>?options? host port</em></dd>
            <dd><b>tls::socket</b> <em> ?-server command? ?options? port</em></dd>
            <dd><b>tls::handshake</b> <em> channel</em></dd>
            <dd><b>tls::status </b> <em>?-local? channel</em></dd>
            <dd><b>tls::connection </b> <em>channel</em></dd>
            <dd><b>tls::import</b> <em>channel ?options?</em></dd>
            <dd><b>tls::unimport</b> <em>channel</em></dd>
            <dt>&nbsp;</dt>
            <dd><b>tls::ciphers </b> <em>protocol ?verbose? ?supported?</em></dd>
            <dd><b>tls::protocols</b></dd>
            <dd><b>tls::version</b></dd>
        </dl>
	    <dd><b>package require Tcl</b> <em>?8.4?</em></dd>
	    <dd><b>package require tls</b></dd>
	    <dt>&nbsp;</dt>
	    <dd><b>tls::init</b> <em>?options?</em> </dd>
	    <dd><b>tls::socket</b> <em>?options? host port</em></dd>
	    <dd><b>tls::socket</b> <em> ?-server command? ?options? port</em></dd>
	    <dd><b>tls::handshake</b> <em> channel</em></dd>
	    <dd><b>tls::status </b> <em>?-local? channel</em></dd>
	    <dd><b>tls::connection </b> <em>channel</em></dd>
	    <dd><b>tls::import</b> <em>channel ?options?</em></dd>
	    <dd><b>tls::unimport</b> <em>channel</em></dd>
	    <dt>&nbsp;</dt>
	    <dd><b>tls::ciphers </b> <em>protocol ?verbose? ?supported?</em></dd>
	    <dd><b>tls::protocols</b></dd>
	    <dd><b>tls::version</b></dd>
	</dl>
    </dd>
    <dd><a href="#COMMANDS">COMMANDS</a></dd>
    <dd><a href="#CALLBACK OPTIONS">CALLBACK OPTIONS</a></dd>
    <dd><a href="#HTTPS EXAMPLE">HTTPS EXAMPLE</a></dd>
    <dd><a href="#SEE ALSO">SPECIAL CONSIDERATIONS</a></dd>
    <dd><a href="#SEE ALSO">SEE ALSO</a></dd>
</dl>
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
395
396
397
398
399
400
401
402


















403
404
405
406
407
408
409

410
411
412
413
414
415
416
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
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







-
-
-
-
+
+
+
+


-
+


-
-
-
-
-
+
+
+
+
+


-
-
-
+
+
+




-
+

-
-
+
+



-
-
-
-
+
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
-
-
-
-
+
+

-
-
+
+








-
-
+
+

-
-
+
+





-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
+
+



-
-
-
-
-
+
+
+
+
+

-
-
-
+
+
+





-
-
-
-
-
+
+
+
+
+



-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+










-
-
-
+
+
+






-
+




-
-
+
+

-
-
-
-
-
-
-
+
+
+
+
+
+
+

-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+





-
-
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+


-
-
-
-
+
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
+
+


-
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
+
+
+
+






-
-
+
+



-
-
-
-
-
-
+
+
+
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+





-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+





-
-
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+






-
+







command. In such cases <strong>tls::import</strong> should not be
used directly.</p>

<dl>
    <dt><a name="tls::init"><b>tls::init </b><i>?options?</i></a></dt>
    <dd>Optional function to set the default options used by
	<strong>tls::socket</strong>. If you call <strong>tls::import</strong>
        directly this routine has no effect. Any of the options
        that <strong>tls::socket</strong> accepts can be set
        using this command, though you should limit your options
        to only TLS related ones.</dd>
	directly this routine has no effect. Any of the options
	that <strong>tls::socket</strong> accepts can be set
	using this command, though you should limit your options
	to only TLS related ones.</dd>
    <dt>&nbsp;</dt>
    <dt><a name="tls::socket"><b>tls::socket </b><em>?options?
        host port</em></a></dt>
	host port</em></a></dt>
    <dt><b>tls::socket</b><em> ?-server command? ?options? port</em></dt>
    <dd>This is a helper function that utilizes the underlying
        commands (<strong>tls::import</strong>). It behaves
        exactly the same as the native Tcl <strong>socket</strong>
        command except that the options can include any of the
        applicable <a href="#tls::import"><strong>tls:import</strong></a>
        options with one additional option:
	commands (<strong>tls::import</strong>). It behaves
	exactly the same as the native Tcl <strong>socket</strong>
	command except that the options can include any of the
	applicable <a href="#tls::import"><strong>tls:import</strong></a>
	options with one additional option:
<blockquote>
    <dl>
        <dt><strong>-autoservername</strong> <em>bool</em></dt>
        <dd>Automatically send the -servername as the <em>host</em> argument
            (default is <em>false</em>)</dd>
	<dt><strong>-autoservername</strong> <em>bool</em></dt>
	<dd>Automatically send the -servername as the <em>host</em> argument
	    (default is <em>false</em>)</dd>
    </dl>
</blockquote>

    <dt><a name="tls::import"><b>tls::import </b><i>channel
        ?options?</i></a></dt>
	?options?</i></a></dt>
    <dd>SSL-enable a regular Tcl channel - it need not be a
        socket, but must provide bi-directional flow. Also
        setting session parameters for SSL handshake.</dd>
	socket, but must provide bi-directional flow. Also
	setting session parameters for SSL handshake.</dd>

<blockquote>
    <dl>
        <dt><strong>-alpn</strong> <em>list</em></dt>
        <dd>List of protocols to offer during Application-Layer
	    Protocol Negotiation (ALPN). For example: h2, http/1.1, etc.</dd>
        <dt><strong>-cadir</strong> <em>dir</em></dt>
	<dt><strong>-alpn</strong> <em>list</em></dt>
	<dd>List of protocols to offer during Application-Layer
	    Protocol Negotiation (ALPN). For example: <em>h2</em> and
	    <em>http/1.1</em>, but not <em>h3</em> or <em>quic</em>.</dd>
	<dt><strong>-cadir</strong> <em>dir</em></dt>
        <dd>Specify the directory containing the CA certificates. The
	    default directory is platform specific and can be set at
	    compile time. This can be overridden via the <b>SSL_CERT_DIR</b>
	    environment variable.</dd>
        <dt><strong>-cafile </strong><em>filename</em></dt>
        <dd>Specify the certificate authority (CA) file to use.</dd>
        <dt><strong>-certfile</strong> <em>filename</em></dt>
        <dd>Specify the filename containing the certificate to use. The
	<dd>Set the CA certificates path. The default directory is platform
	    specific and can be set at compile time. This can be overridden
	    via the <b>SSL_CERT_DIR</b> environment variable.</dd>
	<dt><strong>-cafile </strong><em>filename</em></dt>
	<dd>Set the certificate authority (CA) certificates file. The default
	    is the cert.pem file in the OpsnSSL directory. This can also be
	    overridden via the <b>SSL_CERT_FILE</b> environment variable.</dd>
	<dt><strong>-certfile</strong> <em>filename</em></dt>
	<dd>Specify the filename with the certificate to use.</dd>
	    default name is <b>cert.pem</b>. This can be overridden via
	    the <b>SSL_CERT_FILE</b> environment variable.</dd>
        <dt><strong>-cert</strong> <em>filename</em></dt>
        <dd>Specify the contents of a certificate to use, as a DER
	<dt><strong>-cert</strong> <em>filename</em></dt>
	<dd>Specify the contents of a certificate to use, as a DER
	    encoded binary value (X.509 DER).</dd>
        <dt><strong>-cipher</strong> <em>string</em></dt>
        <dd>List of ciphers to use. String is a colon (":") separated list
	<dt><strong>-cipher</strong> <em>string</em></dt>
	<dd>List of ciphers to use. String is a colon (":") separated list
	    of ciphers or cipher suites. Cipher suites can be combined
	    using the <b>+</b> character. Prefixes can be used to permanently
	    remove ("!"), delete ("-"), or move a cypher to the end of
	    the list ("+"). Keywords <b>@STRENGTH</b> (sort by algorithm
	    key length), <b>@SECLEVEL=</b><i>n</i> (set security level to
	    n), and <b>DEFAULT</b> (use default cipher list, at start only)
	    can also be specified. See OpenSSL documentation for the full
	    list of valid values. (TLS 1.2 and earlier only)</dd>
        <dt><strong>-ciphersuites</strong> <em>string</em></dt>
        <dd>List of cipher suites to use. String is a colon (":")
	<dt><strong>-ciphersuites</strong> <em>string</em></dt>
	<dd>List of cipher suites to use. String is a colon (":")
	    separated list of cipher suite names. (TLS 1.3 only)</dd>
        <dt><strong>-command</strong> <em>callback</em></dt>
        <dd>Callback to invoke at several points during the handshake.
	<dt><strong>-command</strong> <em>callback</em></dt>
	<dd>Callback to invoke at several points during the handshake.
	    This is used to pass errors and tracing information, and
	    it can allow Tcl scripts to perform their own certificate
	    validation in place of the default validation provided by
	    OpenSSL. See <a href="#CALLBACK OPTIONS">CALLBACK OPTIONS</a>
	    for further discussion.</dd>
        <dt><strong>-dhparams </strong><em>filename</em></dt>
        <dd>Specify the Diffie-Hellman parameters file.</dd>
        <dt><strong>-keyfile</strong> <em>filename</em></dt>
        <dd>Specify the private key file. (default is
            value of -certfile)</dd>
        <dt><strong>-key</strong> <em>filename</em></dt>
        <dd>Specify the private key to use as a DER encoded value (PKCS#1 DER)</dd>
        <dt><strong>-model</strong> <em>channel</em></dt>
        <dd>Force this channel to share the same <em><strong>SSL_CTX</strong></em>
            structure as the specified <em>channel</em>, and
            therefore share callbacks etc.</dd>
        <dt><strong>-password</strong> <em>callback</em></dt>
        <dd>Callback to invoke when OpenSSL needs to obtain a password,
	<dt><strong>-dhparams </strong><em>filename</em></dt>
	<dd>Specify the Diffie-Hellman parameters file.</dd>
	<dt><strong>-keyfile</strong> <em>filename</em></dt>
	<dd>Specify the private key file. (default is
	    value of -certfile)</dd>
	<dt><strong>-key</strong> <em>filename</em></dt>
	<dd>Specify the private key to use as a DER encoded value (PKCS#1 DER)</dd>
	<dt><strong>-model</strong> <em>channel</em></dt>
	<dd>Force this channel to share the same <em><strong>SSL_CTX</strong></em>
	    structure as the specified <em>channel</em>, and
	    therefore share callbacks etc.</dd>
	<dt><strong>-password</strong> <em>callback</em></dt>
	<dd>Callback to invoke when OpenSSL needs to obtain a password,
	    typically to unlock the private key of a certificate. The
            callback should return a string which represents the password
            to be used. See <a href="#CALLBACK OPTIONS">CALLBACK OPTIONS</a>
	    callback should return a string which represents the password
	    to be used. See <a href="#CALLBACK OPTIONS">CALLBACK OPTIONS</a>
	    for further discussion.</dd>
	<dt><strong>-post_handshake</strong> <em>bool</em></dt>
	<dd>Allow post-handshake ticket updates.</dd>
        <dt><strong>-request </strong><em>bool</em></dt>
        <dd>Request a certificate from peer during SSL handshake.
            (default is <em>true</em>)</dd>
        <dt><strong>-require</strong> <em>bool</em></dt>
        <dd>Require a valid certificate from peer during SSL handshake.
	<dt><strong>-request </strong><em>bool</em></dt>
	<dd>Request a certificate from peer during SSL handshake.
	    (default is <em>true</em>)</dd>
	<dt><strong>-require</strong> <em>bool</em></dt>
	<dd>Require a valid certificate from peer during SSL handshake.
	    If this is set to true, then <strong>-request</strong> must
            also be set to true. (default is <em>false</em>)</dd>
        <dt><strong>-securitylevel</strong> <em>integer</em></dt>
        <dd>Set security level. Must be 0 to 5. The security level affects
	    also be set to true. (default is <em>false</em>)</dd>
	<dt><strong>-securitylevel</strong> <em>integer</em></dt>
	<dd>Set security level. Must be 0 to 5. The security level affects
	    cipher suite encryption algorithms, supported ECC curves,
	    supported signature algorithms, DH parameter sizes, certificate
	    key sizes and signature algorithms. The default is 1.
	    Level 3 and higher disable support for session tickets and only
	    accept cipher suites that provide forward secrecy.</dd>
        <dt><strong>-server</strong> <em>bool</em></dt>
        <dd>Handshake as server if true, else handshake as
            client. (default is <em>false</em>)</dd>
        <dt><strong>-servername</strong> <em>host</em></dt>
        <dd>Specify server hostname. Only available if the OpenSSL library
	<dt><strong>-server</strong> <em>bool</em></dt>
	<dd>Handshake as server if true, else handshake as
	    client. (default is <em>false</em>)</dd>
	<dt><strong>-servername</strong> <em>host</em></dt>
	<dd>Specify server hostname. Only available if the OpenSSL library
	    the package is linked against supports the TLS hostname extension
	    for 'Server Name Indication' (SNI). Use to name the logical host
	    we are talking to and expecting a certificate for.</dd>
        <dt><strong>-session_id</strong> <em>string</em></dt>
        <dd>Session id to resume session.</dd>
        <dt><strong>-ssl2</strong> <em>bool</em></dt>
        <dd>Enable use of SSL v2. (default is <em>false</em>)</dd>
        <dt><strong>-ssl3 </strong><em>bool</em></dt>
        <dd>Enable use of SSL v3. (default is <em>false</em>)</dd>
        <dt>-<strong>tls1</strong> <em>bool</em></dt>
        <dd>Enable use of TLS v1. (default is <em>true</em>)</dd>
        <dt>-<strong>tls1.1</strong> <em>bool</em></dt>
        <dd>Enable use of TLS v1.1 (default is <em>true</em>)</dd>
        <dt>-<strong>tls1.2</strong> <em>bool</em></dt>
        <dd>Enable use of TLS v1.2 (default is <em>true</em>)</dd>
        <dt>-<strong>tls1.3</strong> <em>bool</em></dt>
        <dd>Enable use of TLS v1.3 (default is <em>true</em>)</dd>
	<dt><strong>-session_id</strong> <em>string</em></dt>
	<dd>Session id to resume session.</dd>
	<dt><strong>-ssl2</strong> <em>bool</em></dt>
	<dd>Enable use of SSL v2. (default is <em>false</em>)</dd>
	<dt><strong>-ssl3 </strong><em>bool</em></dt>
	<dd>Enable use of SSL v3. (default is <em>false</em>)</dd>
	<dt>-<strong>tls1</strong> <em>bool</em></dt>
	<dd>Enable use of TLS v1. (default is <em>true</em>)</dd>
	<dt>-<strong>tls1.1</strong> <em>bool</em></dt>
	<dd>Enable use of TLS v1.1 (default is <em>true</em>)</dd>
	<dt>-<strong>tls1.2</strong> <em>bool</em></dt>
	<dd>Enable use of TLS v1.2 (default is <em>true</em>)</dd>
	<dt>-<strong>tls1.3</strong> <em>bool</em></dt>
	<dd>Enable use of TLS v1.3 (default is <em>true</em>)</dd>
	<dt><strong>-validatecommand</strong> <em>callback</em></dt>
	<dd>Callback to invoke to verify or validate protocol config
	    parameters during the protocol negotiation phase. See
	    <a href="#CALLBACK OPTIONS">CALLBACK OPTIONS</a>
	    for further discussion.</dd>
    </dl>
</blockquote>

    <dt><a name="tls::unimport"><b>tls::unimport </b><i>channel</i></a></dt>
    <dd>Provided for symmetry to <strong>tls::import</strong>, this
      unstacks the SSL-enabling of a regular Tcl channel.  An error
      is thrown if TLS is not the top stacked channel type.</dd>
    <dt>&nbsp;</dt>
    <dt><a name="tls::handshake"><strong>tls::handshake</strong> <em>channel</em></a></dt>
    <dd>Forces handshake to take place, and returns 0 if
        handshake is still in progress (non-blocking), or 1 if
        the handshake was successful. If the handshake failed
        this routine will throw an error.</dd>
	handshake is still in progress (non-blocking), or 1 if
	the handshake was successful. If the handshake failed
	this routine will throw an error.</dd>
    <dt>&nbsp;</dt>
    <dt><a name="tls::status"><strong>tls::status</strong>
    <em>?-local? channel</em></a></dt>
    <dd>Returns the current status of the certificate for an SSL
	channel. The result is a list of key-value pairs describing
	the certificate. If the result is an empty list then the
        SSL handshake has not yet completed. If <em>-local</em> is
	SSL handshake has not yet completed. If <em>-local</em> is
	specified, then the local certificate is used.</dd>
<blockquote>
	<b>SSL Status</b>
    <dl>
        <dt><strong>alpn</strong> <em>protocol</em></dt>
        <dd>The protocol selected after Application-Layer Protocol
	<dt><strong>alpn</strong> <em>protocol</em></dt>
	<dd>The protocol selected after Application-Layer Protocol
	    Negotiation (ALPN).</dd>
        <dt><strong>cipher</strong> <em>cipher</em></dt>
        <dd>The current cipher in use between the client and
            server channels.</dd>
        <dt><strong>peername</strong> <em>name</em></dt>
        <dd>The peername from the certificate.</dd>
        <dt><strong>protocol</strong> <em>version</em></dt>
        <dd>The protocol version used for the connection:
	<dt><strong>cipher</strong> <em>cipher</em></dt>
	<dd>The current cipher in use between the client and
	    server channels.</dd>
	<dt><strong>peername</strong> <em>name</em></dt>
	<dd>The peername from the certificate.</dd>
	<dt><strong>protocol</strong> <em>version</em></dt>
	<dd>The protocol version used for the connection:
	    SSL2, SSL3, TLS1, TLS1.1, TLS1.2, TLS1.3, or unknown.</dd>
        <dt><strong>sbits</strong> <em>n</em></dt>
        <dd>The number of bits used for the session key.</dd>
        <dt><strong>signatureHashAlgorithm</strong> <em>algorithm</em></dt>
        <dd>The signature hash algorithm.</dd>
        <dt><strong>signature_type</strong> <em>type</em></dt>
        <dd>The signature type value.</dd>
        <dt><strong>verification</strong> <em>result</em></dt>
        <dd>Certificate verification result.</dd>
        <dt><strong>ca_names</strong> <em>list</em></dt>
        <dd>List of the Certificate Authorities used to create the certificate.</dd>
	<dt><strong>sbits</strong> <em>n</em></dt>
	<dd>The number of bits used for the session key.</dd>
	<dt><strong>signatureHashAlgorithm</strong> <em>algorithm</em></dt>
	<dd>The signature hash algorithm.</dd>
	<dt><strong>signature_type</strong> <em>type</em></dt>
	<dd>The signature type value.</dd>
	<dt><strong>verification</strong> <em>result</em></dt>
	<dd>Certificate verification result.</dd>
	<dt><strong>ca_names</strong> <em>list</em></dt>
	<dd>List of the Certificate Authorities used to create the certificate.</dd>
    </dl>
</blockquote>
<blockquote>
	<b>Certificate Status</b>
    <dl>
        <dt><strong>all</strong> <em>string</em></dt>
        <dd>Dump of all certificate info.</dd>
	<dt><strong>all</strong> <em>string</em></dt>
	<dd>Dump of all certificate info.</dd>

        <dt><strong>version</strong> <em>value</em></dt>
        <dd>The certificate version.</dd>
        <dt><strong>serialNumber</strong> <em>n</em></dt>
        <dd>The serial number of the certificate as hex string.</dd>
        <dt><strong>signature</strong> <em>algorithm</em></dt>
        <dd>Cipher algorithm used for certificate signature.</dd>
        <dt><strong>issuer</strong> <em>dn</em></dt>
        <dd>The distinguished name (DN) of the certificate issuer.</dd>
        <dt><strong>notBefore</strong> <em>date</em></dt>
        <dd>The begin date for the validity of the certificate.</dd>
        <dt><strong>notAfter</strong> <em>date</em></dt>
        <dd>The expiration date for the certificate.</dd>
        <dt><strong>subject</strong> <em>dn</em></dt>
        <dd>The distinguished name (DN) of the certificate subject.
	<dt><strong>version</strong> <em>value</em></dt>
	<dd>The certificate version.</dd>
	<dt><strong>serialNumber</strong> <em>n</em></dt>
	<dd>The serial number of the certificate as hex string.</dd>
	<dt><strong>signature</strong> <em>algorithm</em></dt>
	<dd>Cipher algorithm used for certificate signature.</dd>
	<dt><strong>issuer</strong> <em>dn</em></dt>
	<dd>The distinguished name (DN) of the certificate issuer.</dd>
	<dt><strong>notBefore</strong> <em>date</em></dt>
	<dd>The begin date for the validity of the certificate.</dd>
	<dt><strong>notAfter</strong> <em>date</em></dt>
	<dd>The expiration date for the certificate.</dd>
	<dt><strong>subject</strong> <em>dn</em></dt>
	<dd>The distinguished name (DN) of the certificate subject.
	    Fields include: Common Name (CN), Organization (O), Locality
	    or City (L), State or Province (S), and Country Name (C).</dd>
        <dt><strong>issuerUniqueID</strong> <em>string</em></dt>
        <dd>The issuer unique id.</dd>
        <dt><strong>subjectUniqueID</strong> <em>string</em></dt>
        <dd>The subject unique id.</dd>
	<dt><strong>issuerUniqueID</strong> <em>string</em></dt>
	<dd>The issuer unique id.</dd>
	<dt><strong>subjectUniqueID</strong> <em>string</em></dt>
	<dd>The subject unique id.</dd>

        <dt><strong>num_extensions</strong> <em>n</em></dt>
        <dd>Number of certificate extensions.</dd>
        <dt><strong>extensions</strong> <em>list</em></dt>
        <dd>List of certificate extension names.</dd>
        <dt><strong>authorityKeyIdentifier</strong> <em>string</em></dt>
        <dd>(AKI) Key identifier of the Issuing CA certificate that signed
	    the SSL certificate. This value matches the SKI value of the
	    Intermediate CA certificate.</dd>
        <dt><strong>subjectKeyIdentifier</strong> <em>string</em></dt>
        <dd>(SKI) Hash of the public key inside the certificate. Used to
	   identify certificates that contain a particular public key.</dd>
        <dt><strong>subjectAltName</strong> <em>list</em></dt>
        <dd>List of all of the alternative domain names, sub domains,
	<dt><strong>num_extensions</strong> <em>n</em></dt>
	<dd>Number of certificate extensions.</dd>
	<dt><strong>extensions</strong> <em>list</em></dt>
	<dd>List of certificate extension names.</dd>
	<dt><strong>authorityKeyIdentifier</strong> <em>string</em></dt>
	<dd>(AKI) Key identifier of the Issuing CA certificate that signed
	    the SSL certificate as hex string. This value matches the SKI
	    value of the Intermediate CA certificate.</dd>
	<dt><strong>subjectKeyIdentifier</strong> <em>string</em></dt>
	<dd>(SKI) Hash of the public key inside the certificate as hex
	   string. Used to identify certificates that contain a particular
	   public key.</dd>
	<dt><strong>subjectAltName</strong> <em>list</em></dt>
	<dd>List of all of the alternative domain names, sub domains,
	    and IP addresses that are secured by the certificate.</dd>
        <dt><strong>ocsp</strong> <em>list</em></dt>
        <dd>List of all OCSP URLs.</dd>
	<dt><strong>ocsp</strong> <em>list</em></dt>
	<dd>List of all Online Certificate Status Protocol (OCSP) URLs.</dd>

	<dt><strong>certificate</strong> <em>cert</em></dt>
        <dd>The PEM encoded certificate.</dd>
	<dd>The PEM encoded certificate.</dd>

        <dt><strong>signatureAlgorithm</strong> <em>algorithm</em></dt>
        <dd>Cipher algorithm used for certificate signature.</dd>
        <dt><strong>signatureValue</strong> <em>string</em></dt>
        <dd>Certificate signature as hex string.</dd>
        <dt><strong>signatureDigest</strong> <em>version</em></dt>
        <dd>Certificate signing digest.</dd>
        <dt><strong>publicKeyAlgorithm</strong> <em>algorithm</em></dt>
        <dd>Certificate signature public key algorithm.</dd>
        <dt><strong>publicKey</strong> <em>string</em></dt>
        <dd>Certificate signature public key as hex string.</dd>
        <dt><strong>bits</strong> <em>n</em></dt>
        <dd>Number of bits used for certificate signature key</dd>
        <dt><strong>self_signed</strong> <em>boolean</em></dt>
        <dd>Is certificate signature self signed.</dd>
	<dt><strong>signatureAlgorithm</strong> <em>algorithm</em></dt>
	<dd>Cipher algorithm used for certificate signature.</dd>
	<dt><strong>signatureValue</strong> <em>string</em></dt>
	<dd>Certificate signature as hex string.</dd>
	<dt><strong>signatureDigest</strong> <em>version</em></dt>
	<dd>Certificate signing digest.</dd>
	<dt><strong>publicKeyAlgorithm</strong> <em>algorithm</em></dt>
	<dd>Certificate signature public key algorithm.</dd>
	<dt><strong>publicKey</strong> <em>string</em></dt>
	<dd>Certificate signature public key as hex string.</dd>
	<dt><strong>bits</strong> <em>n</em></dt>
	<dd>Number of bits used for certificate signature key</dd>
	<dt><strong>self_signed</strong> <em>boolean</em></dt>
	<dd>Is certificate signature self signed.</dd>

        <dt><strong>sha1_hash</strong> <em>hash</em></dt>
        <dd>The SHA1 hash of the certificate as hex string.</dd>
        <dt><strong>sha256_hash</strong> <em>hash</em></dt>
        <dd>The SHA256 hash of the certificate as hex string.</dd>
	<dt><strong>sha1_hash</strong> <em>hash</em></dt>
	<dd>The SHA1 hash of the certificate as hex string.</dd>
	<dt><strong>sha256_hash</strong> <em>hash</em></dt>
	<dd>The SHA256 hash of the certificate as hex string.</dd>
    </dl>
</blockquote>

    <dt><a name="tls::connection"><strong>tls::connection</strong>
    <em>channel</em></a></dt>
    <dd>Returns the current connection status of an SSL channel. The
        result is a list of key-value pairs describing the
        connected peer.</dd>
	result is a list of key-value pairs describing the
	connected peer.</dd>
<blockquote>
	<b>SSL Status</b>
    <dl>
        <dt><strong>state</strong> <em>state</em></dt>
        <dd>State of the connection.</dd>
        <dt><strong>servername</strong> <em>name</em></dt>
        <dd>The name of the connected to server.</dd>
        <dt><strong>protocol</strong> <em>version</em></dt>
        <dd>The protocol version used for the connection:
	<dt><strong>state</strong> <em>state</em></dt>
	<dd>State of the connection.</dd>
	<dt><strong>servername</strong> <em>name</em></dt>
	<dd>The name of the connected to server.</dd>
	<dt><strong>protocol</strong> <em>version</em></dt>
	<dd>The protocol version used for the connection:
	    SSL2, SSL3, TLS1, TLS1.1, TLS1.2, TLS1.3, or unknown.</dd>
        <dt><strong>renegotiation</strong> <em>state</em></dt>
        <dd>Whether protocol renegotiation is supported or not.</dd>
        <dt><strong>securitylevel</strong> <em>level</em></dt>
        <dd>The security level used for selection of ciphers, key size, etc.</dd>
        <dt><strong>session_reused</strong> <em>boolean</em></dt>
        <dd>Whether the session has been reused or not.</dd>
        <dt><strong>is_server</strong> <em>boolean</em></dt>
        <dd>Whether the connection configured as a server or client (false).</dd>
        <dt><strong>compression</strong> <em>mode</em></dt>
        <dd>Compression method.</dd>
        <dt><strong>expansion</strong> <em>mode</em></dt>
        <dd>Expansion method.</dd>
	<dt><strong>renegotiation</strong> <em>boolean</em></dt>
	<dd>Whether protocol renegotiation is supported or not.</dd>
	<dt><strong>securitylevel</strong> <em>level</em></dt>
	<dd>The security level used for selection of ciphers, key size, etc.</dd>
	<dt><strong>session_reused</strong> <em>boolean</em></dt>
	<dd>Whether the session has been reused or not.</dd>
	<dt><strong>is_server</strong> <em>boolean</em></dt>
	<dd>Whether the connection is configured as a server (1) or client (0).</dd>
	<dt><strong>compression</strong> <em>mode</em></dt>
	<dd>Compression method.</dd>
	<dt><strong>expansion</strong> <em>mode</em></dt>
	<dd>Expansion method.</dd>
    </dl>
</blockquote>
<blockquote>
	<b>Cipher Info</b>
    <dl>
        <dt><strong>cipher</strong> <em>cipher</em></dt>
        <dd>The current cipher in use for the connection.</dd>
        <dt><strong>standard_name</strong> <em>name</em></dt>
        <dd>The standard RFC name of cipher.</dd>
        <dt><strong>bits</strong> <em>n</em></dt>
        <dd>The number of processed bits used for cipher.</dd>
        <dt><strong>secret_bits</strong> <em>n</em></dt>
        <dd>The number of secret bits used for cipher.</dd>
        <dt><strong>min_version</strong> <em>version</em></dt>
        <dd>The minimum protocol version for cipher.</dd>
        <dt><strong>id</strong> <em>id</em></dt>
        <dd>The OpenSSL cipher id.</dd>
        <dt><strong>description</strong> <em>string</em></dt>
        <dd>A text description of the cipher.</dd>
	<dt><strong>cipher</strong> <em>cipher</em></dt>
	<dd>The current cipher in use for the connection.</dd>
	<dt><strong>standard_name</strong> <em>name</em></dt>
	<dd>The standard RFC name of cipher.</dd>
	<dt><strong>bits</strong> <em>n</em></dt>
	<dd>The number of processed bits used for cipher.</dd>
	<dt><strong>secret_bits</strong> <em>n</em></dt>
	<dd>The number of secret bits used for cipher.</dd>
	<dt><strong>min_version</strong> <em>version</em></dt>
	<dd>The minimum protocol version for cipher.</dd>
	<dt><strong>id</strong> <em>id</em></dt>
	<dd>The OpenSSL cipher id.</dd>
	<dt><strong>description</strong> <em>string</em></dt>
	<dd>A text description of the cipher.</dd>
    </dl>
</blockquote>
<blockquote>
	<b>Session Info</b>
    <dl>
        <dt><strong>alpn</strong> <em>protocol</em></dt>
        <dd>The protocol selected after Application-Layer Protocol
	<dt><strong>alpn</strong> <em>protocol</em></dt>
	<dd>The protocol selected after Application-Layer Protocol
	    Negotiation (ALPN).</dd>
        <dt><strong>resumable</strong> <em>boolean</em></dt>
        <dd>Can the session be resumed or not.</dd>
        <dt><strong>start_time</strong> <em>seconds</em></dt>
        <dd>Time since session started in seconds since epoch.</dd>
        <dt><strong>timeout</strong> <em>seconds</em></dt>
        <dd>Max duration of session in seconds before time-out.</dd>
        <dt><strong>lifetime</strong> <em>seconds</em></dt>
        <dd>Session ticket lifetime hint in seconds.</dd>
        <dt><strong>session_id</strong> <em>string</em></dt>
        <dd>Unique session id for use in resuming the session.</dd>
        <dt><strong>session_ticket</strong> <em>string</em></dt>
        <dd>Unique session ticket for use in resuming the session.</dd>
        <dt><strong>ticket_app_data</strong> <em>string</em></dt>
        <dd>Unique session ticket application data.</dd>
        <dt><strong>master_key</strong> <em>binary_string</em></dt>
        <dd>Unique session master key.</dd>
        <dt><strong>session_cache_mode</strong> <em>mode</em></dt>
        <dd>Server cache mode (client, server, or both).</dd>
	<dt><strong>resumable</strong> <em>boolean</em></dt>
	<dd>Can the session be resumed or not.</dd>
	<dt><strong>start_time</strong> <em>seconds</em></dt>
	<dd>Time since session started in seconds since epoch.</dd>
	<dt><strong>timeout</strong> <em>seconds</em></dt>
	<dd>Max duration of session in seconds before time-out.</dd>
	<dt><strong>lifetime</strong> <em>seconds</em></dt>
	<dd>Session ticket lifetime hint in seconds.</dd>
	<dt><strong>session_id</strong> <em>binary_string</em></dt>
	<dd>Unique session id for use in resuming the session.</dd>
	<dt><strong>session_ticket</strong> <em>binary_string</em></dt>
	<dd>Unique session ticket for use in resuming the session.</dd>
	<dt><strong>ticket_app_data</strong> <em>binary_string</em></dt>
	<dd>Unique session ticket application data.</dd>
	<dt><strong>master_key</strong> <em>binary_string</em></dt>
	<dd>Unique session master key.</dd>
	<dt><strong>session_cache_mode</strong> <em>mode</em></dt>
	<dd>Server cache mode (client, server, or both).</dd>
    </dl>
</blockquote>

    <dt><a name="tls::ciphers"><strong>tls::ciphers</strong>
    <em>protocol ?verbose? ?supported?</em></a></dt>
    <dd>Returns a list of supported ciphers available for <em>protocol</em>,
        where protocol must be one of <b>ssl2, ssl3, tls1, tls1.1,
	where protocol must be one of <b>ssl2, ssl3, tls1, tls1.1,
	tls1.2,</b> or <b>tls1.3</b>. If <em>verbose</em> is specified as
	true then a verbose, human readable list is returned with
	additional information on the cipher. If <em>supported</em>
	is specified as true, then only the ciphers supported for protocol
	will be listed.</dd>

    <dt><a name="tls::protocols"><strong>tls::protocols</strong></a></dt>
424
425
426
427
428
429
430

431

432


433
434
435
436
437
438
439
440
441
442



443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471

472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489

490
491
492
493


494
495
496
497
498
499
500
501





502
503

504
505
506


507




508
509












510
511
512
513

514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
















576
577
578
579
580























































































581
582
583
584
585
586


587
588
589


590
591
592
593
594
595
596
597





598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614



615
616
617
618
619
620
621
622
623
624
625
626
627
628
629



630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650




651
652
653
654
655
656
657
658

659
660
661
662
663
664
665
430
431
432
433
434
435
436
437

438
439
440
441
442
443
444
445
446
447
448



449
450
451
452


453
454
455
456
457
458














459
460
461
462
463

464












465
466
467
468
469

470
471
472
473

474
475
476







477
478
479
480
481


482



483
484

485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505

506
507
508
509
510
511
512
513
514

515












































516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539





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


631
632
633


634
635
636
637
638





639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657



658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674

675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694




695
696
697
698








699
700
701
702
703
704
705
706







+
-
+

+
+







-
-
-
+
+
+

-
-






-
-
-
-
-
-
-
-
-
-
-
-
-
-





-
+
-
-
-
-
-
-
-
-
-
-
-
-





-
+



-
+
+

-
-
-
-
-
-
-
+
+
+
+
+
-
-
+
-
-
-
+
+
-
+
+
+
+


+
+
+
+
+
+
+
+
+
+
+
+



-
+








-

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-








+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+




-
-
+
+

-
-
+
+



-
-
-
-
-
+
+
+
+
+














-
-
-
+
+
+














-
+
+
+

















-
-
-
-
+
+
+
+
-
-
-
-
-
-
-
-
+







</dl>

<h3><a name="CALLBACK OPTIONS">CALLBACK OPTIONS</a></h3>

<p>
As indicated above, individual channels can be given their own callbacks
to handle intermediate processing by the OpenSSL library, using the
<strong>-command</strong>, <strong>-password</strong>, and
<em>-command</em> and <em>-password</em> options passed to either of
<strong>-validate_command</strong> options passed to either of
<strong>tls::socket</strong> or <strong>tls::import</strong>.
If the callback generates an error, the <b>bgerror</b> command with be
invoked with the error information.
</p>

<blockquote>
<dl>

    <dt><strong>-command</strong> <em>callback</em></dt>
    <dd>
	Invokes the specified <em>callback</em> script at
	several points during the OpenSSL handshake.
	Except as indicated below, values returned from the
	Invokes the specified <em>callback</em> script at several points
	during the OpenSSL handshake and use. See below for the possible
	arguments passed to the callback script. Values returned from the
	callback are ignored.
	Arguments appended to the script upon callback take one of the
	following forms:

	<br>
	<br>

	<dl>

	<dt>
	  <strong>alpn</strong> <em>protocol</em>
	</dt>
	<dd>
	  For servers, this form of callback is invoked when the client ALPN
	  header is received and the first <b>-alpn</b> specified protocol common
	  to the both the client and server is selected. If none, the first
	  client specified protocol is used.
	</dd>

	<br>

<!--	This form of callback is disabled.

	<dt>
	  <strong>error</strong> <em>channel message</em>
	</dt>
	<dd>
	  The <em>message</em> argument contains an error message generated
	  by the OpenSSL function
	  by the OpenSSL function <code>ERR_reason_error_string()</code>.
	  <code>ERR_reason_error_string()</code>.
	</dd>

	<br>
-->

	<dt>
	  <strong>hello</strong> <em>servername</em>
	</dt>
	<dd>
	  For servers, this form of callback is invoked during client hello
	  message processing.
	</dd>

	<br>

	<dt>
	  <strong>info</strong> <em>channel major minor message</em>
	  <strong>info</strong> <em>channel major minor message type</em>
	</dt>
	<dd>
	  This form of callback is invoked by the OpenSSL function
	  <code>SSL_CTX_set_info_callback()</code>.
	  <code>SSL_CTX_set_info_callback()</code> during connection setup
	  and use.
	  <br>
	  The <em>major</em> and <em>minor</em> arguments are used to
	  represent the state information bitmask.
	  <dl>
	  <dt>Possible values for <em>major</em> are:</dt>
	  <dd><code>handshake, alert, connect, accept</code>.</dd>
	  <dt>Possible values for <em>minor</em> are:</dt>
	  <dd><code>start, done, read, write, loop, exit</code>.</dd>
	  <ul>
	  <li>Possible values for <em>major</em> are:
	  <code>handshake, alert, connect, accept</code>.</li>
	  <li>Possible values for <em>minor</em> are:
	  <code>start, done, read, write, loop, exit</code>.</li>
	  </dl>
	  The <em>message</em> argument is a descriptive string which may
	  <li>The <em>message</em> argument is a descriptive string which may
	  be generated either by
	  <code>SSL_state_string_long()</code> or by
	  <code>SSL_alert_desc_string_long()</code>,
	  be generated either by <code>SSL_state_string_long()</code> or by
	  <code>SSL_alert_desc_string_long()</code>, depending on the context.</li>
	  depending on context.
	  <li>For alerts, the possible values for <em>type</em> are:
	  <code>warning, fatal, and unknown</code>. For others,
	  <code>info</code> is used.</li>
	  </ul>
	</dd>

	<dt>
	  <strong>message</strong> <em>channel direction version content_type data</em>
	</dt>
	<dd>
	  This form of callback is invoked by the OpenSSL function
	  <code>SSL_set_msg_callback()</code> whenever a message is sent or
	  received. It is only available when
	  OpenSSL is complied with the <em>enable-ssl-trace</em> option.
	  Where <em>direction</em> is Sent or Received, <em>version</em> is the
	  protocol version, <em>content_type</em> is the message content type,
	  and <em>data</em> is more info on the message from the <code>SSL_trace</code> API.
	</dd>
	<br>

	<dt>
	  <strong>session</strong> <em>session_id ticket lifetime</em>
	  <strong>session</strong> <em>channel session_id ticket lifetime</em>
	</dt>
	<dd>
	  This form of callback is invoked by the OpenSSL function
	  <code>SSL_CTX_sess_set_new_cb()</code>.
	  Where <em>session_id</em> is the current session identifier,
	  <em>ticket</em> is the session ticket info, and <em>lifetime</em>
	  is the the ticket lifetime in seconds.
	</dd>

	<br>

	<dt>
	  <strong>sni</strong> <em>servername</em>
	</dt>
	<dd>
	  For servers, this form of callback is invoked when the SNI header
	  from the client is received. Where <i>servername</i> is the client
	  specified servername. This is used when a server supports multiple
	  names, so the right certificate can be used.
	</dd>

	<br>
	<br>

	<dt>
	  <strong>verify</strong> <em>channel depth cert status error</em>
	</dt>
	<dd>
	  This form of callback is invoked by OpenSSL when a new certificate
	  is received from the peer. It allows the client to check the
	  certificate verification result and choose whether to continue or not.
	  <br>
	  The <em>depth</em> argument is an integer representing the
	  current depth on the certificate chain, with
	  <code>0</code> as the subject certificate and higher values
	  denoting progressively more indirect issuer certificates.
	  <br>
	  The <em>cert</em> argument is a list of key-value pairs similar
	  to those returned by
	  <a href="#tls::status"><strong>tls::status</strong></a>.
	  <br>
	  The <em>status</em> argument is an integer representing the
	  current validity of the certificate.
	  A value of <code>0</code> means the certificate is deemed invalid.
	  A value of <code>1</code> means the certificate is deemed valid.
	  <br>
	  The <em>error</em> argument supplies the message, if any, generated
	  by <code>X509_STORE_CTX_get_error()</code>.
	  <br>
	  <br>
	  The callback may override normal validation processing by explicitly
	  returning one of the above <em>status</em> values.
	</dd>

	</dl>
    </dd>

    <br>

    <dt><strong>-password</strong> <em>callback</em></dt>
    <dd>
	Invokes the specified <em>callback</em> script when OpenSSL needs to
	obtain a password. See below for the possible arguments passed to
	the callback script. See below for valid return values.

	<br>
	<br>

	<dl>

	<dt>
	  <strong>password</strong> <em>rwflag size</em>
	</dt>
	<dd>
	  Invoked when loading or storing a PEM certificate with encryption.
	  Where <em>rwflag</em> is 0 for reading/decryption or 1 for
	  writing/encryption (can prompt user to confirm) and
	  <em>size</em> is the max password length in bytes.
	obtain a password.  The callback should return a string which
	represents the password to be used.
	No arguments are appended to the script upon callback.
    </dd>
</dl>
	  The callback should return the password as a string.
	</dd>
    </dd>

    <br>


    <dt><strong>-validatecommand</strong> <em>callback</em></dt>
    <dd>
	Invokes the specified <em>callback</em> script during handshake in
	order to validate the provided value(s). See below for the possible
	arguments passed to the callback script.
	To reject the value and abort connection, the callback should return 0.
	To accept the value and continue the connection, it should return 1.
	To reject the value, but continue the connection, it should return 2.

	<br>
	<br>

	<dl>

	<dt>
	  <strong>alpn</strong> <em>channel protocol match</em>
	</dt>
	<dd>
	  For servers, this form of callback is invoked when the client ALPN
	  extension is received. If <em>match</em> is true, <em>protocol</em>
	  is the first <b>-alpn</b> specified protocol common to the both the
	  client and server. If not, the first client specified protocol is
	  used. Called after hello and ALPN callbacks.
	</dd>

	<br>

	<dt>
	  <strong>hello</strong> <em>channel servername</em>
	</dt>
	<dd>
	  For servers, this form of callback is invoked during client hello
	  message processing. It is used to select an appropriate certificate to
	  present, and make other configuration adjustments relevant to that
	  server name and its configuration. Called before SNI and ALPN callbacks.
	</dd>

	<br>

	<dt>
	  <strong>sni</strong> <em>channel servername</em>
	</dt>
	<dd>
	  For servers, this form of callback is invoked when the SNI extension
	  from the client is received. Where <em>servername</em> is the client
	  provided server name from the <b>-servername</b> option. This is
	  used when a server supports multiple names, so the right certificate
	  can be used. Called after hello callback but before ALPN callback.
	</dd>

	<br>

	<dt>
	  <strong>verify</strong> <em>channel depth cert status error</em>
	</dt>
	<dd>
	  This form of callback is invoked by OpenSSL when a new certificate
	  is received from the peer. It allows the client to check the
	  certificate verification results and choose whether to continue
	  or not. It is called for each certificate in the certificate chain.
	  <ul>
	  <li>The <em>depth</em> argument is an integer representing the
	  current depth on the certificate chain, with
	  <code>0</code> as the peer certificate and higher values going
	  up to the Certificate Authority (CA).</li>
	  <li>The <em>cert</em> argument is a list of key-value pairs similar
	  to those returned by
	  <a href="#tls::status"><strong>tls::status</strong></a>.</li>
	  <li>The <em>status</em> argument is an boolean representing the
	  validity of the current certificate.
	  A value of <code>0</code> means the certificate is deemed invalid.
	  A value of <code>1</code> means the certificate is deemed valid.</li>
	  <li>The <em>error</em> argument supplies the message, if any, generated
	  by <code>X509_STORE_CTX_get_error()</code>.</li>
	  </ul>
	</dd>
	<br>
	</dl>
    </dd>
</dl>
</blockquote>

<p>
Reference implementations of these callbacks are provided in the
distribution as <strong>tls::callback</strong> and
<strong>tls::password</strong> respectively.  Note that these are
distribution as <strong>tls::callback</strong>, <strong>tls::password</strong>,
and <strong>tls::validate_command</strong> respectively.  Note that these are
<em>sample</em> implementations only.  In a more realistic deployment
you would specify your own callback scripts on each TLS channel
using the <em>-command</em> and <em>-password</em> options.
you would specify your own callback scripts on each TLS channel using the
<strong>-command</strong>, <strong>-password</strong>, and <strong>-validate_command</strong> options.
</p>

<p>
The default behavior when the <em>-command</em> option is not specified is for
TLS to process the associated library callbacks internally.
The default behavior when the <em>-password</em> option is not specified is for
TLS to process the associated library callbacks by attempting to call
<strong>tls::password</strong>.
The default behavior when the <strong>-command</strong> and <strong>-validate_command</strong>
options are not specified is for TLS to process the associated library callbacks
internally. The default behavior when the <strong>-password</strong> option is not
specified is for TLS to process the associated library callbacks by attempting
to call <strong>tls::password</strong>.
The difference between these two behaviors is a consequence of maintaining
compatibility with earlier implementations.
</p>

<p>
The <strong>tls::debug</strong> variable provides some additional
control over these reference callbacks.  Its value is zero by default.
Higher values produce more diagnostic output, and will also force the
verify method in <strong>tls::callback</strong> to accept the
certificate, even when it is invalid.
</p>

<p>
<em>
The use of the reference callbacks <strong>tls::callback</strong> and
<strong>tls::password</strong> is not recommended.  They may be removed
from future releases.
The use of the reference callbacks <strong>tls::callback</strong>,
<strong>tls::password</strong>, and <strong>tls::validate_command</strong>
is not recommended.  They may be removed from future releases.
</em>
</p>

<p>
<em>
The use of the variable <strong>tls::debug</strong> is not recommended.
It may be removed from future releases.
</em>
</p>

<h3><a name="DEBUG">DEBUG</a></h3>

TLS key logging can be enabled by setting the environment variable
<b>SSLKEYLOGFILE</b> to the name of the file to log to. Then whenever TLS
key material is generated or received it will be logged to the file.
key material is generated or received it will be logged to the file. This
is useful for logging key data for network logging tools to use to
decrypt the data.

<h3><a name="HTTPS EXAMPLE">HTTPS EXAMPLE</a></h3>

<p>This example uses a sample server.pem provided with the TLS release,
courtesy of the <strong>OpenSSL</strong> project.</p>

<pre><code>
package require http
package require tls

http::register https 443 [list ::tls::socket -autoservername true -require true -cadir /etc/ssl/certs]

set tok [http::geturl https://www.tcl.tk/]
</code></pre>

<h3><a name="SPECIAL CONSIDERATIONS">SPECIAL CONSIDERATIONS</a></h3>

<p>The capabilities of this package can vary enormously based
upon how your OpenSSL library was configured and built. At the
most macro-level OpenSSL supports a &quot;no patents&quot; build,
which disables RSA, IDEA, RC(2,4,5) and SSL2 - if your OpenSSL is
<p>The capabilities of this package can vary enormously based upon how your
OpenSSL library was configured and built. New versions may obsolete older
protocol versions, add or remove ciphers, change default values, etc. Use the
<strong>tls::ciphers</strong> and <strong>tls::protocols</strong> commands to
configured this way then you will need to build TLS with the
-DNO_PATENTS option - and the resultant module will function
correctly and also support ADH certificate-less encryption,
however you will be unable to utilize this to speak to normal Web
Servers, which typically require RSA support. Please see <a
href="http://www.openssl.org/">http://www.openssl.org/</a> for
more information on the whole issue of patents and US export
restrictions. </p>
obtain the supported versions.</p>

<h3><a name="SEE ALSO">SEE ALSO</a></h3>

<p><strong>socket</strong>, <strong>fileevent, </strong><a
href="http://www.openssl.org/"><strong>OpenSSL</strong></a></p>

<hr>

Modified generic/tls.c from [55d19f65b6] to [b314eff29c].

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



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
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
395
396
397
398
399
400
401




402
403
404
405
406







407


















408
409

410




411
412
413
414
415
416
417
418

419

420
421
422
423
424
425
426
427
428
429


430
431
432
433
434
435








436









437

438
439
440

441
442
443
444

445
446


447
448
449








450
451
452
453
454
455
456
457
458



459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493



494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509

510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554





555
556
557
558
559
560
561
562

563
564
565

566
567
568
569
570
571
572







+




+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+






-
+






+














-
-
-
-
-
-
-
-
-
-
-



















+
+






-
+

-
-
-
+
-
-
+
+



+

-
-

+

-
+

-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+






-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+

+
+
+


-
-
+
+
+





+




-
+
-
-






-



-
+







+
-
+









-
-
-
-
+
+

+

-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-


-
+
-
-
-
-
+







-
+
-




+





-
-
+
+
+



-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-

-
+
+

-



+
-
+

-
-
+
+

-
-
-
-
-
-
-
-
+
+
+
+
+
+

+
+
-
-
-
+
+
+











+





+
+
+












-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+



-
+







+










+

+
+
+




+













+

+
-
-
-
-
-
+
+
+
+
+
+
+
+
-



-








static Tcl_Mutex *locks = NULL;
static int locksCount = 0;
static Tcl_Mutex init_mx;
#endif /* OPENSSL_THREADS */
#endif /* TCL_THREADS */


/********************/
/* Callbacks        */
/********************/

/*
 *-------------------------------------------------------------------
 *
 * Eval Callback Command --
 *
 *	Eval callback command and catch any errors
 *
 * Results:
 *	0 = Command returned fail or eval returned TCL_ERROR
 *	1 = Command returned success or eval returned TCL_OK
 *
 * Side effects:
 *	Evaluates callback command
 *
 *-------------------------------------------------------------------
 */
static int
EvalCallback(Tcl_Interp *interp, State *statePtr, Tcl_Obj *cmdPtr) {
    int code, ok;

    Tcl_Preserve((ClientData) interp);
    Tcl_Preserve((ClientData) statePtr);

    /* Eval callback with success for ok or return value 1, fail for error or return value 0 */
    code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL);
    if (code == TCL_OK) {
	/* Check result for return value */
	Tcl_Obj *result = Tcl_GetObjResult(interp);
	if (result == NULL || Tcl_GetIntFromObj(interp, result, &ok) != TCL_OK) {
	    ok = 1;
	}
    } else {
	/* Error - reject the certificate */
	ok = 0;
#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6)
	Tcl_BackgroundError(interp);
#else
	Tcl_BackgroundException(interp, code);
#endif
    }

    Tcl_Release((ClientData) statePtr);
    Tcl_Release((ClientData) interp);
    return ok;
}

/*
 *-------------------------------------------------------------------
 *
 * InfoCallback --
 *
 *	monitors SSL connection process
 *	Monitors SSL connection process
 *
 * Results:
 *	None
 *
 * Side effects:
 *	Calls callback (if defined)
 *
 *-------------------------------------------------------------------
 */
static void
InfoCallback(const SSL *ssl, int where, int ret) {
    State *statePtr = (State*)SSL_get_app_data((SSL *)ssl);
    Tcl_Interp *interp	= statePtr->interp;
    Tcl_Obj *cmdPtr;
    char *major; char *minor;

    dprintf("Called");

    if (statePtr->callback == (Tcl_Obj*)NULL)
	return;

    cmdPtr = Tcl_DuplicateObj(statePtr->callback);

#if 0
    if (where & SSL_CB_ALERT) {
	sev = SSL_alert_type_string_long(ret);
	if (strcmp(sev, "fatal")==0) {	/* Map to error */
	    Tls_Error(statePtr, SSL_ERROR(ssl, 0));
	    return;
	}
    }
#endif
    if (where & SSL_CB_HANDSHAKE_START) {
	major = "handshake";
	minor = "start";
    } else if (where & SSL_CB_HANDSHAKE_DONE) {
	major = "handshake";
	minor = "done";
    } else {
	if (where & SSL_CB_ALERT)		major = "alert";
	else if (where & SSL_ST_CONNECT)	major = "connect";
	else if (where & SSL_ST_ACCEPT)		major = "accept";
	else					major = "unknown";

	if (where & SSL_CB_READ)		minor = "read";
	else if (where & SSL_CB_WRITE)		minor = "write";
	else if (where & SSL_CB_LOOP)		minor = "loop";
	else if (where & SSL_CB_EXIT)		minor = "exit";
	else					minor = "unknown";
    }

    /* Create command to eval */
    cmdPtr = Tcl_DuplicateObj(statePtr->callback);
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("info", -1));
    Tcl_ListObjAppendElement(interp, cmdPtr,
	    Tcl_NewStringObj(Tcl_GetChannelName(statePtr->self), -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(major, -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(minor, -1));

    if (where & (SSL_CB_LOOP|SSL_CB_EXIT)) {
    if (where & SSL_CB_ALERT) {
	Tcl_ListObjAppendElement(interp, cmdPtr,
	    Tcl_NewStringObj(SSL_state_string_long(ssl), -1));
    } else if (where & SSL_CB_ALERT) {
	const char *cp = (char *) SSL_alert_desc_string_long(ret);
	    Tcl_NewStringObj(SSL_alert_desc_string_long(ret), -1));

	Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(cp, -1));
	Tcl_ListObjAppendElement(interp, cmdPtr,
	    Tcl_NewStringObj(SSL_alert_type_string_long(ret), -1));
    } else {
	Tcl_ListObjAppendElement(interp, cmdPtr,
	    Tcl_NewStringObj(SSL_state_string_long(ssl), -1));
	Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("info", -1));
    }
    Tcl_Preserve((ClientData) interp);
    Tcl_Preserve((ClientData) statePtr);

    /* Eval callback command */
    Tcl_IncrRefCount(cmdPtr);
    (void) Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL);
    EvalCallback(interp, statePtr, cmdPtr);
    Tcl_DecrRefCount(cmdPtr);

    Tcl_Release((ClientData) statePtr);
    Tcl_Release((ClientData) interp);
}

/*
 *-------------------------------------------------------------------
 *
 * MessageCallback --
 *
 *	Monitors SSL protocol messages
 *
 * Results:
 *	None
 *
 * Side effects:
 *	Calls callback (if defined)
 *
 *-------------------------------------------------------------------
 */
#ifndef OPENSSL_NO_SSL_TRACE
static void
MessageCallback(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg) {
    State *statePtr = (State*)arg;
    Tcl_Interp *interp	= statePtr->interp;
    Tcl_Obj *cmdPtr;
    char *ver, *type;
    BIO *bio;
    char buffer[15000];
    buffer[0] = 0;

    dprintf("Called");

    if (statePtr->callback == (Tcl_Obj*)NULL)
	return;

    switch(version) {
#if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(NO_SSL2) && !defined(OPENSSL_NO_SSL2)
    case SSL2_VERSION:
	ver = "SSLv2";
	break;
#endif
#if !defined(NO_SSL3) && !defined(OPENSSL_NO_SSL3)
    case SSL3_VERSION:
	ver = "SSLv3";
	break;
#endif
    case TLS1_VERSION:
	ver = "TLSv1";
	break;
    case TLS1_1_VERSION:
	ver = "TLSv1.1";
	break;
    case TLS1_2_VERSION:
	ver = "TLSv1.2";
	break;
    case TLS1_3_VERSION:
	ver = "TLSv1.3";
	break;
    case 0:
        ver = "none";
	break;
    default:
	ver = "unknown";
	break;
    }

    switch (content_type) {
    case SSL3_RT_HEADER:
	type = "Header";
        break;
    case SSL3_RT_INNER_CONTENT_TYPE:
	type = "Inner Content Type";
        break;
    case SSL3_RT_CHANGE_CIPHER_SPEC:
	type = "Change Cipher";
        break;
    case SSL3_RT_ALERT:
	type = "Alert";
        break;
    case SSL3_RT_HANDSHAKE:
	type = "Handshake";
        break;
    case SSL3_RT_APPLICATION_DATA:
	type = "App Data";
        break;
    case DTLS1_RT_HEARTBEAT:
	type = "Heartbeat";
        break;
    default:
	type = "unknown";
    }

    /* Needs compile time option "enable-ssl-trace". */
    if ((bio = BIO_new(BIO_s_mem())) != NULL) {
	int n;
	SSL_trace(write_p, version, content_type, buf, len, ssl, (void *)bio);
	n = BIO_read(bio, buffer, min(BIO_pending(bio), 14999));
	n = (n<0) ? 0 : n;
	buffer[n] = 0;
	(void)BIO_flush(bio);
 	BIO_free(bio);
   }

    /* Create command to eval */
    cmdPtr = Tcl_DuplicateObj(statePtr->callback);
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("message", -1));
    Tcl_ListObjAppendElement(interp, cmdPtr,
	    Tcl_NewStringObj(Tcl_GetChannelName(statePtr->self), -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(write_p ? "Sent" : "Received", -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(ver, -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(type, -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(buffer, -1));

    /* Eval callback command */
    Tcl_IncrRefCount(cmdPtr);
    EvalCallback(interp, statePtr, cmdPtr);
    Tcl_DecrRefCount(cmdPtr);
}
#endif

/*
 *-------------------------------------------------------------------
 *
 * VerifyCallback --
 *
 *	Monitors SSL certificate validation process.
 *	This is called whenever a certificate is inspected
 *	or decided invalid.
 *	Monitors SSL certificate validation process. Used to control the
 *	behavior when the SSL_VERIFY_PEER flag is set. This is called
 *	whenever a certificate is inspected or decided invalid. Called for
 *	each certificate in the cert chain.
 *
 * Checks:
 *	certificate chain is checked starting with the deepest nesting level
 *	  (the root CA certificate) and worked upward to the peer's certificate.
 *	All signatures are valid, current time is within first and last validity time.
 *	Check that the certificate is issued by the issuer certificate issuer.
 *	Check the revocation status for each certificate.
 *	Check the validity of the given CRL and the cert revocation status.
 *	Check the policies of all the certificates
 *
 * Args
 *	preverify_ok indicates whether the certificate verification passed (1) or not (0)
 *
 * Results:
 *	A callback bound to the socket may return one of:
 *	    0			- the certificate is deemed invalid
 *	    1			- the certificate is deemed valid
 *	    0			- the certificate is deemed invalid, send verification
 *				  failure alert to peer, and terminate handshake.
 *	    1			- the certificate is deemed valid, continue with handshake.
 *	    empty string	- no change to certificate validation
 *
 * Side effects:
 *	The err field of the currently operative State is set
 *	  to a string describing the SSL negotiation failure reason
 *
 *-------------------------------------------------------------------
 */
static int
VerifyCallback(int ok, X509_STORE_CTX *ctx) {
    Tcl_Obj *cmdPtr, *result;
    Tcl_Obj *cmdPtr;
    char *string;
    int length;
    SSL   *ssl		= (SSL*)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
    X509  *cert		= X509_STORE_CTX_get_current_cert(ctx);
    State *statePtr	= (State*)SSL_get_app_data(ssl);
    Tcl_Interp *interp	= statePtr->interp;
    int depth		= X509_STORE_CTX_get_error_depth(ctx);
    int err		= X509_STORE_CTX_get_error(ctx);
    int code;

    dprintf("Verify: %d", ok);

    if (statePtr->callback == (Tcl_Obj*)NULL) {
    if (statePtr->vcmd == (Tcl_Obj*)NULL) {
	if (statePtr->vflags & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
	    return ok;
	} else {
	    return 1;
	}
    }

    /* Create command to eval */
    cmdPtr = Tcl_DuplicateObj(statePtr->callback);
    cmdPtr = Tcl_DuplicateObj(statePtr->vcmd);
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("verify", -1));
    Tcl_ListObjAppendElement(interp, cmdPtr,
	Tcl_NewStringObj(Tcl_GetChannelName(statePtr->self), -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewIntObj(depth));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tls_NewX509Obj(interp, cert));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewIntObj(ok));
    Tcl_ListObjAppendElement(interp, cmdPtr,
	Tcl_NewStringObj((char*)X509_verify_cert_error_string(err), -1));

    Tcl_Preserve((ClientData) interp);
    Tcl_Preserve((ClientData) statePtr);

    statePtr->flags |= TLS_TCL_CALLBACK;
    /* Prevent I/O while callback is in progress */
    /* statePtr->flags |= TLS_TCL_CALLBACK; */

    /* Eval callback command */
    Tcl_IncrRefCount(cmdPtr);
    code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL);
    if (code != TCL_OK) {
	/* It got an error - reject the certificate.		*/
#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6)
	Tcl_BackgroundError(interp);
#else
	Tcl_BackgroundException(interp, code);
    ok = EvalCallback(interp, statePtr, cmdPtr);
#endif
	ok = 0;
    } else {
	result = Tcl_GetObjResult(interp);
	string = Tcl_GetStringFromObj(result, &length);
	/* An empty result leaves verification unchanged.	*/
	if (string != NULL && length > 0) {
	    code = Tcl_GetIntFromObj(interp, result, &ok);
	    if (code != TCL_OK) {
#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6)
		Tcl_BackgroundError(interp);
#else
		Tcl_BackgroundException(interp, code);
#endif
		ok = 0;
	    }
	}
    }
    Tcl_DecrRefCount(cmdPtr);

    statePtr->flags &= ~(TLS_TCL_CALLBACK);
    /* statePtr->flags &= ~(TLS_TCL_CALLBACK); */

    Tcl_Release((ClientData) statePtr);
    Tcl_Release((ClientData) interp);
    return(ok);	/* By default, leave verification unchanged.	*/
    return(ok);	/* By default, leave verification unchanged. */
}

/*
 *-------------------------------------------------------------------
 *
 * Tls_Error --
 *
 *	Calls callback with $fd and $msg - so the callback can decide
 *	Calls callback with list of errors.
 *	what to do with errors.
 *
 * Side effects:
 *	The err field of the currently operative State is set
 *	  to a string describing the SSL negotiation failure reason
 *
 *-------------------------------------------------------------------
 */
void
Tls_Error(State *statePtr, char *msg) {
    Tcl_Interp *interp	= statePtr->interp;
    Tcl_Obj *cmdPtr;
    int code;
    Tcl_Obj *cmdPtr, *listPtr;
    unsigned long err;
    statePtr->err = msg;

    dprintf("Called");

    if (msg && *msg) {
	Tcl_SetErrorCode(interp, "SSL", msg, (char *)NULL);
    } else {
	msg = Tcl_GetStringFromObj(Tcl_GetObjResult(interp), NULL);
    }
    statePtr->err = msg;

    if (statePtr->callback == (Tcl_Obj*)NULL) {
    if (statePtr->callback == (Tcl_Obj*)NULL)
	char buf[BUFSIZ];
	sprintf(buf, "SSL channel \"%s\": error: %s",
	    Tcl_GetChannelName(statePtr->self), msg);
	Tcl_SetResult(interp, buf, TCL_VOLATILE);
#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6)
	Tcl_BackgroundError(interp);
#else
	Tcl_BackgroundException(interp, TCL_ERROR);
#endif
	return;
    }

    /* Create command to eval */
    cmdPtr = Tcl_DuplicateObj(statePtr->callback);

    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("error", -1));
    Tcl_ListObjAppendElement(interp, cmdPtr,
	    Tcl_NewStringObj(Tcl_GetChannelName(statePtr->self), -1));
    if (msg != NULL) {
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(msg, -1));
	Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(msg, -1));

    Tcl_Preserve((ClientData) interp);
    Tcl_Preserve((ClientData) statePtr);
    } else if ((msg = Tcl_GetStringFromObj(Tcl_GetObjResult(interp), NULL)) != NULL) {
	Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(msg, -1));

    Tcl_IncrRefCount(cmdPtr);
    code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL);
    if (code != TCL_OK) {
#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6)
	Tcl_BackgroundError(interp);
#else
	Tcl_BackgroundException(interp, code);
#endif
    } else {
	listPtr = Tcl_NewListObj(0, NULL);
	while ((err = ERR_get_error()) != 0) {
	    Tcl_ListObjAppendElement(interp, listPtr, Tcl_NewStringObj(ERR_reason_error_string(err), -1));
	}
	Tcl_ListObjAppendElement(interp, cmdPtr, listPtr);
    }

    /* Eval callback command */
    Tcl_DecrRefCount(cmdPtr);
    Tcl_Release((ClientData) statePtr);
    Tcl_Release((ClientData) interp);
    Tcl_IncrRefCount(cmdPtr);
    EvalCallback(interp, statePtr, cmdPtr);
    Tcl_DecrRefCount(cmdPtr);
}

/*
 *-------------------------------------------------------------------
 *
 * KeyLogCallback --
 *
 *	Write received key data to log file.
 *
 * Side effects:
 *	none
 *
 *-------------------------------------------------------------------
 */
void KeyLogCallback(const SSL *ssl, const char *line) {
    char *str = getenv(SSLKEYLOGFILE);
    FILE *fd;

    dprintf("Called");

    if (str) {
	fd = fopen(str, "a");
	fprintf(fd, "%s\n",line);
	fclose(fd);
    }
}

/*
 *-------------------------------------------------------------------
 *
 * Password Callback --
 *
 *	Called when a password is needed to unpack RSA and PEM keys.
 *	Evals any bound password script and returns the result as
 *	the password string.
 *	Called when a password for a private key loading/storing a PEM
 *	certificate with encryption. Evals callback script and returns
 *	the result as the password string in buf.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	Calls callback (if defined)
 *
 * Returns:
 *	Password size in bytes or -1 for an error.
 *
 *-------------------------------------------------------------------
 */
static int
PasswordCallback(char *buf, int size, int verify, void *udata) {
PasswordCallback(char *buf, int size, int rwflag, void *udata) {
    State *statePtr	= (State *) udata;
    Tcl_Interp *interp	= statePtr->interp;
    Tcl_Obj *cmdPtr;
    int code;

    dprintf("Called");

    /* If no callback, use default callback */
    if (statePtr->password == NULL) {
	if (Tcl_EvalEx(interp, "tls::password", -1, TCL_EVAL_GLOBAL) == TCL_OK) {
	    char *ret = (char *) Tcl_GetStringResult(interp);
	    strncpy(buf, ret, (size_t) size);
	    return (int)strlen(ret);
	} else {
	    return -1;
	}
    }

    /* Create command to eval */
    cmdPtr = Tcl_DuplicateObj(statePtr->password);
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("password", -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewIntObj(rwflag));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewIntObj(size));

    Tcl_Preserve((ClientData) interp);
    Tcl_Preserve((ClientData) statePtr);

    /* Eval callback command */
    Tcl_IncrRefCount(cmdPtr);
    code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL);
    if (code != TCL_OK) {
#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6)
	Tcl_BackgroundError(interp);
#else
	Tcl_BackgroundException(interp, code);
#endif
    }
    Tcl_DecrRefCount(cmdPtr);

    Tcl_Release((ClientData) statePtr);

    /* If successful, pass back password string and truncate if too long */
    if (code == TCL_OK) {
	int len;
	char *ret = (char *) Tcl_GetStringResult(interp);
	if (strlen(ret) < size - 1) {
	    strncpy(buf, ret, (size_t) size);
	    Tcl_Release((ClientData) interp);
	    return (int)strlen(ret);
	char *ret = (char *) Tcl_GetStringFromObj(Tcl_GetObjResult(interp), &len);
	if (len > size-1) {
	    len = size-1;
	}
	strncpy(buf, ret, (size_t) len);
	buf[len] = '\0';
	Tcl_Release((ClientData) interp);
	return(len);
	}
    }
    Tcl_Release((ClientData) interp);
    return -1;
	verify = verify;
}

/*
 *-------------------------------------------------------------------
 *
 * Session Callback for Clients --
 *
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465

466
467


468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483

484
485
486
487
488
489
490

491
492
493
494

495
496
497
498
499
500
501
502

503
504
505



506
507
508
509
510
511
512
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







-











+


+
+













-
-
-
+

-
-
-
-
-
-
+
-
-

-
+
-
-





-
+

-
-
+
+
+







static int
SessionCallback(const SSL *ssl, SSL_SESSION *session) {
    State *statePtr = (State*)SSL_get_app_data((SSL *)ssl);
    Tcl_Interp *interp	= statePtr->interp;
    Tcl_Obj *cmdPtr;
    const unsigned char *ticket;
    const unsigned char *session_id;
    int code;
    size_t len2;
    unsigned int ulen;

    dprintf("Called");

    if (statePtr->callback == (Tcl_Obj*)NULL) {
	return SSL_TLSEXT_ERR_OK;
    } else if (ssl == NULL) {
	return SSL_TLSEXT_ERR_NOACK;
    }

    /* Create command to eval */
    cmdPtr = Tcl_DuplicateObj(statePtr->callback);
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("session", -1));
    Tcl_ListObjAppendElement(interp, cmdPtr,
	    Tcl_NewStringObj(Tcl_GetChannelName(statePtr->self), -1));

    /* Session id */
    session_id = SSL_SESSION_get_id(session, &ulen);
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewByteArrayObj(session_id, (int) ulen));

    /* Session ticket */
    SSL_SESSION_get0_ticket(session, &ticket, &len2);
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewByteArrayObj(ticket, (int) len2));

    /* Lifetime - number of seconds */
    Tcl_ListObjAppendElement(interp, cmdPtr,
	Tcl_NewLongObj((long) SSL_SESSION_get_ticket_lifetime_hint(session)));

    Tcl_Preserve((ClientData) interp);
    Tcl_Preserve((ClientData) statePtr);

    /* Eval callback command */
    Tcl_IncrRefCount(cmdPtr);
    code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL);
    if (code != TCL_OK) {
#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6)
	Tcl_BackgroundError(interp);
#else
	Tcl_BackgroundException(interp, code);
    EvalCallback(interp, statePtr, cmdPtr);
#endif
    }
    Tcl_DecrRefCount(cmdPtr);

    return 0;
    Tcl_Release((ClientData) statePtr);
    Tcl_Release((ClientData) interp);    return 0;
}

/*
 *-------------------------------------------------------------------
 *
 * ALPN Callback for Servers --
 * ALPN Callback for Servers and NPN Callback for Clients --
 *
 *	Perform server-side protocol (http/1.1, h2, h3, etc.) selection for the
 *	incoming connection. Called after Hello and server callbacks
 *	Perform protocol (http/1.1, h2, h3, etc.) selection for the
 *	incoming connection. Called after Hello and server callbacks.
 *	Where 'out' is selected protocol and 'in' is the peer advertised list.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	Calls callback (if defined)
 *
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
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

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
831
832
833
834
835
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
884
885
886
887
888

889
890
891
892
893
894

895
896
897
898
899
900

901
902
903
904
905
906



907
908


909
910
911
912



913
914


915
916
917
918




919
920
921
922
923
924
925
926







-
-
-
+






+


-
+



+
+
+
+
+
-
+

+
+

-
+
-
-

+

-
-
+
+
+
-
-
-
+
+
-
-
+


-
-
-






+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


-
-
+
+












-
+










-
+




-
-
-
+



+


-
+


+
+
+
+
+
-
+

+
+


-
-
-
+

-
-
+
+
+
+
-
-
-
+
+
-
-
+
+


-
-
-
-
+





-
+







+








-
-
-
+
+
+








-
+






-
+

-
+





+
-
+






+
-
+





+
-
+





+
-
+




+
-
+




+
-
+

+
+


-
-
-
+

-
-
+
+
+
+
-
-
-
+
+
-
-
+
+


-
-
-
-
+







    State *statePtr = (State*)arg;
    Tcl_Interp *interp	= statePtr->interp;
    Tcl_Obj *cmdPtr;
    int code, res;

    dprintf("Called");

    if (statePtr->callback == (Tcl_Obj*)NULL) {
	return SSL_TLSEXT_ERR_OK;
    } else if (ssl == NULL) {
    if (ssl == NULL || arg == NULL) {
	return SSL_TLSEXT_ERR_NOACK;
    }

    /* Select protocol */
    if (SSL_select_next_proto(out, outlen, statePtr->protos, statePtr->protos_len,
	in, inlen) == OPENSSL_NPN_NEGOTIATED) {
	/* Match found */
	res = SSL_TLSEXT_ERR_OK;
    } else {
	/* No overlap, so first client protocol used */
	/* OPENSSL_NPN_NO_OVERLAP = No overlap, so use first item from client protocol list */
	res = SSL_TLSEXT_ERR_NOACK;
    }

    if (statePtr->vcmd == (Tcl_Obj*)NULL) {
	return res;
    }

    /* Create command to eval */
    cmdPtr = Tcl_DuplicateObj(statePtr->callback);
    cmdPtr = Tcl_DuplicateObj(statePtr->vcmd);
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("alpn", -1));
    Tcl_ListObjAppendElement(interp, cmdPtr,
	    Tcl_NewStringObj(Tcl_GetChannelName(statePtr->self), -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(*out, -1));

    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewBooleanObj(res == SSL_TLSEXT_ERR_OK));
    Tcl_Preserve((ClientData) interp);
    Tcl_Preserve((ClientData) statePtr);

    /* Eval callback command */
    Tcl_IncrRefCount(cmdPtr);
    code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL);
    if (code != TCL_OK) {
    if ((code = EvalCallback(interp, statePtr, cmdPtr)) > 1) {
	res = SSL_TLSEXT_ERR_NOACK;
    } else if (code == 1) {
#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6)
	Tcl_BackgroundError(interp);
#else
	res = SSL_TLSEXT_ERR_OK;
    } else {
	Tcl_BackgroundException(interp, code);
#endif
	res = SSL_TLSEXT_ERR_ALERT_FATAL;
    }
    Tcl_DecrRefCount(cmdPtr);

    Tcl_Release((ClientData) statePtr);
    Tcl_Release((ClientData) interp);
    return res;
}

/*
 *-------------------------------------------------------------------
 *
 * Advertise Protocols Callback for Next Protocol Negotiation (NPN) in ServerHello --
 *
 *	called when a TLS server needs a list of supported protocols for Next
 *	Protocol Negotiation.
 *
 * Results:
 *	None
 *
 * Side effects:
 *
 * Return codes:
 *	SSL_TLSEXT_ERR_OK: NPN protocol selected. The connection continues.
 *	SSL_TLSEXT_ERR_NOACK: NPN protocol not selected. The connection continues.
 *
 *-------------------------------------------------------------------
 */
#ifdef USE_NPN
static int
NPNCallback(const SSL *ssl, const unsigned char **out, unsigned int *outlen, void *arg) {
    State *statePtr = (State*)arg;

    dprintf("Called");

    if (ssl == NULL || arg == NULL) {
	return SSL_TLSEXT_ERR_NOACK;
    }

    /* Set protocols list */
    if (statePtr->protos != NULL) {
	*out = statePtr->protos;
	*outlen = statePtr->protos_len;
    } else {
	*out = NULL;
	*outlen = 0;
	return SSL_TLSEXT_ERR_NOACK;
    }
    return SSL_TLSEXT_ERR_OK;
}
#endif

/*
 *-------------------------------------------------------------------
 *
 * SNI Callback for Servers --
 *
 *	Perform server-side SNI hostname selection after receiving SNI header.
 *	Called after hello callback but before ALPN callback.
 *	Perform server-side SNI hostname selection after receiving SNI extension
 *	in Client Hello. Called after hello callback but before ALPN callback.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	Calls callback (if defined)
 *
 * Return codes:
 *	SSL_TLSEXT_ERR_OK: SNI hostname is accepted. The connection continues.
 *	SSL_TLSEXT_ERR_ALERT_FATAL: SNI hostname is not accepted. The connection
 *	    is aborted. Default for alert is SSL_AD_UNRECOGNIZED_NAME.
 *	SSL_TLSEXT_ERR_ALERT_WARNING: SNI hostname is not accepted, warning alert
 *	    sent (not in TLSv1.3). The connection continues.
 *	    sent (not supported in TLSv1.3). The connection continues.
 *	SSL_TLSEXT_ERR_NOACK: SNI hostname is not accepted and not acknowledged,
 *	    e.g. if SNI has not been configured. The connection continues.
 *
 *-------------------------------------------------------------------
 */
static int
SNICallback(const SSL *ssl, int *alert, void *arg) {
    State *statePtr = (State*)arg;
    Tcl_Interp *interp	= statePtr->interp;
    Tcl_Obj *cmdPtr;
    int code;
    int code, res;
    char *servername = NULL;

    dprintf("Called");

    if (statePtr->callback == (Tcl_Obj*)NULL) {
	return SSL_TLSEXT_ERR_OK;
    } else if (ssl == NULL) {
    if (ssl == NULL || arg == NULL) {
	return SSL_TLSEXT_ERR_NOACK;
    }

    /* Only works for TLS 1.2 and earlier */
    servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
    if (!servername || servername[0] == '\0') {
        return SSL_TLSEXT_ERR_NOACK;
	return SSL_TLSEXT_ERR_NOACK;
    }

    if (statePtr->vcmd == (Tcl_Obj*)NULL) {
	return SSL_TLSEXT_ERR_OK;
    }

    /* Create command to eval */
    cmdPtr = Tcl_DuplicateObj(statePtr->callback);
    cmdPtr = Tcl_DuplicateObj(statePtr->vcmd);
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("sni", -1));
    Tcl_ListObjAppendElement(interp, cmdPtr,
	    Tcl_NewStringObj(Tcl_GetChannelName(statePtr->self), -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(servername , -1));

    Tcl_Preserve((ClientData) interp);
    Tcl_Preserve((ClientData) statePtr);

    /* Eval callback command */
    Tcl_IncrRefCount(cmdPtr);
    code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL);
    if (code != TCL_OK) {
    if ((code = EvalCallback(interp, statePtr, cmdPtr)) > 1) {
	res = SSL_TLSEXT_ERR_ALERT_WARNING;
	*alert = SSL_AD_UNRECOGNIZED_NAME; /* Not supported by TLS 1.3 */
    } else if (code == 1) {
#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6)
	Tcl_BackgroundError(interp);
#else
	res = SSL_TLSEXT_ERR_OK;
    } else {
	Tcl_BackgroundException(interp, code);
#endif
	res = SSL_TLSEXT_ERR_ALERT_FATAL;
	*alert = SSL_AD_UNRECOGNIZED_NAME; /* Not supported by TLS 1.3 */
    }
    Tcl_DecrRefCount(cmdPtr);

    Tcl_Release((ClientData) statePtr);
    Tcl_Release((ClientData) interp);
    return SSL_TLSEXT_ERR_OK;
    return res;
}

/*
 *-------------------------------------------------------------------
 *
 * Hello Handshake Callback for Servers --
 * ClientHello Handshake Callback for Servers --
 *
 *	Used by server to examine the server name indication (SNI) extension
 *	provided by the client in order to select an appropriate certificate to
 *	present, and make other configuration adjustments relevant to that server
 *	name and its configuration. This includes swapping out the associated
 *	SSL_CTX pointer, modifying the server's list of permitted TLS versions,
 *	changing the server's cipher list in response to the client's cipher list, etc.
 *	Called before SNI and ALPN callbacks.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	Calls callback (if defined)
 *
 * Return codes:
 *	SSL_CLIENT_HELLO_RETRY = suspend the handshake, and the handshake function will return immediately
 *	SSL_CLIENT_HELLO_ERROR = failure, terminate connection. Set alert to error code.
 *	SSL_CLIENT_HELLO_SUCCESS = success
 *	SSL_CLIENT_HELLO_RETRY: suspend the handshake, and the handshake function will return immediately
 *	SSL_CLIENT_HELLO_ERROR: failure, terminate connection. Set alert to error code.
 *	SSL_CLIENT_HELLO_SUCCESS: success
 *
 *-------------------------------------------------------------------
 */
static int
HelloCallback(const SSL *ssl, int *alert, void *arg) {
    State *statePtr = (State*)arg;
    Tcl_Interp *interp	= statePtr->interp;
    Tcl_Obj *cmdPtr;
    int code;
    int code, res;
    const char *servername;
    const unsigned char *p;
    size_t len, remaining;

    dprintf("Called");

    if (statePtr->callback == (Tcl_Obj*)NULL) {
    if (statePtr->vcmd == (Tcl_Obj*)NULL) {
	return SSL_CLIENT_HELLO_SUCCESS;
    } else if (ssl == NULL) {
    } else if (ssl == NULL || arg == NULL) {
	return SSL_CLIENT_HELLO_ERROR;
    }

    /* Get names */
    if (!SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &p, &remaining) || remaining <= 2) {
	*alert = SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER;
        return SSL_CLIENT_HELLO_ERROR;
	return SSL_CLIENT_HELLO_ERROR;
    }

    /* Extract the length of the supplied list of names. */
    len = (*(p++) << 8);
    len += *(p++);
    if (len + 2 != remaining) {
	*alert = SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER;
        return SSL_CLIENT_HELLO_ERROR;
	return SSL_CLIENT_HELLO_ERROR;
    }
    remaining = len;

    /* The list in practice only has a single element, so we only consider the first one. */
    if (remaining == 0 || *p++ != TLSEXT_NAMETYPE_host_name) {
	*alert = SSL_R_TLSV1_ALERT_INTERNAL_ERROR;
        return SSL_CLIENT_HELLO_ERROR;
	return SSL_CLIENT_HELLO_ERROR;
    }
    remaining--;

    /* Now we can finally pull out the byte array with the actual hostname. */
    if (remaining <= 2) {
	*alert = SSL_R_TLSV1_ALERT_INTERNAL_ERROR;
        return SSL_CLIENT_HELLO_ERROR;
	return SSL_CLIENT_HELLO_ERROR;
    }
    len = (*(p++) << 8);
    len += *(p++);
    if (len + 2 > remaining) {
	*alert = SSL_R_TLSV1_ALERT_INTERNAL_ERROR;
        return SSL_CLIENT_HELLO_ERROR;
	return SSL_CLIENT_HELLO_ERROR;
    }
    remaining = len;
    servername = (const char *)p;

    /* Create command to eval */
    cmdPtr = Tcl_DuplicateObj(statePtr->callback);
    cmdPtr = Tcl_DuplicateObj(statePtr->vcmd);
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("hello", -1));
    Tcl_ListObjAppendElement(interp, cmdPtr,
	    Tcl_NewStringObj(Tcl_GetChannelName(statePtr->self), -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(servername, (int) len));

    Tcl_Preserve((ClientData) interp);
    Tcl_Preserve((ClientData) statePtr);

    /* Eval callback command */
    Tcl_IncrRefCount(cmdPtr);
    code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL);
    if (code != TCL_OK) {
    if ((code = EvalCallback(interp, statePtr, cmdPtr)) > 1) {
	res = SSL_CLIENT_HELLO_RETRY;
	*alert = SSL_R_TLSV1_ALERT_USER_CANCELLED;
    } else if (code == 1) {
#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6)
	Tcl_BackgroundError(interp);
#else
	res = SSL_CLIENT_HELLO_SUCCESS;
    } else {
	Tcl_BackgroundException(interp, code);
#endif
	res = SSL_CLIENT_HELLO_ERROR;
	*alert = SSL_R_TLSV1_ALERT_INTERNAL_ERROR;
    }
    Tcl_DecrRefCount(cmdPtr);

    Tcl_Release((ClientData) statePtr);
    Tcl_Release((ClientData) interp);
    return SSL_CLIENT_HELLO_SUCCESS;
    return res;
}

/********************/
/* Commands         */
/********************/

/*
825
826
827
828
829
830
831
832

833
834
835
836
837
838
839
1011
1012
1013
1014
1015
1016
1017

1018
1019
1020
1021
1022
1023
1024
1025







-
+







#endif
	case TLS_TLS1_3:
#if defined(NO_TLS1_3) || defined(OPENSSL_NO_TLS1_3)
	    Tcl_AppendResult(interp, protocols[index], ": protocol not supported", NULL);
	    return TCL_ERROR;
#else
	    ctx = SSL_CTX_new(TLS_method());
            SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
	    SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
	    SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
	    break;
#endif
	default:
	    break;
    }
    if (ctx == NULL) {
916
917
918
919
920
921
922


923
924
925
926
927
928
929

930
931
932

933
934
935

936
937
938

939
940
941
942
943
944
945
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







+
+






-
+


-
+


-
+


-
+








    dprintf("Called");

    if (objc != 1) {
	Tcl_WrongNumArgs(interp, 1, objv, "");
	return TCL_ERROR;
    }

    ERR_clear_error();

    objPtr = Tcl_NewListObj(0, NULL);

#if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(NO_SSL2) && !defined(OPENSSL_NO_SSL2)
    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(protocols[TLS_SSL2], -1));
#endif
#if !defined(NO_SSL3) && !defined(OPENSSL_NO_SSL3)
#if !defined(NO_SSL3) && !defined(OPENSSL_NO_SSL3) && !defined(OPENSSL_NO_SSL3_METHOD)
    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(protocols[TLS_SSL3], -1));
#endif
#if !defined(NO_TLS1) && !defined(OPENSSL_NO_TLS1)
#if !defined(NO_TLS1) && !defined(OPENSSL_NO_TLS1) && !defined(OPENSSL_NO_TLS1_METHOD)
    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(protocols[TLS_TLS1], -1));
#endif
#if !defined(NO_TLS1_1) && !defined(OPENSSL_NO_TLS1_1)
#if !defined(NO_TLS1_1) && !defined(OPENSSL_NO_TLS1_1) && !defined(OPENSSL_NO_TLS1_1_METHOD)
    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(protocols[TLS_TLS1_1], -1));
#endif
#if !defined(NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_2)
#if !defined(NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_2_METHOD)
    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(protocols[TLS_TLS1_2], -1));
#endif
#if !defined(NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_3)
    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(protocols[TLS_TLS1_3], -1));
#endif

    Tcl_SetObjResult(interp, objPtr);
972
973
974
975
976
977
978


979
980
981
982
983
984
985
986
987
988



989
990
991
992
993
994
995
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







+
+









-
+
+
+








    dprintf("Called");

    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "channel");
	return(TCL_ERROR);
    }

    ERR_clear_error();

    chan = Tcl_GetChannel(interp, Tcl_GetStringFromObj(objv[1], NULL), NULL);
    if (chan == (Tcl_Channel) NULL) {
	return(TCL_ERROR);
    }

    /* Make sure to operate on the topmost channel */
    chan = Tcl_GetTopChannel(chan);
    if (Tcl_GetChannelType(chan) != Tls_ChannelType()) {
	Tcl_AppendResult(interp, "bad channel \"", Tcl_GetChannelName(chan), "\": not a TLS channel", NULL);
	Tcl_AppendResult(interp, "bad channel \"", Tcl_GetChannelName(chan),
	    "\": not a TLS channel", NULL);
	Tcl_SetErrorCode(interp, "TLS", "HANDSHAKE", "CHANNEL", "INVALID", (char *) NULL);
	return(TCL_ERROR);
    }
    statePtr = (State *)Tcl_GetChannelInstanceData(chan);

    dprintf("Calling Tls_WaitForConnect");
    ret = Tls_WaitForConnect(statePtr, &err, 1);
    dprintf("Tls_WaitForConnect returned: %i", ret);
1003
1004
1005
1006
1007
1008
1009

1010
1011
1012
1013
1014
1015
1016
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209







+







	Tcl_SetErrno(err);

	if (!errStr || (*errStr == 0)) {
	    errStr = Tcl_PosixError(interp);
	}

	Tcl_AppendResult(interp, "handshake failed: ", errStr, (char *) NULL);
	Tcl_SetErrorCode(interp, "TLS", "HANDSHAKE", "FAILED", (char *) NULL);
	dprintf("Returning TCL_ERROR with handshake failed: %s", errStr);
	return(TCL_ERROR);
    } else {
	if (err != 0) {
	    dprintf("Got an error with a completed handshake: err = %i", err);
	}
	ret = 1;
1042
1043
1044
1045
1046
1047
1048

1049
1050
1051
1052
1053
1054
1055
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249







+







static int
ImportObjCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]) {
    Tcl_Channel chan;		/* The channel to set a mode on. */
    State *statePtr;		/* client state for ssl socket */
    SSL_CTX *ctx	        = NULL;
    Tcl_Obj *script	        = NULL;
    Tcl_Obj *password	        = NULL;
    Tcl_Obj *vcmd	        = NULL;
    Tcl_DString upperChannelTranslation, upperChannelBlocking, upperChannelEncoding, upperChannelEOFChar;
    int idx, len;
    int flags		        = TLS_TCL_INIT;
    int server		        = 0;	/* is connection incoming or outgoing? */
    char *keyfile	        = NULL;
    char *certfile	        = NULL;
    unsigned char *key  	= NULL;
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
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







+
+















+


+






+




-

+




-






-
-
+
+

-
+



-
-
-
-
+
+
+
+







    tls1_3 = 0;
#endif

    if (objc < 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "channel ?options?");
	return TCL_ERROR;
    }

    ERR_clear_error();

    chan = Tcl_GetChannel(interp, Tcl_GetStringFromObj(objv[1], NULL), NULL);
    if (chan == (Tcl_Channel) NULL) {
	return TCL_ERROR;
    }

    /* Make sure to operate on the topmost channel */
    chan = Tcl_GetTopChannel(chan);

    for (idx = 2; idx < objc; idx++) {
	char *opt = Tcl_GetStringFromObj(objv[idx], NULL);

	if (opt[0] != '-')
	    break;

	OPTOBJ("-alpn", alpn);
	OPTSTR("-cadir", CAdir);
	OPTSTR("-cafile", CAfile);
	OPTBYTE("-cert", cert, cert_len);
	OPTSTR("-certfile", certfile);
	OPTSTR("-cipher", ciphers);
	OPTSTR("-ciphers", ciphers);
	OPTSTR("-ciphersuites", ciphersuites);
	OPTOBJ("-command", script);
	OPTSTR("-dhparams", DHparams);
	OPTBYTE("-key", key, key_len);
	OPTSTR("-keyfile", keyfile);
	OPTSTR("-model", model);
	OPTOBJ("-password", password);
	OPTBOOL("-post_handshake", post_handshake);
	OPTBOOL("-require", require);
	OPTBOOL("-request", request);
	OPTBOOL("-require", require);
	OPTINT("-securitylevel", level);
	OPTBOOL("-server", server);
	OPTSTR("-servername", servername);
	OPTSTR("-session_id", session_id);
	OPTOBJ("-alpn", alpn);
	OPTBOOL("-ssl2", ssl2);
	OPTBOOL("-ssl3", ssl3);
	OPTBOOL("-tls1", tls1);
	OPTBOOL("-tls1.1", tls1_1);
	OPTBOOL("-tls1.2", tls1_2);
	OPTBOOL("-tls1.3", tls1_3);
	OPTBYTE("-cert", cert, cert_len);
	OPTBYTE("-key", key, key_len);
	OPTOBJ("-validatecommand", vcmd);
	OPTOBJ("-vcmd", vcmd);

	OPTBAD("option", "-alpn, -cadir, -cafile, -cert, -certfile, -cipher, -ciphersuites, -command, -dhparams, -key, -keyfile, -model, -password, -require, -request, -securitylevel, -server, -servername, -session_id, -ssl2, -ssl3, -tls1, -tls1.1, -tls1.2, or -tls1.3");
	OPTBAD("option", "-alpn, -cadir, -cafile, -cert, -certfile, -cipher, -ciphersuites, -command, -dhparams, -key, -keyfile, -model, -password, -post_handshake, -request, -require, -securitylevel, -server, -servername, -session_id, -ssl2, -ssl3, -tls1, -tls1.1, -tls1.2, -tls1.3, or -validatecommand");

	return TCL_ERROR;
    }
    if (request)	    verify |= SSL_VERIFY_CLIENT_ONCE | SSL_VERIFY_PEER;
    if (request && require) verify |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
    if (request && post_handshake)  verify |= SSL_VERIFY_POST_HANDSHAKE;
    if (verify == 0)	verify = SSL_VERIFY_NONE;
    if (request)		verify |= SSL_VERIFY_CLIENT_ONCE | SSL_VERIFY_PEER;
    if (request && require)	verify |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
    if (request && post_handshake)	verify |= SSL_VERIFY_POST_HANDSHAKE;
    if (verify == 0)		verify = SSL_VERIFY_NONE;

    proto |= (ssl2 ? TLS_PROTO_SSL2 : 0);
    proto |= (ssl3 ? TLS_PROTO_SSL3 : 0);
    proto |= (tls1 ? TLS_PROTO_TLS1 : 0);
    proto |= (tls1_1 ? TLS_PROTO_TLS1_1 : 0);
    proto |= (tls1_2 ? TLS_PROTO_TLS1_2 : 0);
    proto |= (tls1_3 ? TLS_PROTO_TLS1_3 : 0);
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
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







+
+
+
+
+
+
+
+
+

















+







    if (password) {
	(void) Tcl_GetStringFromObj(password, &len);
	if (len) {
	    statePtr->password = password;
	    Tcl_IncrRefCount(statePtr->password);
	}
    }

    /* allocate validate command */
    if (vcmd) {
	(void) Tcl_GetStringFromObj(vcmd, &len);
	if (len) {
	    statePtr->vcmd = vcmd;
	    Tcl_IncrRefCount(statePtr->vcmd);
	}
    }

    if (model != NULL) {
	int mode;
	/* Get the "model" context */
	chan = Tcl_GetChannel(interp, model, &mode);
	if (chan == (Tcl_Channel) NULL) {
	    Tls_Free((char *) statePtr);
	    return TCL_ERROR;
	}

	/*
	 * Make sure to operate on the topmost channel
	 */
	chan = Tcl_GetTopChannel(chan);
	if (Tcl_GetChannelType(chan) != Tls_ChannelType()) {
	    Tcl_AppendResult(interp, "bad channel \"", Tcl_GetChannelName(chan),
		"\": not a TLS channel", NULL);
	    Tcl_SetErrorCode(interp, "TLS", "IMPORT", "CHANNEL", "INVALID", (char *) NULL);
	    Tls_Free((char *) statePtr);
	    return TCL_ERROR;
	}
	ctx = ((State *)Tcl_GetChannelInstanceData(chan))->ctx;
    } else {
	if ((ctx = CTX_Init(statePtr, server, proto, keyfile, certfile, key, cert, key_len,
	    cert_len, CAdir, CAfile, ciphers, ciphersuites, level, DHparams)) == NULL) {
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
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







+






-
+
+


+
-
-
-
+
+
+





+
-
-
+
+








+






-
+















+




















+


















-
+
+
+
+
+
+
+
+
+







-



+
+
+
+
+
-
+
+
+
+

+
+




+



+
+
+
+
+
+
+









+







    /*
     * SSL Initialization
     */
    statePtr->ssl = SSL_new(statePtr->ctx);
    if (!statePtr->ssl) {
	/* SSL library error */
	Tcl_AppendResult(interp, "couldn't construct ssl session: ", REASON(), (char *) NULL);
	    Tcl_SetErrorCode(interp, "TLS", "IMPORT", "INIT", "FAILED", (char *) NULL);
	Tls_Free((char *) statePtr);
	return TCL_ERROR;
    }

    /* Set host server name */
    if (servername) {
	/* Sets the server name indication (SNI) ClientHello extension */
	/* Sets the server name indication (SNI) in ClientHello extension */
	/* Per RFC 6066, hostname is a ASCII encoded string. */
	if (!SSL_set_tlsext_host_name(statePtr->ssl, servername) && require) {
	    Tcl_AppendResult(interp, "setting TLS host name extension failed", (char *) NULL);
	    Tcl_SetErrorCode(interp, "TLS", "IMPORT", "SNI", "FAILED", (char *) NULL);
            Tls_Free((char *) statePtr);
            return TCL_ERROR;
        }
	    Tls_Free((char *) statePtr);
	    return TCL_ERROR;
	}

	/* Configure server host name checks in the SSL client. Set DNS hostname to
	   name for peer certificate checks. SSL_set1_host has limitations. */
	if (!SSL_add1_host(statePtr->ssl, servername)) {
	    Tcl_AppendResult(interp, "setting DNS host name failed", (char *) NULL);
	    Tcl_SetErrorCode(interp, "TLS", "IMPORT", "HOSTNAME", "FAILED", (char *) NULL);
            Tls_Free((char *) statePtr);
            return TCL_ERROR;
	    Tls_Free((char *) statePtr);
	    return TCL_ERROR;
	}
    }

    /* Resume session id */
    if (session_id && strlen(session_id) <= SSL_MAX_SID_CTX_LENGTH) {
	/* SSL_set_session() */
	if (!SSL_SESSION_set1_id_context(SSL_get_session(statePtr->ssl), session_id, (unsigned int) strlen(session_id))) {
	    Tcl_AppendResult(interp, "Resume session id ", session_id, " failed", (char *) NULL);
	    Tcl_SetErrorCode(interp, "TLS", "IMPORT", "SESSION", "FAILED", (char *) NULL);
            Tls_Free((char *) statePtr);
            return TCL_ERROR;
	}
    }

    if (alpn) {
	/* Convert a Tcl list into a protocol-list in wire-format */
	/* Convert a TCL list into a protocol-list in wire-format */
	unsigned char *protos, *p;
	unsigned int protos_len = 0;
	int i, len, cnt;
	Tcl_Obj **list;

	if (Tcl_ListObjGetElements(interp, alpn, &cnt, &list) != TCL_OK) {
	    Tls_Free((char *) statePtr);
	    return TCL_ERROR;
	}

	/* Determine the memory required for the protocol-list */
	for (i = 0; i < cnt; i++) {
	    Tcl_GetStringFromObj(list[i], &len);
	    if (len > 255) {
		Tcl_AppendResult(interp, "ALPN protocol name too long", (char *) NULL);
		Tcl_SetErrorCode(interp, "TLS", "IMPORT", "ALPN", "FAILED", (char *) NULL);
		Tls_Free((char *) statePtr);
		return TCL_ERROR;
	    }
	    protos_len += 1 + len;
	}

	/* Build the complete protocol-list */
	protos = ckalloc(protos_len);
	/* protocol-lists consist of 8-bit length-prefixed, byte strings */
	for (i = 0, p = protos; i < cnt; i++) {
	    char *str = Tcl_GetStringFromObj(list[i], &len);
	    *p++ = len;
	    memcpy(p, str, len);
	    p += len;
	}

	/* SSL_set_alpn_protos makes a copy of the protocol-list */
	/* Note: This functions reverses the return value convention */
	if (SSL_set_alpn_protos(statePtr->ssl, protos, protos_len)) {
	    Tcl_AppendResult(interp, "failed to set ALPN protocols", (char *) NULL);
	    Tcl_SetErrorCode(interp, "TLS", "IMPORT", "ALPN", "FAILED", (char *) NULL);
	    Tls_Free((char *) statePtr);
	    ckfree(protos);
	    return TCL_ERROR;
	}

	/* Store protocols list */
	statePtr->protos = protos;
	statePtr->protos_len = protos_len;
    } else {
	statePtr->protos = NULL;
	statePtr->protos_len = 0;
    }

    /*
     * SSL Callbacks
     */
    SSL_set_app_data(statePtr->ssl, (void *)statePtr);	/* point back to us */
    SSL_set_verify(statePtr->ssl, verify, VerifyCallback);
    SSL_CTX_set_info_callback(statePtr->ctx, InfoCallback);
    SSL_set_info_callback(statePtr->ssl, InfoCallback);

    /* Callback for observing protocol messages */
#ifndef OPENSSL_NO_SSL_TRACE
    /* void SSL_CTX_set_msg_callback_arg(statePtr->ctx, (void *)statePtr);
    void SSL_CTX_set_msg_callback(statePtr->ctx, MessageCallback); */
    SSL_set_msg_callback_arg(statePtr->ssl, (void *)statePtr);
    SSL_set_msg_callback(statePtr->ssl, MessageCallback);
#endif

    /* Create Tcl_Channel BIO Handler */
    statePtr->p_bio	= BIO_new_tcl(statePtr, BIO_NOCLOSE);
    statePtr->bio	= BIO_new(BIO_f_ssl());

    if (server) {
	/* Server callbacks */
	SSL_CTX_set_alpn_select_cb(statePtr->ctx, ALPNCallback, (void *)statePtr);
	SSL_CTX_set_tlsext_servername_arg(statePtr->ctx, (void *)statePtr);
	SSL_CTX_set_tlsext_servername_callback(statePtr->ctx, SNICallback);
	SSL_CTX_set_client_hello_cb(statePtr->ctx, HelloCallback, (void *)statePtr);
	if (statePtr->protos != NULL) {
	    SSL_CTX_set_alpn_select_cb(statePtr->ctx, ALPNCallback, (void *)statePtr);
#ifdef USE_NPN
	    if (tls1_2 == 0 && tls1_3 == 0) {
		SSL_CTX_set_next_protos_advertised_cb(statePtr->ctx, NPNCallback, (void *)statePtr);

	    }
#endif
	}

	/* Enable server to send cert request after handshake (TLS 1.3 only) */
	/* A write operation must take place for the Certificate Request to be
	   sent to the client, this can be done with SSL_do_handshake(). */
	if (request && post_handshake) {
	    SSL_verify_client_post_handshake(statePtr->ssl);
	}

	/* Set server mode */
	statePtr->flags |= TLS_TCL_SERVER;
	SSL_set_accept_state(statePtr->ssl);
    } else {
	/* Client callbacks */
#ifdef USE_NPN
	if (statePtr->protos != NULL && tls1_2 == 0 && tls1_3 == 0) {
	    SSL_CTX_set_next_proto_select_cb(statePtr->ctx, ALPNCallback, (void *)statePtr);
	}
#endif

	/* Session caching */
	SSL_CTX_set_session_cache_mode(statePtr->ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
	SSL_CTX_sess_set_new_cb(statePtr->ctx, SessionCallback);

	/* Enable post handshake Authentication extension. TLS 1.3 only, not http/2. */
	if (request && post_handshake) {
	    SSL_set_post_handshake_auth(statePtr->ssl, 1);
	}

	/* Set client mode */
	SSL_set_connect_state(statePtr->ssl);
    }
    SSL_set_bio(statePtr->ssl, statePtr->p_bio, statePtr->p_bio);
    BIO_set_ssl(statePtr->bio, statePtr->ssl, BIO_NOCLOSE);

    /*
     * End of SSL Init
1426
1427
1428
1429
1430
1431
1432

1433
1434
1435
1436
1437
1438
1439
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681







+








    /* Make sure to operate on the topmost channel */
    chan = Tcl_GetTopChannel(chan);

    if (Tcl_GetChannelType(chan) != Tls_ChannelType()) {
	Tcl_AppendResult(interp, "bad channel \"", Tcl_GetChannelName(chan),
		"\": not a TLS channel", NULL);
	    Tcl_SetErrorCode(interp, "TLS", "UNIMPORT", "CHANNEL", "INVALID", (char *) NULL);
	return TCL_ERROR;
    }

    if (Tcl_UnstackChannel(interp, chan) == TCL_ERROR) {
	return TCL_ERROR;
    }

1564
1565
1566
1567
1568
1569
1570
1571
1572

1573
1574
1575
1576
1577
1578
1579
1806
1807
1808
1809
1810
1811
1812

1813
1814
1815
1816
1817
1818
1819
1820
1821







-

+







#if !defined(NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_3)
	off |= (ENABLED(proto, TLS_PROTO_TLS1_3) ? 0 : SSL_OP_NO_TLSv1_3);
#endif
	break;
    }

    ERR_clear_error();
    ctx = SSL_CTX_new(method);

    ctx = SSL_CTX_new(method);
    if (!ctx) {
	return(NULL);
    }

    if (getenv(SSLKEYLOGFILE)) {
	SSL_CTX_set_keylog_callback(ctx, KeyLogCallback);
    }
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
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







-
+





-
-
-
+
+
+


-
-
-
+
+
+







	SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
    }

    SSL_CTX_set_app_data(ctx, (void*)interp);	/* remember the interpreter */
    SSL_CTX_set_options(ctx, SSL_OP_ALL);	/* all SSL bug workarounds */
    SSL_CTX_set_options(ctx, off);		/* disable protocol versions */
#if OPENSSL_VERSION_NUMBER < 0x10101000L
    SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);	/* handle new handshakes in background */
    SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);	/* handle new handshakes in background. On by default in OpenSSL 1.1.1. */
#endif
    SSL_CTX_sess_set_cache_size(ctx, 128);

    /* Set user defined ciphers, cipher suites, and security level */
    if ((ciphers != NULL) && !SSL_CTX_set_cipher_list(ctx, ciphers)) {
	    Tcl_AppendResult(interp, "Set ciphers failed: No valid ciphers", (char *) NULL);
	    SSL_CTX_free(ctx);
	    return NULL;
	Tcl_AppendResult(interp, "Set ciphers failed: No valid ciphers", (char *) NULL);
	SSL_CTX_free(ctx);
	return NULL;
    }
    if ((ciphersuites != NULL) && !SSL_CTX_set_ciphersuites(ctx, ciphersuites)) {
	    Tcl_AppendResult(interp, "Set cipher suites failed: No valid ciphers", (char *) NULL);
	    SSL_CTX_free(ctx);
	    return NULL;
	Tcl_AppendResult(interp, "Set cipher suites failed: No valid ciphers", (char *) NULL);
	SSL_CTX_free(ctx);
	return NULL;
    }

    /* Set security level */
    if (level > -1 && level < 6) {
	/* SSL_set_security_level */
	SSL_CTX_set_security_level(ctx, level);
    }
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
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100

2101
2102
2103
2104
2105
2106
2107
2108







+



+
+















+













-
+







	return TCL_ERROR;
    }
    /* Make sure to operate on the topmost channel */
    chan = Tcl_GetTopChannel(chan);
    if (Tcl_GetChannelType(chan) != Tls_ChannelType()) {
	Tcl_AppendResult(interp, "bad channel \"", Tcl_GetChannelName(chan),
		"\": not a TLS channel", NULL);
	Tcl_SetErrorCode(interp, "TLS", "STATUS", "CHANNEL", "INVALID", (char *) NULL);
	return TCL_ERROR;
    }
    statePtr = (State *) Tcl_GetChannelInstanceData(chan);

    /* Get certificate for peer or self */
    if (objc == 2) {
	peer = SSL_get_peer_certificate(statePtr->ssl);
    } else {
	peer = SSL_get_certificate(statePtr->ssl);
    }
    if (peer) {
	objPtr = Tls_NewX509Obj(interp, peer);
	if (objc == 2) { X509_free(peer); }
    } else {
	objPtr = Tcl_NewListObj(0, NULL);
    }

    /* Peer cert chain (client only) */
    STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(statePtr->ssl);
    if (!peer && (ssl_certs == NULL || sk_X509_num(ssl_certs) == 0)) {
	Tcl_SetErrorCode(interp, "TLS", "STATUS", "CERTIFICATE", (char *) NULL);
	return TCL_ERROR;
    }

    /* Peer name from cert */
    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("peername", -1));
    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(SSL_get0_peername(statePtr->ssl), -1));

    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("sbits", -1));
    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewIntObj(SSL_get_cipher_bits(statePtr->ssl, NULL)));

    ciphers = (char*)SSL_get_cipher(statePtr->ssl);
    if ((ciphers != NULL) && (strcmp(ciphers, "(NONE)") != 0)) {
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("cipher", -1));
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(SSL_get_cipher(statePtr->ssl), -1));
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(ciphers, -1));
    }

    /* Verify the X509 certificate presented by the peer */
    Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("verification", -1));
    Tcl_ListObjAppendElement(interp, objPtr,
	Tcl_NewStringObj(X509_verify_cert_error_string(SSL_get_verify_result(statePtr->ssl)), -1));

1916
1917
1918
1919
1920
1921
1922
1923



1924
1925
1926
1927
1928
1929
1930
2162
2163
2164
2165
2166
2167
2168

2169
2170
2171
2172
2173
2174
2175
2176
2177
2178







-
+
+
+







    if (chan == (Tcl_Channel) NULL) {
	return(TCL_ERROR);
    }

    /* Make sure to operate on the topmost channel */
    chan = Tcl_GetTopChannel(chan);
    if (Tcl_GetChannelType(chan) != Tls_ChannelType()) {
	Tcl_AppendResult(interp, "bad channel \"", Tcl_GetChannelName(chan), "\": not a TLS channel", NULL);
	Tcl_AppendResult(interp, "bad channel \"", Tcl_GetChannelName(chan),
	    "\": not a TLS channel", NULL);
	Tcl_SetErrorCode(interp, "TLS", "CONNECTION", "CHANNEL", "INVALID", (char *) NULL);
	return(TCL_ERROR);
    }

    objPtr = Tcl_NewListObj(0, NULL);

    /* Connection info */
    statePtr = (State *)Tcl_GetChannelInstanceData(chan);
1973
1974
1975
1976
1977
1978
1979
1980

1981
1982
1983
1984
1985
1986
1987
2221
2222
2223
2224
2225
2226
2227

2228
2229
2230
2231
2232
2233
2234
2235







-
+








	bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("bits", -1));
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewIntObj(bits));
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("secret_bits", -1));
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewIntObj(alg_bits));
	/* alg_bits is actual key secret bits. If use bits and secret (algorithm) bits differ,
           the rest of the bits are fixed, i.e. for limited export ciphers (bits < 56) */
	   the rest of the bits are fixed, i.e. for limited export ciphers (bits < 56) */
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("min_version", -1));
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(SSL_CIPHER_get_version(cipher), -1));

	/* Get OpenSSL-specific ID, not IANA ID */
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("id", -1));
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewIntObj((int) SSL_CIPHER_get_id(cipher)));

2000
2001
2002
2003
2004
2005
2006







2007
2008
2009
2010
2011
2012
2013
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268







+
+
+
+
+
+
+







	const unsigned char *session_id;
	char buffer[SSL_MAX_MASTER_KEY_LENGTH];

	/* Report the selected protocol as a result of the ALPN negotiation */
	SSL_SESSION_get0_alpn_selected(session, &proto, &len2);
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("alpn", -1));
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj((char *)proto, (int) len2));

	/* Report the selected protocol as a result of the NPN negotiation */
#ifdef USE_NPN
	SSL_get0_next_proto_negotiated(ssl, &proto, &ulen);
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("npn", -1));
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj((char *)proto, (int) ulen));
#endif

	/* Resumable session */
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("resumable", -1));
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewIntObj(SSL_SESSION_is_resumable(session)));

	/* Session start time (seconds since epoch) */
	Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("start_time", -1));
2135
2136
2137
2138
2139
2140
2141


2142
2143
2144
2145
2146
2147
2148
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405







+
+







    if (objc < 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "subcommand ?args?");
	return TCL_ERROR;
    }
    if (Tcl_GetIndexFromObj(interp, objv[1], commands, "command", 0,&cmd) != TCL_OK) {
	return TCL_ERROR;
    }

    ERR_clear_error();

    isStr = (cmd == C_STRREQ);
    switch ((enum command) cmd) {
	case C_REQ:
	case C_STRREQ: {
	    EVP_PKEY *pkey=NULL;
	    X509 *cert=NULL;
2404
2405
2406
2407
2408
2409
2410




2411
2412
2413
2414
2415
2416
2417
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678







+
+
+
+







	Tcl_DecrRefCount(statePtr->callback);
	statePtr->callback = NULL;
    }
    if (statePtr->password) {
	Tcl_DecrRefCount(statePtr->password);
	statePtr->password = NULL;
    }
    if (statePtr->vcmd) {
	Tcl_DecrRefCount(statePtr->vcmd);
	statePtr->vcmd = NULL;
    }

    dprintf("Returning");
}

/*
 *-------------------------------------------------------------------
 *
2514
2515
2516
2517
2518
2519
2520
2521
2522


2523
2524
2525


2526
2527

2528
2529
2530

2531
2532
2533
2534
2535
2536





2537
2538

2539
2540
2541

2542
2543
2544

2545
2546
2547
2548
2549


2550
2551
2552
2553
2554
2555
2556
2775
2776
2777
2778
2779
2780
2781


2782
2783
2784


2785
2786
2787

2788
2789
2790

2791
2792





2793
2794
2795
2796
2797
2798

2799
2800
2801

2802
2803
2804

2805
2806
2807
2808


2809
2810
2811
2812
2813
2814
2815
2816
2817







-
-
+
+

-
-
+
+

-
+


-
+

-
-
-
-
-
+
+
+
+
+

-
+


-
+


-
+



-
-
+
+







    static int initialized = 0;
    int status = TCL_OK;
#if defined(OPENSSL_THREADS) && defined(TCL_THREADS)
    size_t num_locks;
#endif

    if (uninitialize) {
        if (!initialized) {
            dprintf("Asked to uninitialize, but we are not initialized");
	if (!initialized) {
	    dprintf("Asked to uninitialize, but we are not initialized");

            return(TCL_OK);
        }
	    return(TCL_OK);
	}

        dprintf("Asked to uninitialize");
	dprintf("Asked to uninitialize");

#if defined(OPENSSL_THREADS) && defined(TCL_THREADS)
        Tcl_MutexLock(&init_mx);
	Tcl_MutexLock(&init_mx);

        if (locks) {
            free(locks);
            locks = NULL;
            locksCount = 0;
        }
	if (locks) {
	    free(locks);
	    locks = NULL;
	    locksCount = 0;
	}
#endif
        initialized = 0;
	initialized = 0;

#if defined(OPENSSL_THREADS) && defined(TCL_THREADS)
        Tcl_MutexUnlock(&init_mx);
	Tcl_MutexUnlock(&init_mx);
#endif

        return(TCL_OK);
	return(TCL_OK);
    }

    if (initialized) {
        dprintf("Called, but using cached value");
        return(status);
	dprintf("Called, but using cached value");
	return(status);
    }

    dprintf("Called");

#if defined(OPENSSL_THREADS) && defined(TCL_THREADS)
    Tcl_MutexLock(&init_mx);
#endif

Modified generic/tlsIO.c from [a52b873d9c] to [ede520a139].

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







+


















+

-
+







 * Also work done by the follow people provided the impetus to do this "right":
 *    tclSSL (Colin McCormack, Shared Technology)
 *    SSLtcl (Peter Antman)
 *
 */

#include "tlsInt.h"
#include <errno.h>

/*
 * Forward declarations
 */
static void TlsChannelHandlerTimer(ClientData clientData);

/*
 * TLS Channel Type
 */
static Tcl_ChannelType *tlsChannelType = NULL;

/*
 *-------------------------------------------------------------------
 *
 * TlsBlockModeProc --
 *
 *    This procedure is invoked by the generic IO level
 *       to set blocking and nonblocking modes
 *
 * Results:
 *    0 if successful, errno when failed.
 *    0 if successful or POSIX error code if failed.
 *
 * Side effects:
 *    Sets the device into blocking or nonblocking mode.
 *
 *-------------------------------------------------------------------
 */
static int TlsBlockModeProc(ClientData instanceData, int mode) {
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
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







-
+



















-
+
+
+
+
+
+
+
+









-
+

+
+
+
-
-
+
+
-
-
-







+






-







 *    This procedure is invoked by the generic IO level to perform
 *    channel-type-specific cleanup when a SSL socket based channel
 *    is closed.
 *
 *    Note: we leave the underlying socket alone, is this right?
 *
 * Results:
 *    0 if successful, the value of Tcl_GetErrno() if failed.
 *    0 if successful or POSIX error code if failed.
 *
 * Side effects:
 *    Closes the socket of the channel.
 *
 *-------------------------------------------------------------------
 */
static int TlsCloseProc(ClientData instanceData, Tcl_Interp *interp) {
    State *statePtr = (State *) instanceData;

    dprintf("TlsCloseProc(%p)", (void *) statePtr);

    Tls_Clean(statePtr);
    Tcl_EventuallyFree((ClientData)statePtr, Tls_Free);
    return(0);

	/* Interp is unused. */
	interp = interp;
}

static int TlsCloseProc2(ClientData instanceData, Tcl_Interp *interp, int flags) {
static int TlsCloseProc2(ClientData instanceData,    /* The socket state. */
    Tcl_Interp *interp,		/* For errors - can be NULL. */
    int flags)			/* Flags to close read and/or write side of channel */
{
    State *statePtr = (State *) instanceData;

    dprintf("TlsCloseProc2(%p)", (void *) statePtr);

    if ((flags & (TCL_CLOSE_READ|TCL_CLOSE_WRITE)) == 0) {
	return TlsCloseProc(instanceData, interp);
    }
    return EINVAL;
}

/*
 *------------------------------------------------------*
 *
 *    Tls_WaitForConnect --
 * Tls_WaitForConnect --
 *
 * Result:
 *    0 if successful, -1 if failed.
 *
 *    Side effects:
 *        Issues SSL_accept or SSL_connect
 * Side effects:
 *    Issues SSL_accept or SSL_connect
 *
 *    Result:
 *        None.
 *
 *------------------------------------------------------*
 */
int Tls_WaitForConnect(State *statePtr, int *errorCodePtr, int handshakeFailureIsPermanent) {
    unsigned long backingError;
    int err, rc;
    int bioShouldRetry;
    *errorCodePtr = 0;

    dprintf("WaitForConnect(%p)", (void *) statePtr);
    dprintFlags(statePtr);

    if (!(statePtr->flags & TLS_TCL_INIT)) {
	dprintf("Tls_WaitForConnect called on already initialized channel -- returning with immediate success");
	*errorCodePtr = 0;
	return(0);
    }

    if (statePtr->flags & TLS_TCL_HANDSHAKE_FAILED) {
	/*
	 * Different types of operations have different requirements
	 * SSL being established
191
192
193
194
195
196
197
198
199
200
201
202
203

204
205
206


207
208
209
210
211
212
213
200
201
202
203
204
205
206


207
208
209
210
211
212
213

214
215
216
217
218
219
220
221
222







-
-




+


-
+
+







	    }
	}

	dprintf("We have either completely established the session or completely failed it -- there is no more need to ever retry it though");
	break;
    }

    *errorCodePtr = EINVAL;

    switch (rc) {
	case SSL_ERROR_NONE:
	    /* The connection is up, we are done here */
	    dprintf("The connection is up");
	    *errorCodePtr = 0;
	    break;
	case SSL_ERROR_ZERO_RETURN:
	    dprintf("SSL_ERROR_ZERO_RETURN: Connect returned an invalid value...")
	    dprintf("SSL_ERROR_ZERO_RETURN: Connect returned an invalid value...");
	    *errorCodePtr = EINVAL;
	    return(-1);
	case SSL_ERROR_SYSCALL:
	    backingError = ERR_get_error();

	    if (backingError == 0 && err == 0) {
		dprintf("EOF reached")
		*errorCodePtr = ECONNRESET;
274
275
276
277
278
279
280
281
282


283
284
285
286
287
288
289
290
283
284
285
286
287
288
289


290
291

292
293
294
295
296
297
298







-
-
+
+
-







 *
 * TlsInputProc --
 *
 *    This procedure is invoked by the generic IO level
 *       to read input from a SSL socket based channel.
 *
 * Results:
 *    The number of bytes read is returned or -1 on error. An output
 *    argument contains the POSIX error code on error, or zero if no
 *    Returns the number of bytes read or -1 on error. Sets errorCodePtr
 *    to a POSIX error code if an error occurred, or 0 if none.
 *    error occurred.
 *
 * Side effects:
 *    Reads input from the input device of the channel.
 *
 *-------------------------------------------------------------------
 */
static int TlsInputProc(ClientData instanceData, char *buf, int bufSize, int *errorCodePtr) {
304
305
306
307
308
309
310

311
312
313
314
315
316
317
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326







+







	return(0);
    }

    dprintf("Calling Tls_WaitForConnect");
    tlsConnect = Tls_WaitForConnect(statePtr, errorCodePtr, 0);
    if (tlsConnect < 0) {
	dprintf("Got an error waiting to connect (tlsConnect = %i, *errorCodePtr = %i)", tlsConnect, *errorCodePtr);
	Tls_Error(statePtr, strerror(*errorCodePtr));

	bytesRead = -1;
	if (*errorCodePtr == ECONNRESET) {
	    dprintf("Got connection reset");
	    /* Soft EOF */
	    *errorCodePtr = 0;
	    bytesRead = 0;
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
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







+
+
+













-
-
+
+







	default:
	    dprintf("Unknown error (err = %i), mapping to EOF", err);
	    *errorCodePtr = 0;
	    bytesRead = 0;
	    break;
    }

    if (*errorCodePtr < 0) {
	Tls_Error(statePtr, strerror(*errorCodePtr));
    }
    dprintf("Input(%d) -> %d [%d]", bufSize, bytesRead, *errorCodePtr);
    return(bytesRead);
}

/*
 *-------------------------------------------------------------------
 *
 * TlsOutputProc --
 *
 *    This procedure is invoked by the generic IO level
 *       to write output to a SSL socket based channel.
 *
 * Results:
 *    The number of bytes written is returned. An output argument is
 *    set to a POSIX error code if an error occurred, or zero.
 *    Returns the number of bytes written or -1 on error. Sets errorCodePtr
 *    to a POSIX error code if an error occurred, or 0 if none.
 *
 * Side effects:
 *    Writes output on the output device of the channel.
 *
 *-------------------------------------------------------------------
 */
static int TlsOutputProc(ClientData instanceData, const char *buf, int toWrite, int *errorCodePtr) {
434
435
436
437
438
439
440

441
442
443
444
445
446
447
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460







+







	return(-1);
    }

    dprintf("Calling Tls_WaitForConnect");
    tlsConnect = Tls_WaitForConnect(statePtr, errorCodePtr, 1);
    if (tlsConnect < 0) {
	dprintf("Got an error waiting to connect (tlsConnect = %i, *errorCodePtr = %i)", tlsConnect, *errorCodePtr);
	Tls_Error(statePtr, strerror(*errorCodePtr));

	written = -1;
	if (*errorCodePtr == ECONNRESET) {
	    dprintf("Got connection reset");
	    /* Soft EOF */
	    *errorCodePtr = 0;
	    written = 0;
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
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







+
+
+









-
+



-
-
-
+


-
+







	    break;

	default:
	    dprintf(" unknown err: %d", err);
	    break;
    }

    if (*errorCodePtr < 0) {
	Tls_Error(statePtr, strerror(*errorCodePtr));
    }
    dprintf("Output(%d) -> %d", toWrite, written);
    return(written);
}

/*
 *-------------------------------------------------------------------
 *
 * TlsSetOptionProc --
 *
 *    Computes an option value for a SSL socket based channel, or a
 *    Sets an option value for a SSL socket based channel, or a
 *    list of all options and their values.
 *
 * Results:
 *    A standard Tcl result. The value of the specified option or a
 *    list of all options and    their values is returned in the
 *    supplied DString.
 *    TCL_OK if successful or TCL_ERROR if failed.
 *
 * Side effects:
 *    None.
 *    Updates channel option to new value.
 *
 *-------------------------------------------------------------------
 */
static int
TlsSetOptionProc(ClientData instanceData,    /* Socket state. */
    Tcl_Interp *interp,		/* For errors - can be NULL. */
    const char *optionName,	/* Name of the option to set the value for, or
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
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







-
+







-
+




-
+












-
+








-
+









-
+




















-
-
+
+







	 * Request is query for all options, this is ok.
	 */
	return TCL_OK;
    }
    /*
     * Request for a specific option has to fail, we don't have any.
     */
    return TCL_ERROR;
    return Tcl_BadChannelOption(interp, optionName, "");
}

/*
 *-------------------------------------------------------------------
 *
 * TlsGetOptionProc --
 *
 *    Computes an option value for a SSL socket based channel, or a
 *    Gets an option value for a SSL socket based channel, or a
 *    list of all options and their values.
 *
 * Results:
 *    A standard Tcl result. The value of the specified option or a
 *    list of all options and    their values is returned in the
 *    list of all options and their values is returned in the
 *    supplied DString.
 *
 * Side effects:
 *    None.
 *
 *-------------------------------------------------------------------
 */
static int
TlsGetOptionProc(ClientData instanceData,    /* Socket state. */
    Tcl_Interp *interp,		/* For errors - can be NULL. */
    const char *optionName,	/* Name of the option to retrieve the value for, or
				 * NULL to get all options and their values. */
    Tcl_DString *dsPtr)		/* Where to store the computed value initialized by caller. */
    Tcl_DString *optionValue)	/* Where to store the computed value initialized by caller. */
{
    State *statePtr = (State *) instanceData;

    Tcl_Channel downChan = Tls_GetParent(statePtr, TLS_TCL_FASTPATH);
    Tcl_DriverGetOptionProc *getOptionProc;

    getOptionProc = Tcl_ChannelGetOptionProc(Tcl_GetChannelType(downChan));
    if (getOptionProc != NULL) {
	return (*getOptionProc)(Tcl_GetChannelInstanceData(downChan), interp, optionName, dsPtr);
	return (*getOptionProc)(Tcl_GetChannelInstanceData(downChan), interp, optionName, optionValue);
    } else if (optionName == (char*) NULL) {
	/*
	 * Request is query for all options, this is ok.
	 */
	return TCL_OK;
    }
    /*
     * Request for a specific option has to fail, we don't have any.
     */
    return TCL_ERROR;
    return Tcl_BadChannelOption(interp, optionName, "");
}

/*
 *-------------------------------------------------------------------
 *
 * TlsWatchProc --
 *
 *    Initialize the notifier to watch Tcl_Files from this channel.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Sets up the notifier so that a future event on the channel
 *    will be seen by Tcl.
 *
 *-------------------------------------------------------------------
 */
static void
TlsWatchProc(ClientData instanceData,    /* The socket state. */
    int mask)		/* Events of interest; an OR-ed combination of
			* TCL_READABLE, TCL_WRITABLE and TCL_EXCEPTION. */
    int mask)			/* Events of interest; an OR-ed combination of
				 * TCL_READABLE, TCL_WRITABLE and TCL_EXCEPTION. */
{
    Tcl_Channel     downChan;
    State *statePtr = (State *) instanceData;

    dprintf("TlsWatchProc(0x%x)", mask);

    /* Pretend to be dead as long as the verify callback is running.
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
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







-
-
-
-
-
-
+
+
+
+
+
+












-
+






-
+
+
+
+














-
+






-
+
+
+
+







	dprintf("A timer was found, deleting it");
	Tcl_DeleteTimerHandler(statePtr->timer);
	statePtr->timer = (Tcl_TimerToken) NULL;
    }

    if ((mask & TCL_READABLE) &&
	((Tcl_InputBuffered(statePtr->self) > 0) || (BIO_ctrl_pending(statePtr->bio) > 0))) {
	    /*
	     * There is interest in readable events and we actually have
	     * data waiting, so generate a timer to flush that.
	     */
	    dprintf("Creating a new timer since data appears to be waiting");
	    statePtr->timer = Tcl_CreateTimerHandler(TLS_TCL_DELAY, TlsChannelHandlerTimer, (ClientData) statePtr);
	/*
	 * There is interest in readable events and we actually have
	 * data waiting, so generate a timer to flush that.
	 */
	dprintf("Creating a new timer since data appears to be waiting");
	statePtr->timer = Tcl_CreateTimerHandler(TLS_TCL_DELAY, TlsChannelHandlerTimer, (ClientData) statePtr);
    }
}

/*
 *-------------------------------------------------------------------
 *
 * TlsGetHandleProc --
 *
 *    Called from Tcl_GetChannelFile to retrieve o/s file handler
 *    from the SSL socket based channel.
 *
 * Results:
 *    The appropriate Tcl_File or NULL if not present.
 *    The appropriate Tcl_File handle or NULL if none.
 *
 * Side effects:
 *    None.
 *
 *-------------------------------------------------------------------
 */
static int TlsGetHandleProc(ClientData instanceData, int direction, ClientData *handlePtr) {
static int TlsGetHandleProc(ClientData instanceData,    /* Socket state. */
    int direction,		/* TCL_READABLE or TCL_WRITABLE */
    ClientData *handlePtr)	/* Handle associated with the channel */
{
    State *statePtr = (State *) instanceData;

    return(Tcl_GetChannelHandle(Tls_GetParent(statePtr, TLS_TCL_FASTPATH), direction, handlePtr));
}

/*
 *-------------------------------------------------------------------
 *
 * TlsNotifyProc --
 *
 *    Handler called by Tcl to inform us of activity
 *    on the underlying channel.
 *
 * Results:
 *    None.
 *    Type of event or 0 if failed
 *
 * Side effects:
 *    May process the incoming event by itself.
 *
 *-------------------------------------------------------------------
 */
static int TlsNotifyProc(ClientData instanceData, int mask) {
static int TlsNotifyProc(ClientData instanceData,    /* Socket state. */
    int mask)			/* type of event that occurred:
				 * OR-ed combination of TCL_READABLE or TCL_WRITABLE */
{
    State *statePtr = (State *) instanceData;
    int errorCode;

    /*
     * An event occurred in the underlying channel.  This
     * transformation doesn't process such events thus returns the
     * incoming mask unchanged.
773
774
775
776
777
778
779

780
781
782
783
784
785
786
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807







+







	dprintf("Returning 0 due to callback");
	return 0;
    }

    dprintf("Calling Tls_WaitForConnect");
    errorCode = 0;
    if (Tls_WaitForConnect(statePtr, &errorCode, 1) < 0) {
	Tls_Error(statePtr, strerror(errorCode));
	if (errorCode == EAGAIN) {
	    dprintf("Async flag could be set (didn't check) and errorCode == EAGAIN:  Returning 0");

	    return 0;
	}

	dprintf("Tls_WaitForConnect returned an error");
809
810
811
812
813
814
815
816

817
818
819
820
821
822
823
830
831
832
833
834
835
836

837
838
839
840
841
842
843
844







-
+







 *
 *      Result:
 *              None.
 *
 *------------------------------------------------------*
 */
static void
TlsChannelHandler (ClientData clientData, int mask) {
TlsChannelHandler(ClientData clientData, int mask) {
    State *statePtr = (State *) clientData;

    dprintf("HANDLER(0x%x)", mask);
    Tcl_Preserve((ClientData)statePtr);

    if (mask & TCL_READABLE) {
	BIO_set_flags(statePtr->p_bio, BIO_FLAGS_READ);

Modified generic/tlsInt.h from [c6bd77ee65] to [bb784703e5].

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







-
+


-
-
-
+
+
+

-
-
-
+
+
+
+

-
-
-
-
-
+
+
+
+
+








/*
 * This structure describes the per-instance state of an SSL channel.
 *
 * The SSL processing context is maintained here, in the ClientData
 */
typedef struct State {
	Tcl_Channel self;       /* this socket channel */
	Tcl_Channel self;	/* this socket channel */
	Tcl_TimerToken timer;

	int flags;              /* see State.flags above  */
	int watchMask;          /* current WatchProc mask */
	int mode;               /* current mode of parent channel */
	int flags;		/* see State.flags above  */
	int watchMask;		/* current WatchProc mask */
	int mode;		/* current mode of parent channel */

	Tcl_Interp *interp;     /* interpreter in which this resides */
	Tcl_Obj *callback;      /* script called for tracing, verifying and errors */
	Tcl_Obj *password;      /* script called for certificate password */
	Tcl_Interp *interp;	/* interpreter in which this resides */
	Tcl_Obj *callback;	/* script called for tracing, info, and errors */
	Tcl_Obj *password;	/* script called for certificate password */
	Tcl_Obj *vcmd;		/* script called to verify or validate protocol config */

	int vflags;             /* verify flags */
	SSL *ssl;               /* Struct for SSL processing */
	SSL_CTX *ctx;           /* SSL Context */
	BIO *bio;               /* Struct for SSL processing */
	BIO *p_bio;             /* Parent BIO (that is layered on Tcl_Channel) */
	int vflags;		/* verify flags */
	SSL *ssl;		/* Struct for SSL processing */
	SSL_CTX *ctx;		/* SSL Context */
	BIO *bio;		/* Struct for SSL processing */
	BIO *p_bio;		/* Parent BIO (that is layered on Tcl_Channel) */

	char *protos;		/* List of supported protocols in protocol format */
	unsigned int protos_len; /* Length of protos */

	char *err;
} State;

Modified library/tls.tcl from [cfce68af71] to [806ff9312a].

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







+











+




+


-






+
+







    #### iopts: [tls::import] option
    ### How many arguments the following the option to consume
    variable socketOptionRules {
        {0 -async sopts 0}
        {* -myaddr sopts 1}
        {0 -myport sopts 1}
        {* -type sopts 1}
        {* -alpn iopts 1}
        {* -cadir iopts 1}
        {* -cafile iopts 1}
        {* -cert iopts 1}
        {* -certfile iopts 1}
        {* -cipher iopts 1}
        {* -ciphersuites iopts 1}
        {* -command iopts 1}
        {* -dhparams iopts 1}
        {* -key iopts 1}
        {* -keyfile iopts 1}
        {* -password iopts 1}
        {* -post_handshake iopts 1}
        {* -request iopts 1}
        {* -require iopts 1}
        {* -securitylevel iopts 1}
        {* -autoservername discardOpts 1}
        {* -server iopts 1}
        {* -servername iopts 1}
        {* -session_id iopts 1}
        {* -alpn iopts 1}
        {* -ssl2 iopts 1}
        {* -ssl3 iopts 1}
        {* -tls1 iopts 1}
        {* -tls1.1 iopts 1}
        {* -tls1.2 iopts 1}
        {* -tls1.3 iopts 1}
        {* -validatecommand iopts 1}
        {* -vcmd iopts 1}
    }

    # tls::socket and tls::init options as a humane readable string
    variable socketOptionsNoServer
    variable socketOptionsServer

    # Internal [switch] body to validate options
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
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







+













-
+




+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
















-
-
-
-
-
-
-
-
-
-
-
-
-


-
+


+




















-
+







	log 1 "tls::_accept error: ${::errorInfo}"
	close $chan
	error $err $::errorInfo $::errorCode
    } else {
	log 2 "tls::_accept - called \"$callback\" succeeded"
    }
}

#
# Sample callback for hooking: -
#
# error
# verify
# info
#
proc tls::callback {option args} {
    variable debug

    #log 2 [concat $option $args]

    switch -- $option {
	"error"	{
	"error" {
	    foreach {chan msg} $args break

	    log 0 "TLS/$chan: error: $msg"
	}
	"info" {
	    # poor man's lassign
	    foreach {chan major minor msg type} $args break

	    if {$msg != ""} {
		append state ": $msg"
	    }
	    # For tracing
	    upvar #0 tls::$chan cb
	    set cb($major) $minor

	    log 2 "TLS/$chan: $major/$minor: $state"
	}
	"message" {
	    # poor man's lassign
	    foreach {chan direction version content_type msg} $args break

	    log 0 "TLS/$chan: info: $direction $msg"
	}
	"session" {
	    foreach {chan session_id ticket lifetime} $args break

	    log 0 "TLS/$chan: session: lifetime $lifetime"
	}
	default	{
	    return -code error "bad option \"$option\":\
		    must be one of error, info, or session"
	}
    }
}

#
# Sample callback when return value is needed
#
proc tls::validate_command {option args} {
    variable debug

    #log 2 [concat $option $args]

    switch -- $option {
	"alpn" {
	    foreach {chan protocol match} $args break

	    log 0 "TLS/$chan: alpn: $protocol $match"
	}
	"hello" {
	    foreach {chan servername} $args break

	    log 0 "TLS/$chan: hello: $servername"
	}
	"sni" {
	    foreach {chan servername} $args break

	    log 0 "TLS/$chan: sni: $servername"
	}
	"verify"	{
	"verify" {
	    # poor man's lassign
	    foreach {chan depth cert rc err} $args break

	    array set c $cert

	    if {$rc != "1"} {
		log 1 "TLS/$chan: verify/$depth: Bad Cert: $err (rc = $rc)"
	    } else {
		log 2 "TLS/$chan: verify/$depth: $c(subject)"
	    }
	    if {$debug > 0} {
		return 1;	# FORCE OK
	    } else {
		return $rc
	    }
	}
	"info"	{
	    # poor man's lassign
	    foreach {chan major minor state msg} $args break

	    if {$msg != ""} {
		append state ": $msg"
	    }
	    # For tracing
	    upvar #0 tls::$chan cb
	    set cb($major) $minor

	    log 2 "TLS/$chan: $major/$minor: $state"
	}
	default	{
	    return -code error "bad option \"$option\":\
		    must be one of error, info, or verify"
		    must be one of alpn, info, or verify"
	}
    }
    return 1
}

proc tls::xhandshake {chan} {
    upvar #0 tls::$chan cb

    if {[info exists cb(handshake)] && \
	$cb(handshake) == "done"} {
	return 1
    }
    while {1} {
	vwait tls::${chan}(handshake)
	if {![info exists cb(handshake)]} {
	    return 0
	}
	if {$cb(handshake) == "done"} {
	    return 1
	}
    }
}

proc tls::password {} {
proc tls::password {rwflag size} {
    log 0 "TLS/Password: did you forget to set your passwd!"
    # Return the worlds best kept secret password.
    return "secret"
}

proc tls::log {level msg} {
    variable debug