]> git.ipfire.org Git - thirdparty/cups.git/blame - cups/tls-darwin.c
Add SSLOptions to enable Diffie-Hellman key exchange and disable TLS/1.0.
[thirdparty/cups.git] / cups / tls-darwin.c
CommitLineData
2c85b752
MS
1/*
2 * "$Id$"
3 *
4 * TLS support code for CUPS on OS X.
5 *
3abb875b 6 * Copyright 2007-2015 by Apple Inc.
2c85b752
MS
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
8 *
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
14 *
15 * This file is subject to the Apple OS-Developed Software exception.
16 */
17
ebb24a07 18/**** This file is included from tls.c ****/
2c85b752
MS
19
20/*
dafebafd 21 * Include necessary headers...
2c85b752
MS
22 */
23
dafebafd
MS
24#include <spawn.h>
25
26extern char **environ;
27
28
c0459938
MS
29/*
30 * Local globals...
31 */
32
eb66bc71 33#ifdef HAVE_SECKEYCHAINOPEN
c0459938
MS
34static int tls_auto_create = 0;
35 /* Auto-create self-signed certs? */
36static char *tls_common_name = NULL;
37 /* Default common name */
41e0907c
MS
38static SecKeychainRef tls_keychain = NULL;
39 /* Server cert keychain */
40static char *tls_keypath = NULL;
41 /* Server cert keychain path */
42static _cups_mutex_t tls_mutex = _CUPS_MUTEX_INITIALIZER;
43 /* Mutex for keychain/certs */
63aefcd5 44static int tls_options = 0;/* Options for TLS connections */
eb66bc71 45#endif /* HAVE_SECKEYCHAINOPEN */
c0459938
MS
46
47
dafebafd
MS
48/*
49 * Local functions...
50 */
2c85b752 51
eb66bc71 52#ifdef HAVE_SECKEYCHAINOPEN
41e0907c 53static CFArrayRef http_cdsa_copy_server(const char *common_name);
eb66bc71 54#endif /* HAVE_SECKEYCHAINOPEN */
2ece34a9 55static SecCertificateRef http_cdsa_create_credential(http_credential_t *credential);
005f7f1f 56static const char *http_cdsa_default_path(char *buffer, size_t bufsize);
41e0907c 57static OSStatus http_cdsa_read(SSLConnectionRef connection, void *data, size_t *dataLength);
88f1e9c8 58static int http_cdsa_set_credentials(http_t *http);
41e0907c 59static OSStatus http_cdsa_write(SSLConnectionRef connection, const void *data, size_t *dataLength);
2c85b752
MS
60
61
3af9ac9e
MS
62/*
63 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
64 *
e1f19878 65 * @since CUPS 2.0/OS 10.10@
3af9ac9e
MS
66 */
67
68int /* O - 1 on success, 0 on failure */
69cupsMakeServerCredentials(
f93b32b6 70 const char *path, /* I - Keychain path or @code NULL@ for default */
3af9ac9e
MS
71 const char *common_name, /* I - Common name */
72 int num_alt_names, /* I - Number of subject alternate names */
73 const char **alt_names, /* I - Subject Alternate Names */
74 time_t expiration_date) /* I - Expiration date */
75{
eb66bc71 76#if defined(HAVE_SECGENERATESELFSIGNEDCERTIFICATE) && defined(HAVE_SECKEYCHAINOPEN)
f93b32b6 77 char filename[1024]; /* Default keychain path */
41e0907c
MS
78 int status = 0; /* Return status */
79 OSStatus err; /* Error code (if any) */
80 CFStringRef cfcommon_name = NULL;
81 /* CF string for server name */
82 SecIdentityRef ident = NULL; /* Identity */
83 SecKeyRef publicKey = NULL,
84 /* Public key */
85 privateKey = NULL;
86 /* Private key */
87 CFMutableDictionaryRef keyParams = NULL;
88 /* Key generation parameters */
89
90
172bdf5d
MS
91 DEBUG_printf(("cupsMakeServerCredentials(path=\"%s\", common_name=\"%s\", num_alt_names=%d, alt_names=%p, expiration_date=%d)", path, common_name, num_alt_names, alt_names, (int)expiration_date));
92
3af9ac9e
MS
93 (void)num_alt_names;
94 (void)alt_names;
95 (void)expiration_date;
96
f93b32b6 97 if (!path)
005f7f1f 98 path = http_cdsa_default_path(filename, sizeof(filename));
f93b32b6
MS
99
100 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
41e0907c
MS
101 if (!cfcommon_name)
102 goto cleanup;
103
104 /*
105 * Create a public/private key pair...
106 */
107
f93b32b6 108 keyParams = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
41e0907c
MS
109 if (!keyParams)
110 goto cleanup;
111
112 CFDictionaryAddValue(keyParams, kSecAttrKeyType, kSecAttrKeyTypeRSA);
113 CFDictionaryAddValue(keyParams, kSecAttrKeySizeInBits, CFSTR("2048"));
f93b32b6 114 CFDictionaryAddValue(keyParams, kSecAttrLabel, CFSTR("CUPS Self-Signed Certificate"));
41e0907c
MS
115
116 err = SecKeyGeneratePair(keyParams, &publicKey, &privateKey);
117 if (err != noErr)
118 goto cleanup;
119
120 /*
121 * Create a self-signed certificate using the public/private key pair...
122 */
123
124 CFIndex usageInt = kSecKeyUsageAll;
125 CFNumberRef usage = CFNumberCreate(alloc, kCFNumberCFIndexType, &usageInt);
126 CFDictionaryRef certParams = CFDictionaryCreateMutable(kCFAllocatorDefault,
127kSecCSRBasicContraintsPathLen, CFINT(0), kSecSubjectAltName, cfcommon_name, kSecCertificateKeyUsage, usage, NULL, NULL);
128 CFRelease(usage);
129
130 const void *ca_o[] = { kSecOidOrganization, CFSTR("") };
131 const void *ca_cn[] = { kSecOidCommonName, cfcommon_name };
132 CFArrayRef ca_o_dn = CFArrayCreate(kCFAllocatorDefault, ca_o, 2, NULL);
133 CFArrayRef ca_cn_dn = CFArrayCreate(kCFAllocatorDefault, ca_cn, 2, NULL);
134 const void *ca_dn_array[2];
135
136 ca_dn_array[0] = CFArrayCreate(kCFAllocatorDefault, (const void **)&ca_o_dn, 1, NULL);
137 ca_dn_array[1] = CFArrayCreate(kCFAllocatorDefault, (const void **)&ca_cn_dn, 1, NULL);
138
139 CFArrayRef subject = CFArrayCreate(kCFAllocatorDefault, ca_dn_array, 2, NULL);
140 SecCertificateRef cert = SecGenerateSelfSignedCertificate(subject, certParams, publicKey, privateKey);
141 CFRelease(subject);
142 CFRelease(certParams);
143
144 if (!cert)
145 goto cleanup;
146
147 ident = SecIdentityCreate(kCFAllocatorDefault, cert, privateKey);
148
149 if (ident)
150 status = 1;
151
152 /*
153 * Cleanup and return...
154 */
155
156cleanup:
157
158 if (cfcommon_name)
159 CFRelease(cfcommon_name);
160
161 if (keyParams)
162 CFRelease(keyParams);
163
164 if (ident)
165 CFRelease(ident);
166
167 if (cert)
168 CFRelease(cert);
169
170 if (publicKey)
171 CFRelease(publicKey);
172
173 if (privateKey)
174 CFRelease(publicKey);
175
176 return (status);
177
eb66bc71 178#else /* !(HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN) */
41e0907c 179 int pid, /* Process ID of command */
7d58a105
MS
180 status, /* Status of command */
181 i; /* Looping var */
41e0907c
MS
182 char command[1024], /* Command */
183 *argv[4], /* Command-line arguments */
7d58a105
MS
184 *envp[1000], /* Environment variables */
185 days[32], /* CERTTOOL_EXPIRATION_DAYS env var */
41e0907c 186 keychain[1024], /* Keychain argument */
f93b32b6
MS
187 infofile[1024], /* Type-in information for cert */
188 filename[1024]; /* Default keychain path */
41e0907c
MS
189 cups_file_t *fp; /* Seed/info file */
190
191
172bdf5d
MS
192 DEBUG_printf(("cupsMakeServerCredentials(path=\"%s\", common_name=\"%s\", num_alt_names=%d, alt_names=%p, expiration_date=%d)", path, common_name, num_alt_names, alt_names, (int)expiration_date));
193
41e0907c
MS
194 (void)num_alt_names;
195 (void)alt_names;
41e0907c 196
f93b32b6 197 if (!path)
005f7f1f 198 path = http_cdsa_default_path(filename, sizeof(filename));
f93b32b6 199
41e0907c
MS
200 /*
201 * Run the "certtool" command to generate a self-signed certificate...
202 */
203
204 if (!cupsFileFind("certtool", getenv("PATH"), 1, command, sizeof(command)))
205 return (-1);
206
207 /*
208 * Create a file with the certificate information fields...
209 *
210 * Note: This assumes that the default questions are asked by the certtool
211 * command...
212 */
213
214 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
215 return (-1);
216
217 cupsFilePrintf(fp,
218 "CUPS Self-Signed Certificate\n"
219 /* Enter key and certificate label */
220 "r\n" /* Generate RSA key pair */
221 "2048\n" /* Key size in bits */
222 "y\n" /* OK (y = yes) */
223 "b\n" /* Usage (b=signing/encryption) */
224 "s\n" /* Sign with SHA1 */
225 "y\n" /* OK (y = yes) */
226 "%s\n" /* Common name */
227 "\n" /* Country (default) */
228 "\n" /* Organization (default) */
229 "\n" /* Organizational unit (default) */
230 "\n" /* State/Province (default) */
231 "\n" /* Email address */
232 "y\n", /* OK (y = yes) */
233 common_name);
234 cupsFileClose(fp);
235
236 snprintf(keychain, sizeof(keychain), "k=%s", path);
237
238 argv[0] = "certtool";
239 argv[1] = "c";
240 argv[2] = keychain;
241 argv[3] = NULL;
242
7d58a105
MS
243 snprintf(days, sizeof(days), "CERTTOOL_EXPIRATION_DAYS=%d", (int)((expiration_date - time(NULL) + 86399) / 86400));
244 envp[0] = days;
245 for (i = 0; i < (int)(sizeof(envp) / sizeof(envp[0]) - 2) && environ[i]; i ++)
246 envp[i + 1] = environ[i];
247 envp[i] = NULL;
248
41e0907c
MS
249 posix_spawn_file_actions_t actions; /* File actions */
250
251 posix_spawn_file_actions_init(&actions);
252 posix_spawn_file_actions_addclose(&actions, 0);
253 posix_spawn_file_actions_addopen(&actions, 0, infofile, O_RDONLY, 0);
f93b32b6
MS
254 posix_spawn_file_actions_addclose(&actions, 1);
255 posix_spawn_file_actions_addopen(&actions, 1, "/dev/null", O_WRONLY, 0);
256 posix_spawn_file_actions_addclose(&actions, 2);
257 posix_spawn_file_actions_addopen(&actions, 2, "/dev/null", O_WRONLY, 0);
41e0907c 258
7d58a105 259 if (posix_spawn(&pid, command, &actions, NULL, argv, envp))
41e0907c
MS
260 {
261 unlink(infofile);
262 return (-1);
263 }
264
265 posix_spawn_file_actions_destroy(&actions);
266
267 unlink(infofile);
268
269 while (waitpid(pid, &status, 0) < 0)
270 if (errno != EINTR)
271 {
272 status = -1;
273 break;
274 }
275
276 return (!status);
eb66bc71 277#endif /* HAVE_SECGENERATESELFSIGNEDCERTIFICATE && HAVE_SECKEYCHAINOPEN */
3af9ac9e
MS
278}
279
280
281/*
282 * 'cupsSetServerCredentials()' - Set the default server credentials.
283 *
284 * Note: The server credentials are used by all threads in the running process.
285 * This function is threadsafe.
286 *
e1f19878 287 * @since CUPS 2.0/OS X 10.10@
3af9ac9e
MS
288 */
289
290int /* O - 1 on success, 0 on failure */
291cupsSetServerCredentials(
f93b32b6 292 const char *path, /* I - Keychain path or @code NULL@ for default */
3af9ac9e
MS
293 const char *common_name, /* I - Default common name for server */
294 int auto_create) /* I - 1 = automatically create self-signed certificates */
295{
a27a134a
MS
296 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path, common_name, auto_create));
297
eb66bc71 298#ifdef HAVE_SECKEYCHAINOPEN
f93b32b6 299 char filename[1024]; /* Filename for keychain */
c0459938 300 SecKeychainRef keychain = NULL;/* Temporary keychain */
3af9ac9e 301
c0459938 302
f93b32b6 303 if (!path)
005f7f1f 304 path = http_cdsa_default_path(filename, sizeof(filename));
f93b32b6 305
c0459938
MS
306 if (SecKeychainOpen(path, &keychain) != noErr)
307 {
308 /* TODO: Set cups last error string */
a27a134a 309 DEBUG_puts("1cupsSetServerCredentials: Unable to open keychain, returning 0.");
c0459938
MS
310 return (0);
311 }
312
313 _cupsMutexLock(&tls_mutex);
314
315 /*
316 * Close any keychain that is currently open...
317 */
318
319 if (tls_keychain)
320 CFRelease(tls_keychain);
321
41e0907c
MS
322 if (tls_keypath)
323 _cupsStrFree(tls_keypath);
324
c0459938
MS
325 if (tls_common_name)
326 _cupsStrFree(tls_common_name);
327
328 /*
329 * Save the new keychain...
330 */
331
332 tls_keychain = keychain;
41e0907c 333 tls_keypath = _cupsStrAlloc(path);
c0459938
MS
334 tls_auto_create = auto_create;
335 tls_common_name = _cupsStrAlloc(common_name);
336
337 _cupsMutexUnlock(&tls_mutex);
338
a27a134a 339 DEBUG_puts("1cupsSetServerCredentials: Opened keychain, returning 1.");
c0459938 340 return (1);
eb66bc71
MS
341
342#else
a27a134a 343 DEBUG_puts("1cupsSetServerCredentials: No keychain support compiled in, returning 0.");
eb66bc71
MS
344 return (0);
345#endif /* HAVE_SECKEYCHAINOPEN */
3af9ac9e
MS
346}
347
2c85b752
MS
348
349/*
350 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
351 * an encrypted connection.
352 *
353 * @since CUPS 1.5/OS X 10.7@
354 */
355
356int /* O - Status of call (0 = success) */
357httpCopyCredentials(
358 http_t *http, /* I - Connection to server */
359 cups_array_t **credentials) /* O - Array of credentials */
360{
361 OSStatus error; /* Error code */
362 SecTrustRef peerTrust; /* Peer trust reference */
363 CFIndex count; /* Number of credentials */
364 SecCertificateRef secCert; /* Certificate reference */
365 CFDataRef data; /* Certificate data */
366 int i; /* Looping var */
367
368
376d7c69
MS
369 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http, credentials));
370
2c85b752
MS
371 if (credentials)
372 *credentials = NULL;
373
374 if (!http || !http->tls || !credentials)
375 return (-1);
376
377 if (!(error = SSLCopyPeerTrust(http->tls, &peerTrust)) && peerTrust)
378 {
376d7c69
MS
379 DEBUG_printf(("2httpCopyCredentials: Peer provided %d certificates.", (int)SecTrustGetCertificateCount(peerTrust)));
380
2c85b752
MS
381 if ((*credentials = cupsArrayNew(NULL, NULL)) != NULL)
382 {
383 count = SecTrustGetCertificateCount(peerTrust);
384
385 for (i = 0; i < count; i ++)
386 {
387 secCert = SecTrustGetCertificateAtIndex(peerTrust, i);
376d7c69
MS
388
389#ifdef DEBUG
390 CFStringRef cf_name = SecCertificateCopySubjectSummary(secCert);
391 char name[1024];
392 if (cf_name)
393 CFStringGetCString(cf_name, name, sizeof(name), kCFStringEncodingUTF8);
394 else
395 strlcpy(name, "unknown", sizeof(name));
396
397 DEBUG_printf(("2httpCopyCredentials: Certificate %d name is \"%s\".", i, name));
398#endif /* DEBUG */
399
88f1e9c8 400 if ((data = SecCertificateCopyData(secCert)) != NULL)
2c85b752 401 {
376d7c69
MS
402 DEBUG_printf(("2httpCopyCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data)));
403
7e86f2f6 404 httpAddCredential(*credentials, CFDataGetBytePtr(data), (size_t)CFDataGetLength(data));
2c85b752
MS
405 CFRelease(data);
406 }
407 }
408 }
409
410 CFRelease(peerTrust);
411 }
412
413 return (error);
414}
415
416
417/*
418 * '_httpCreateCredentials()' - Create credentials in the internal format.
419 */
420
421http_tls_credentials_t /* O - Internal credentials */
422_httpCreateCredentials(
423 cups_array_t *credentials) /* I - Array of credentials */
424{
425 CFMutableArrayRef peerCerts; /* Peer credentials reference */
426 SecCertificateRef secCert; /* Certificate reference */
2c85b752
MS
427 http_credential_t *credential; /* Credential data */
428
429
430 if (!credentials)
431 return (NULL);
432
433 if ((peerCerts = CFArrayCreateMutable(kCFAllocatorDefault,
434 cupsArrayCount(credentials),
435 &kCFTypeArrayCallBacks)) == NULL)
436 return (NULL);
437
438 for (credential = (http_credential_t *)cupsArrayFirst(credentials);
439 credential;
440 credential = (http_credential_t *)cupsArrayNext(credentials))
441 {
9653cfdf 442 if ((secCert = http_cdsa_create_credential(credential)) != NULL)
2c85b752 443 {
9653cfdf
MS
444 CFArrayAppendValue(peerCerts, secCert);
445 CFRelease(secCert);
2c85b752
MS
446 }
447 }
448
449 return (peerCerts);
450}
451
452
3af9ac9e 453/*
524c65e6 454 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
3af9ac9e 455 *
e1f19878 456 * @since CUPS 2.0/OS X 10.10@
3af9ac9e
MS
457 */
458
524c65e6
MS
459int /* O - 1 if valid, 0 otherwise */
460httpCredentialsAreValidForName(
461 cups_array_t *credentials, /* I - Credentials */
462 const char *common_name) /* I - Name to check */
463{
464 SecCertificateRef secCert; /* Certificate reference */
465 CFStringRef cfcert_name = NULL;
466 /* Certificate's common name (CF string) */
467 char cert_name[256]; /* Certificate's common name (C string) */
468 int valid = 1; /* Valid name? */
469
470
471 if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
472 return (0);
473
474 /*
475 * Compare the common names...
476 */
477
478 if ((cfcert_name = SecCertificateCopySubjectSummary(secCert)) == NULL)
479 {
480 /*
481 * Can't get common name, cannot be valid...
482 */
483
484 valid = 0;
485 }
486 else if (CFStringGetCString(cfcert_name, cert_name, sizeof(cert_name), kCFStringEncodingUTF8) &&
487 _cups_strcasecmp(common_name, cert_name))
488 {
489 /*
490 * Not an exact match for the common name, check for wildcard certs...
491 */
492
493 const char *domain = strchr(common_name, '.');
494 /* Domain in common name */
495
496 if (strncmp(cert_name, "*.", 2) || !domain || _cups_strcasecmp(domain, cert_name + 1))
497 {
498 /*
499 * Not a wildcard match.
500 */
501
502 /* TODO: Check subject alternate names */
503 valid = 0;
504 }
505 }
506
507 if (cfcert_name)
508 CFRelease(cfcert_name);
509
510 CFRelease(secCert);
511
512 return (valid);
513}
514
515
516/*
517 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
518 *
e1f19878 519 * @since CUPS 2.0/OS X 10.10@
524c65e6
MS
520 */
521
522http_trust_t /* O - Level of trust */
523httpCredentialsGetTrust(
376d7c69
MS
524 cups_array_t *credentials, /* I - Credentials */
525 const char *common_name) /* I - Common name for trust lookup */
3af9ac9e 526{
9653cfdf 527 SecCertificateRef secCert; /* Certificate reference */
524c65e6
MS
528 http_trust_t trust = HTTP_TRUST_OK;
529 /* Trusted? */
376d7c69 530 cups_array_t *tcreds = NULL; /* Trusted credentials */
9653cfdf
MS
531 _cups_globals_t *cg = _cupsGlobals();
532 /* Per-thread globals */
3af9ac9e 533
9653cfdf 534
376d7c69 535 if (!common_name)
524c65e6 536 return (HTTP_TRUST_UNKNOWN);
376d7c69 537
9653cfdf 538 if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
524c65e6 539 return (HTTP_TRUST_UNKNOWN);
9653cfdf 540
3abb875b
MS
541 if (cg->any_root < 0)
542 _cupsSetDefaults();
543
376d7c69 544 /*
88f1e9c8 545 * Look this common name up in the default keychains...
376d7c69
MS
546 */
547
88f1e9c8 548 httpLoadCredentials(NULL, &tcreds, common_name);
376d7c69
MS
549
550 if (tcreds)
551 {
552 char credentials_str[1024], /* String for incoming credentials */
553 tcreds_str[1024]; /* String for saved credentials */
554
555 httpCredentialsString(credentials, credentials_str, sizeof(credentials_str));
556 httpCredentialsString(tcreds, tcreds_str, sizeof(tcreds_str));
557
558 if (strcmp(credentials_str, tcreds_str))
559 {
560 /*
561 * Credentials don't match, let's look at the expiration date of the new
562 * credentials and allow if the new ones have a later expiration...
563 */
564
565 if (httpCredentialsGetExpiration(credentials) <= httpCredentialsGetExpiration(tcreds) ||
524c65e6 566 !httpCredentialsAreValidForName(credentials, common_name))
376d7c69
MS
567 {
568 /*
569 * Either the new credentials are not newly issued, or the common name
570 * does not match the issued certificate...
571 */
572
524c65e6 573 trust = HTTP_TRUST_INVALID;
376d7c69 574 }
524c65e6 575 else if (httpCredentialsGetExpiration(tcreds) < time(NULL))
376d7c69
MS
576 {
577 /*
524c65e6 578 * Save the renewed credentials...
376d7c69
MS
579 */
580
524c65e6
MS
581 trust = HTTP_TRUST_RENEWED;
582
583 httpSaveCredentials(NULL, credentials, common_name);
376d7c69
MS
584 }
585 }
586
587 httpFreeCredentials(tcreds);
588 }
f51f3773 589 else if (cg->validate_certs && !httpCredentialsAreValidForName(credentials, common_name))
524c65e6 590 trust = HTTP_TRUST_INVALID;
376d7c69 591
9653cfdf 592 if (!cg->expired_certs && !SecCertificateIsValid(secCert, CFAbsoluteTimeGetCurrent()))
524c65e6 593 trust = HTTP_TRUST_EXPIRED;
25731360 594 else if (!cg->any_root && cupsArrayCount(credentials) == 1)
524c65e6 595 trust = HTTP_TRUST_INVALID;
376d7c69 596
9653cfdf
MS
597 CFRelease(secCert);
598
524c65e6 599 return (trust);
3af9ac9e
MS
600}
601
602
603/*
604 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
605 *
e1f19878 606 * @since CUPS 2.0/OS X 10.10@
3af9ac9e
MS
607 */
608
609time_t /* O - Expiration date of credentials */
610httpCredentialsGetExpiration(
611 cups_array_t *credentials) /* I - Credentials */
612{
9653cfdf
MS
613 SecCertificateRef secCert; /* Certificate reference */
614 time_t expiration; /* Expiration date */
3af9ac9e 615
9653cfdf
MS
616
617 if ((secCert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
618 return (0);
619
376d7c69 620 expiration = (time_t)(SecCertificateNotValidAfter(secCert) + kCFAbsoluteTimeIntervalSince1970);
9653cfdf
MS
621
622 CFRelease(secCert);
623
624 return (expiration);
3af9ac9e
MS
625}
626
627
72d05bc9
MS
628/*
629 * 'httpCredentialsString()' - Return a string representing the credentials.
630 *
e1f19878 631 * @since CUPS 2.0/OS X 10.10@
72d05bc9
MS
632 */
633
634size_t /* O - Total size of credentials string */
635httpCredentialsString(
636 cups_array_t *credentials, /* I - Credentials */
637 char *buffer, /* I - Buffer or @code NULL@ */
638 size_t bufsize) /* I - Size of buffer */
639{
376d7c69 640 http_credential_t *first; /* First certificate */
9653cfdf 641 SecCertificateRef secCert; /* Certificate reference */
9653cfdf
MS
642
643
376d7c69
MS
644 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT ")", credentials, buffer, CUPS_LLCAST bufsize));
645
9653cfdf
MS
646 if (!buffer)
647 return (0);
72d05bc9
MS
648
649 if (buffer && bufsize > 0)
650 *buffer = '\0';
651
376d7c69
MS
652 if ((first = (http_credential_t *)cupsArrayFirst(credentials)) != NULL &&
653 (secCert = http_cdsa_create_credential(first)) != NULL)
9653cfdf 654 {
376d7c69
MS
655 CFStringRef cf_name; /* CF common name string */
656 char name[256]; /* Common name associated with cert */
657 time_t expiration; /* Expiration date of cert */
658 _cups_md5_state_t md5_state; /* MD5 state */
659 unsigned char md5_digest[16]; /* MD5 result */
660
661 if ((cf_name = SecCertificateCopySubjectSummary(secCert)) != NULL)
9653cfdf 662 {
376d7c69
MS
663 CFStringGetCString(cf_name, name, (CFIndex)sizeof(name), kCFStringEncodingUTF8);
664 CFRelease(cf_name);
9653cfdf 665 }
376d7c69
MS
666 else
667 strlcpy(name, "unknown", sizeof(name));
668
669 expiration = (time_t)(SecCertificateNotValidAfter(secCert) + kCFAbsoluteTimeIntervalSince1970);
670
671 _cupsMD5Init(&md5_state);
672 _cupsMD5Append(&md5_state, first->data, (int)first->datalen);
673 _cupsMD5Finish(&md5_state, md5_digest);
674
675 snprintf(buffer, bufsize, "%s / %s / %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", name, httpGetDateString(expiration), md5_digest[0], md5_digest[1], md5_digest[2], md5_digest[3], md5_digest[4], md5_digest[5], md5_digest[6], md5_digest[7], md5_digest[8], md5_digest[9], md5_digest[10], md5_digest[11], md5_digest[12], md5_digest[13], md5_digest[14], md5_digest[15]);
9653cfdf
MS
676
677 CFRelease(secCert);
678 }
679
376d7c69
MS
680 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer));
681
9653cfdf 682 return (strlen(buffer));
72d05bc9
MS
683}
684
685
2c85b752
MS
686/*
687 * '_httpFreeCredentials()' - Free internal credentials.
688 */
689
690void
691_httpFreeCredentials(
692 http_tls_credentials_t credentials) /* I - Internal credentials */
693{
694 if (!credentials)
695 return;
696
697 CFRelease(credentials);
698}
699
700
72d05bc9
MS
701/*
702 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
703 *
e1f19878 704 * @since CUPS 2.0/OS 10.10@
72d05bc9
MS
705 */
706
dafebafd 707int /* O - 0 on success, -1 on error */
72d05bc9 708httpLoadCredentials(
f93b32b6 709 const char *path, /* I - Keychain path or @code NULL@ for default */
72d05bc9
MS
710 cups_array_t **credentials, /* IO - Credentials */
711 const char *common_name) /* I - Common name for credentials */
712{
88f1e9c8 713#ifdef HAVE_SECKEYCHAINOPEN
dafebafd 714 OSStatus err; /* Error info */
88f1e9c8 715 char filename[1024]; /* Filename for keychain */
dafebafd
MS
716 SecKeychainRef keychain = NULL;/* Keychain reference */
717 SecIdentitySearchRef search = NULL; /* Search reference */
88f1e9c8
MS
718 SecCertificateRef cert = NULL; /* Certificate */
719 CFDataRef data; /* Certificate data */
dafebafd
MS
720 SecPolicyRef policy = NULL; /* Policy ref */
721 CFStringRef cfcommon_name = NULL;
722 /* Server name */
723 CFMutableDictionaryRef query = NULL; /* Query qualifiers */
724 CFArrayRef list = NULL; /* Keychain list */
725
726
88f1e9c8
MS
727 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, credentials, common_name));
728
729 if (!credentials)
730 return (-1);
731
732 *credentials = NULL;
733
734 if (!path)
005f7f1f 735 path = http_cdsa_default_path(filename, sizeof(filename));
88f1e9c8 736
88f1e9c8 737 if ((err = SecKeychainOpen(path, &keychain)) != noErr)
dafebafd
MS
738 goto cleanup;
739
740 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
741
742 policy = SecPolicyCreateSSL(1, cfcommon_name);
743
744 if (cfcommon_name)
745 CFRelease(cfcommon_name);
746
747 if (!policy)
748 goto cleanup;
749
750 if (!(query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)))
751 goto cleanup;
752
88f1e9c8 753 list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks);
dafebafd 754
88f1e9c8 755 CFDictionaryAddValue(query, kSecClass, kSecClassCertificate);
dafebafd
MS
756 CFDictionaryAddValue(query, kSecMatchPolicy, policy);
757 CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
758 CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
759 CFDictionaryAddValue(query, kSecMatchSearchList, list);
760
761 CFRelease(list);
762
88f1e9c8 763 err = SecItemCopyMatching(query, (CFTypeRef *)&cert);
dafebafd
MS
764
765 if (err)
766 goto cleanup;
767
88f1e9c8 768 if (CFGetTypeID(cert) != SecCertificateGetTypeID())
dafebafd
MS
769 goto cleanup;
770
88f1e9c8
MS
771 if ((data = SecCertificateCopyData(cert)) != NULL)
772 {
773 DEBUG_printf(("1httpLoadCredentials: Adding %d byte certificate blob.", (int)CFDataGetLength(data)));
774
775 *credentials = cupsArrayNew(NULL, NULL);
776 httpAddCredential(*credentials, CFDataGetBytePtr(data), (size_t)CFDataGetLength(data));
777 CFRelease(data);
778 }
dafebafd
MS
779
780 cleanup :
781
782 if (keychain)
783 CFRelease(keychain);
784 if (search)
785 CFRelease(search);
88f1e9c8
MS
786 if (cert)
787 CFRelease(cert);
dafebafd
MS
788 if (policy)
789 CFRelease(policy);
790 if (query)
791 CFRelease(query);
792
88f1e9c8
MS
793 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials ? 0 : -1));
794
795 return (*credentials ? 0 : -1);
796
797#else
798 (void)path;
799 (void)credentials;
800 (void)common_name;
801
802 return (-1);
803#endif /* HAVE_SECKEYCHAINOPEN */
72d05bc9
MS
804}
805
806
72d05bc9
MS
807/*
808 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
809 *
e1f19878 810 * @since CUPS 2.0/OS 10.10@
72d05bc9
MS
811 */
812
813int /* O - -1 on error, 0 on success */
814httpSaveCredentials(
f93b32b6 815 const char *path, /* I - Keychain path or @code NULL@ for default */
72d05bc9
MS
816 cups_array_t *credentials, /* I - Credentials */
817 const char *common_name) /* I - Common name for credentials */
818{
eb66bc71 819#ifdef HAVE_SECKEYCHAINOPEN
88f1e9c8 820 int ret = -1; /* Return value */
41e0907c 821 OSStatus err; /* Error info */
88f1e9c8
MS
822 char filename[1024]; /* Filename for keychain */
823 SecKeychainRef keychain = NULL;/* Keychain reference */
41e0907c 824 SecIdentitySearchRef search = NULL; /* Search reference */
88f1e9c8 825 SecCertificateRef cert = NULL; /* Certificate */
88f1e9c8 826 CFMutableDictionaryRef attrs = NULL; /* Attributes for add */
41e0907c
MS
827 CFArrayRef list = NULL; /* Keychain list */
828
829
88f1e9c8
MS
830 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, credentials, common_name));
831 if (!credentials)
41e0907c
MS
832 goto cleanup;
833
524c65e6
MS
834 if (!httpCredentialsAreValidForName(credentials, common_name))
835 {
836 DEBUG_puts("1httpSaveCredentials: Common name does not match.");
837 return (-1);
838 }
839
88f1e9c8
MS
840 if ((cert = http_cdsa_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
841 {
842 DEBUG_puts("1httpSaveCredentials: Unable to create certificate.");
41e0907c 843 goto cleanup;
88f1e9c8 844 }
41e0907c 845
88f1e9c8 846 if (!path)
005f7f1f 847 path = http_cdsa_default_path(filename, sizeof(filename));
2c85b752 848
88f1e9c8 849 if ((err = SecKeychainOpen(path, &keychain)) != noErr)
2c85b752 850 {
88f1e9c8
MS
851 DEBUG_printf(("1httpSaveCredentials: SecKeychainOpen returned %d.", (int)err));
852 goto cleanup;
2c85b752 853 }
2c85b752 854
88f1e9c8 855 if ((list = CFArrayCreate(kCFAllocatorDefault, (const void **)&keychain, 1, &kCFTypeArrayCallBacks)) == NULL)
2c85b752 856 {
88f1e9c8
MS
857 DEBUG_puts("1httpSaveCredentials: Unable to create list of keychains.");
858 goto cleanup;
2c85b752 859 }
88f1e9c8 860
88f1e9c8
MS
861 if ((attrs = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)) == NULL)
862 {
863 DEBUG_puts("1httpSaveCredentials: Unable to create dictionary.");
864 goto cleanup;
2c85b752
MS
865 }
866
88f1e9c8 867 CFDictionaryAddValue(attrs, kSecClass, kSecClassCertificate);
88f1e9c8
MS
868 CFDictionaryAddValue(attrs, kSecValueRef, cert);
869 CFDictionaryAddValue(attrs, kSecMatchSearchList, list);
2c85b752 870
88f1e9c8 871 /* Note: SecItemAdd consumes "attrs"... */
524c65e6 872 err = SecItemAdd(attrs, NULL);
88f1e9c8 873 DEBUG_printf(("1httpSaveCredentials: SecItemAdd returned %d.", (int)err));
2c85b752 874
88f1e9c8 875 cleanup :
2c85b752 876
88f1e9c8
MS
877 if (list)
878 CFRelease(list);
879 if (keychain)
880 CFRelease(keychain);
881 if (search)
882 CFRelease(search);
883 if (cert)
884 CFRelease(cert);
2c85b752 885
88f1e9c8 886 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret));
2c85b752 887
88f1e9c8 888 return (ret);
2c85b752 889
88f1e9c8
MS
890#else
891 (void)path;
892 (void)credentials;
893 (void)common_name;
2c85b752 894
88f1e9c8
MS
895 return (-1);
896#endif /* HAVE_SECKEYCHAINOPEN */
2c85b752
MS
897}
898
899
900/*
25731360 901 * '_httpTLSInitialize()' - Initialize the TLS stack.
2c85b752
MS
902 */
903
25731360
MS
904void
905_httpTLSInitialize(void)
2c85b752
MS
906{
907 /*
908 * Nothing to do...
909 */
910}
911
912
913/*
25731360 914 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
2c85b752
MS
915 */
916
25731360
MS
917size_t
918_httpTLSPending(http_t *http) /* I - HTTP connection */
2c85b752
MS
919{
920 size_t bytes; /* Bytes that are available */
921
922
923 if (!SSLGetBufferedReadSize(http->tls, &bytes))
924 return (bytes);
925
926 return (0);
927}
928
929
930/*
25731360 931 * '_httpTLSRead()' - Read from a SSL/TLS connection.
2c85b752
MS
932 */
933
25731360
MS
934int /* O - Bytes read */
935_httpTLSRead(http_t *http, /* I - HTTP connection */
2c85b752
MS
936 char *buf, /* I - Buffer to store data */
937 int len) /* I - Length of buffer */
938{
939 int result; /* Return value */
940 OSStatus error; /* Error info */
941 size_t processed; /* Number of bytes processed */
942
943
7e86f2f6 944 error = SSLRead(http->tls, buf, (size_t)len, &processed);
25731360 945 DEBUG_printf(("6_httpTLSRead: error=%d, processed=%d", (int)error,
2c85b752
MS
946 (int)processed));
947 switch (error)
948 {
949 case 0 :
950 result = (int)processed;
951 break;
952
953 case errSSLWouldBlock :
954 if (processed)
955 result = (int)processed;
956 else
957 {
958 result = -1;
959 errno = EINTR;
960 }
961 break;
962
963 case errSSLClosedGraceful :
964 default :
965 if (processed)
966 result = (int)processed;
967 else
968 {
969 result = -1;
970 errno = EPIPE;
971 }
972 break;
973 }
974
975 return (result);
976}
977
978
63aefcd5
MS
979/*
980 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
981 */
982
983void
984_httpTLSSetOptions(int options) /* I - Options */
985{
986 tls_options = options;
987}
988
989
2c85b752 990/*
25731360 991 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
2c85b752
MS
992 */
993
25731360
MS
994int /* O - 0 on success, -1 on failure */
995_httpTLSStart(http_t *http) /* I - HTTP connection */
2c85b752
MS
996{
997 char hostname[256], /* Hostname */
998 *hostptr; /* Pointer into hostname */
999 _cups_globals_t *cg = _cupsGlobals();
1000 /* Pointer to library globals */
1001 OSStatus error; /* Error code */
1002 const char *message = NULL;/* Error message */
1003 cups_array_t *credentials; /* Credentials array */
1004 cups_array_t *names; /* CUPS distinguished names */
1005 CFArrayRef dn_array; /* CF distinguished names array */
1006 CFIndex count; /* Number of credentials */
1007 CFDataRef data; /* Certificate data */
1008 int i; /* Looping var */
1009 http_credential_t *credential; /* Credential data */
1010
1011
25731360 1012 DEBUG_printf(("7_httpTLSStart(http=%p)", http));
2c85b752 1013
c913d726 1014#ifdef HAVE_SECKEYCHAINOPEN
41e0907c 1015 if (http->mode == _HTTP_MODE_SERVER && !tls_keychain)
c913d726
MS
1016#else
1017 if (http->mode == _HTTP_MODE_SERVER)
1018#endif /* HAVE_SECKEYCHAINOPEN */
2c85b752 1019 {
25731360 1020 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
41e0907c
MS
1021 http->error = errno = EINVAL;
1022 http->status = HTTP_STATUS_ERROR;
1023 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Server credentials not set."), 1);
2c85b752 1024
41e0907c 1025 return (-1);
2c85b752
MS
1026 }
1027
72d05bc9 1028 if ((http->tls = SSLCreateContext(kCFAllocatorDefault, http->mode == _HTTP_MODE_CLIENT ? kSSLClientSide : kSSLServerSide, kSSLStreamType)) == NULL)
2c85b752 1029 {
25731360 1030 DEBUG_puts("4_httpTLSStart: SSLCreateContext failed.");
2c85b752
MS
1031 http->error = errno = ENOMEM;
1032 http->status = HTTP_STATUS_ERROR;
1033 _cupsSetHTTPError(HTTP_STATUS_ERROR);
1034
1035 return (-1);
1036 }
1037
1038 error = SSLSetConnection(http->tls, http);
25731360 1039 DEBUG_printf(("4_httpTLSStart: SSLSetConnection, error=%d", (int)error));
2c85b752
MS
1040
1041 if (!error)
1042 {
1043 error = SSLSetIOFuncs(http->tls, http_cdsa_read, http_cdsa_write);
25731360 1044 DEBUG_printf(("4_httpTLSStart: SSLSetIOFuncs, error=%d", (int)error));
2c85b752
MS
1045 }
1046
1047 if (!error)
1048 {
1049 error = SSLSetSessionOption(http->tls, kSSLSessionOptionBreakOnServerAuth,
1050 true);
63aefcd5
MS
1051 DEBUG_printf(("4_httpTLSStart: SSLSetSessionOption, error=%d", (int)error));
1052 }
1053
1054 if (!error)
1055 {
ee6226a5
MS
1056 SSLProtocol minProtocol;
1057
1058 if (tls_options & _HTTP_TLS_DENY_TLS10)
1059 minProtocol = kTLSProtocol11;
1060 else if (tls_options & _HTTP_TLS_ALLOW_SSL3)
1061 minProtocol = kSSLProtocol3;
1062 else
1063 minProtocol = kTLSProtocol1;
1064
1065 error = SSLSetProtocolVersionMin(http->tls, minProtocol);
1066 DEBUG_printf(("4_httpTLSStart: SSLSetProtocolVersionMin(%d), error=%d", minProtocol, (int)error));
63aefcd5
MS
1067 }
1068
ee6226a5 1069# if HAVE_SSLSETENABLEDCIPHERS
63aefcd5
MS
1070 if (!error)
1071 {
1072 SSLCipherSuite supported[100]; /* Supported cipher suites */
1073 size_t num_supported; /* Number of supported cipher suites */
1074 SSLCipherSuite enabled[100]; /* Cipher suites to enable */
1075 size_t num_enabled; /* Number of cipher suites to enable */
1076
1077 num_supported = sizeof(supported) / sizeof(supported[0]);
1078 error = SSLGetSupportedCiphers(http->tls, supported, &num_supported);
1079
1080 if (!error)
1081 {
1082 DEBUG_printf(("4_httpTLSStart: %d cipher suites supported.", (int)num_supported));
1083
1084 for (i = 0, num_enabled = 0; i < (int)num_supported && num_enabled < (sizeof(enabled) / sizeof(enabled[0])); i ++)
1085 {
1086 switch (supported[i])
1087 {
1088 /* Obviously insecure cipher suites that we never want to use */
1089 case SSL_NULL_WITH_NULL_NULL :
1090 case SSL_RSA_WITH_NULL_MD5 :
1091 case SSL_RSA_WITH_NULL_SHA :
1092 case SSL_RSA_EXPORT_WITH_RC4_40_MD5 :
1093 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5 :
1094 case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA :
1095 case SSL_RSA_WITH_DES_CBC_SHA :
1096 case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA :
1097 case SSL_DH_DSS_WITH_DES_CBC_SHA :
1098 case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA :
1099 case SSL_DH_RSA_WITH_DES_CBC_SHA :
1100 case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA :
1101 case SSL_DHE_DSS_WITH_DES_CBC_SHA :
1102 case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA :
1103 case SSL_DHE_RSA_WITH_DES_CBC_SHA :
1104 case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 :
1105 case SSL_DH_anon_WITH_RC4_128_MD5 :
1106 case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA :
1107 case SSL_DH_anon_WITH_DES_CBC_SHA :
1108 case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA :
1109 case SSL_FORTEZZA_DMS_WITH_NULL_SHA :
1110 case TLS_DH_anon_WITH_AES_128_CBC_SHA :
1111 case TLS_DH_anon_WITH_AES_256_CBC_SHA :
1112 case TLS_ECDH_ECDSA_WITH_NULL_SHA :
1113 case TLS_ECDHE_RSA_WITH_NULL_SHA :
1114 case TLS_ECDH_anon_WITH_NULL_SHA :
1115 case TLS_ECDH_anon_WITH_RC4_128_SHA :
1116 case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA :
1117 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA :
1118 case TLS_ECDH_anon_WITH_AES_256_CBC_SHA :
1119 case TLS_RSA_WITH_NULL_SHA256 :
1120 case TLS_DH_anon_WITH_AES_128_CBC_SHA256 :
1121 case TLS_DH_anon_WITH_AES_256_CBC_SHA256 :
1122 case TLS_PSK_WITH_NULL_SHA :
1123 case TLS_DHE_PSK_WITH_NULL_SHA :
1124 case TLS_RSA_PSK_WITH_NULL_SHA :
1125 case TLS_DH_anon_WITH_AES_128_GCM_SHA256 :
1126 case TLS_DH_anon_WITH_AES_256_GCM_SHA384 :
1127 case TLS_PSK_WITH_NULL_SHA256 :
1128 case TLS_PSK_WITH_NULL_SHA384 :
1129 case TLS_DHE_PSK_WITH_NULL_SHA256 :
1130 case TLS_DHE_PSK_WITH_NULL_SHA384 :
1131 case TLS_RSA_PSK_WITH_NULL_SHA256 :
1132 case TLS_RSA_PSK_WITH_NULL_SHA384 :
1133 case SSL_RSA_WITH_DES_CBC_MD5 :
1134 break;
1135
1136 /* RC4 cipher suites that should only be used as a last resort */
1137 case SSL_RSA_WITH_RC4_128_MD5 :
1138 case SSL_RSA_WITH_RC4_128_SHA :
1139 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA :
1140 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA :
1141 case TLS_ECDH_RSA_WITH_RC4_128_SHA :
1142 case TLS_ECDHE_RSA_WITH_RC4_128_SHA :
1143 case TLS_PSK_WITH_RC4_128_SHA :
1144 case TLS_DHE_PSK_WITH_RC4_128_SHA :
1145 case TLS_RSA_PSK_WITH_RC4_128_SHA :
1146 if (tls_options & _HTTP_TLS_ALLOW_RC4)
1147 enabled[num_enabled ++] = supported[i];
1148 break;
1149
ee6226a5
MS
1150 /* DH/DHE cipher suites that are problematic with parameters < 1024 bits */
1151 case TLS_DH_DSS_WITH_AES_128_CBC_SHA :
1152 case TLS_DH_RSA_WITH_AES_128_CBC_SHA :
1153 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA :
1154 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA :
1155 case TLS_DH_DSS_WITH_AES_256_CBC_SHA :
1156 case TLS_DH_RSA_WITH_AES_256_CBC_SHA :
1157 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA :
1158 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA :
1159 case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA :
1160 case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA :
1161 case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA :
1162 case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA :
1163 case TLS_DH_DSS_WITH_AES_128_CBC_SHA256 :
1164 case TLS_DH_RSA_WITH_AES_128_CBC_SHA256 :
1165 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 :
1166 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 :
1167 case TLS_DH_DSS_WITH_AES_256_CBC_SHA256 :
1168 case TLS_DH_RSA_WITH_AES_256_CBC_SHA256 :
1169 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 :
1170 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 :
1171 case TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA :
1172 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA :
1173 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA :
1174 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
1175 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
1176 case TLS_DH_RSA_WITH_AES_128_GCM_SHA256 :
1177 case TLS_DH_RSA_WITH_AES_256_GCM_SHA384 :
1178 case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 :
1179 case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 :
1180 case TLS_DH_DSS_WITH_AES_128_GCM_SHA256 :
1181 case TLS_DH_DSS_WITH_AES_256_GCM_SHA384 :
1182 case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 :
1183 case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 :
1184 case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 :
1185 case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 :
1186 if (tls_options & _HTTP_TLS_ALLOW_DH)
1187 enabled[num_enabled ++] = supported[i];
1188 break;
1189
63aefcd5
MS
1190 /* Anything else we'll assume is secure */
1191 default :
1192 enabled[num_enabled ++] = supported[i];
1193 break;
1194 }
1195 }
1196
1197 DEBUG_printf(("4_httpTLSStart: %d cipher suites enabled.", (int)num_enabled));
1198 error = SSLSetEnabledCiphers(http->tls, enabled, num_enabled);
1199 }
2c85b752 1200 }
ee6226a5 1201#endif /* HAVE_SSLSETENABLEDCIPHERS */
2c85b752 1202
41e0907c 1203 if (!error && http->mode == _HTTP_MODE_CLIENT)
2c85b752 1204 {
41e0907c
MS
1205 /*
1206 * Client: set client-side credentials, if any...
1207 */
1208
2c85b752
MS
1209 if (cg->client_cert_cb)
1210 {
1211 error = SSLSetSessionOption(http->tls,
1212 kSSLSessionOptionBreakOnCertRequested, true);
25731360 1213 DEBUG_printf(("4_httpTLSStart: kSSLSessionOptionBreakOnCertRequested, "
2c85b752
MS
1214 "error=%d", (int)error));
1215 }
1216 else
1217 {
88f1e9c8
MS
1218 error = http_cdsa_set_credentials(http);
1219 DEBUG_printf(("4_httpTLSStart: http_cdsa_set_credentials, error=%d",
2c85b752
MS
1220 (int)error));
1221 }
1222 }
41e0907c
MS
1223 else if (!error)
1224 {
1225 /*
1226 * Server: find/create a certificate for TLS...
1227 */
1228
1229 if (http->fields[HTTP_FIELD_HOST][0])
1230 {
1231 /*
1232 * Use hostname for TLS upgrade...
1233 */
1234
1235 strlcpy(hostname, http->fields[HTTP_FIELD_HOST], sizeof(hostname));
1236 }
1237 else
1238 {
1239 /*
1240 * Resolve hostname from connection address...
1241 */
1242
1243 http_addr_t addr; /* Connection address */
1244 socklen_t addrlen; /* Length of address */
1245
1246 addrlen = sizeof(addr);
1247 if (getsockname(http->fd, (struct sockaddr *)&addr, &addrlen))
1248 {
25731360 1249 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno)));
41e0907c
MS
1250 hostname[0] = '\0';
1251 }
1252 else if (httpAddrLocalhost(&addr))
1253 hostname[0] = '\0';
1254 else
a27a134a
MS
1255 {
1256 httpAddrLookup(&addr, hostname, sizeof(hostname));
25731360 1257 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname));
a27a134a 1258 }
41e0907c
MS
1259 }
1260
eb66bc71 1261#ifdef HAVE_SECKEYCHAINOPEN
a27a134a
MS
1262 if (isdigit(hostname[0] & 255) || hostname[0] == '[')
1263 hostname[0] = '\0'; /* Don't allow numeric addresses */
1264
41e0907c
MS
1265 if (hostname[0])
1266 http->tls_credentials = http_cdsa_copy_server(hostname);
1267 else if (tls_common_name)
1268 http->tls_credentials = http_cdsa_copy_server(tls_common_name);
1269
1270 if (!http->tls_credentials && tls_auto_create && (hostname[0] || tls_common_name))
1271 {
25731360 1272 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname[0] ? hostname : tls_common_name));
41e0907c
MS
1273
1274 if (!cupsMakeServerCredentials(tls_keypath, hostname[0] ? hostname : tls_common_name, 0, NULL, time(NULL) + 365 * 86400))
1275 {
25731360 1276 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
41e0907c
MS
1277 http->error = errno = EINVAL;
1278 http->status = HTTP_STATUS_ERROR;
1279 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create server credentials."), 1);
1280
1281 return (-1);
1282 }
1283
1284 http->tls_credentials = http_cdsa_copy_server(hostname[0] ? hostname : tls_common_name);
1285 }
eb66bc71 1286#endif /* HAVE_SECKEYCHAINOPEN */
41e0907c
MS
1287
1288 if (!http->tls_credentials)
1289 {
25731360 1290 DEBUG_puts("4_httpTLSStart: Unable to find server credentials.");
41e0907c
MS
1291 http->error = errno = EINVAL;
1292 http->status = HTTP_STATUS_ERROR;
1293 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to find server credentials."), 1);
1294
1295 return (-1);
1296 }
1297
1298 error = SSLSetCertificate(http->tls, http->tls_credentials);
1299
25731360 1300 DEBUG_printf(("4_httpTLSStart: SSLSetCertificate, error=%d", (int)error));
41e0907c
MS
1301 }
1302
25731360 1303 DEBUG_printf(("4_httpTLSStart: tls_credentials=%p", http->tls_credentials));
2c85b752
MS
1304
1305 /*
1306 * Let the server know which hostname/domain we are trying to connect to
1307 * in case it wants to serve up a certificate with a matching common name.
1308 */
1309
41e0907c 1310 if (!error && http->mode == _HTTP_MODE_CLIENT)
2c85b752 1311 {
41e0907c
MS
1312 /*
1313 * Client: get the hostname to use for TLS...
1314 */
1315
1316 if (httpAddrLocalhost(http->hostaddr))
1317 {
1318 strlcpy(hostname, "localhost", sizeof(hostname));
1319 }
1320 else
1321 {
1322 /*
1323 * Otherwise make sure the hostname we have does not end in a trailing dot.
1324 */
1325
1326 strlcpy(hostname, http->hostname, sizeof(hostname));
1327 if ((hostptr = hostname + strlen(hostname) - 1) >= hostname &&
1328 *hostptr == '.')
1329 *hostptr = '\0';
1330 }
1331
2c85b752
MS
1332 error = SSLSetPeerDomainName(http->tls, hostname, strlen(hostname));
1333
25731360 1334 DEBUG_printf(("4_httpTLSStart: SSLSetPeerDomainName, error=%d", (int)error));
2c85b752
MS
1335 }
1336
1337 if (!error)
1338 {
1339 int done = 0; /* Are we done yet? */
1340
1341 while (!error && !done)
1342 {
1343 error = SSLHandshake(http->tls);
1344
25731360 1345 DEBUG_printf(("4_httpTLSStart: SSLHandshake returned %d.", (int)error));
2c85b752
MS
1346
1347 switch (error)
1348 {
1349 case noErr :
1350 done = 1;
1351 break;
1352
1353 case errSSLWouldBlock :
1354 error = noErr; /* Force a retry */
1355 usleep(1000); /* in 1 millisecond */
1356 break;
1357
1358 case errSSLServerAuthCompleted :
1359 error = 0;
1360 if (cg->server_cert_cb)
1361 {
1362 error = httpCopyCredentials(http, &credentials);
1363 if (!error)
1364 {
1365 error = (cg->server_cert_cb)(http, http->tls, credentials,
1366 cg->server_cert_data);
1367 httpFreeCredentials(credentials);
1368 }
1369
25731360 1370 DEBUG_printf(("4_httpTLSStart: Server certificate callback "
2c85b752
MS
1371 "returned %d.", (int)error));
1372 }
1373 break;
1374
1375 case errSSLClientCertRequested :
1376 error = 0;
1377
1378 if (cg->client_cert_cb)
1379 {
1380 names = NULL;
1381 if (!(error = SSLCopyDistinguishedNames(http->tls, &dn_array)) &&
1382 dn_array)
1383 {
1384 if ((names = cupsArrayNew(NULL, NULL)) != NULL)
1385 {
1386 for (i = 0, count = CFArrayGetCount(dn_array); i < count; i++)
1387 {
1388 data = (CFDataRef)CFArrayGetValueAtIndex(dn_array, i);
1389
1390 if ((credential = malloc(sizeof(*credential))) != NULL)
1391 {
7e86f2f6 1392 credential->datalen = (size_t)CFDataGetLength(data);
2c85b752
MS
1393 if ((credential->data = malloc(credential->datalen)))
1394 {
1395 memcpy((void *)credential->data, CFDataGetBytePtr(data),
1396 credential->datalen);
1397 cupsArrayAdd(names, credential);
1398 }
1399 else
1400 free(credential);
1401 }
1402 }
1403 }
1404
1405 CFRelease(dn_array);
1406 }
1407
1408 if (!error)
1409 {
1410 error = (cg->client_cert_cb)(http, http->tls, names,
1411 cg->client_cert_data);
1412
25731360 1413 DEBUG_printf(("4_httpTLSStart: Client certificate callback "
2c85b752
MS
1414 "returned %d.", (int)error));
1415 }
1416
1417 httpFreeCredentials(names);
1418 }
1419 break;
1420
1421 case errSSLUnknownRootCert :
1422 message = _("Unable to establish a secure connection to host "
1423 "(untrusted certificate).");
1424 break;
1425
1426 case errSSLNoRootCert :
1427 message = _("Unable to establish a secure connection to host "
1428 "(self-signed certificate).");
1429 break;
1430
1431 case errSSLCertExpired :
1432 message = _("Unable to establish a secure connection to host "
1433 "(expired certificate).");
1434 break;
1435
1436 case errSSLCertNotYetValid :
1437 message = _("Unable to establish a secure connection to host "
1438 "(certificate not yet valid).");
1439 break;
1440
1441 case errSSLHostNameMismatch :
1442 message = _("Unable to establish a secure connection to host "
1443 "(host name mismatch).");
1444 break;
1445
1446 case errSSLXCertChainInvalid :
1447 message = _("Unable to establish a secure connection to host "
1448 "(certificate chain invalid).");
1449 break;
1450
1451 case errSSLConnectionRefused :
1452 message = _("Unable to establish a secure connection to host "
1453 "(peer dropped connection before responding).");
1454 break;
1455
1456 default :
1457 break;
1458 }
1459 }
1460 }
1461
1462 if (error)
1463 {
1464 http->error = error;
1465 http->status = HTTP_STATUS_ERROR;
1466 errno = ECONNREFUSED;
1467
1468 CFRelease(http->tls);
1469 http->tls = NULL;
1470
1471 /*
1472 * If an error string wasn't set by the callbacks use a generic one...
1473 */
1474
1475 if (!message)
1476#ifdef HAVE_CSSMERRORSTRING
1477 message = cssmErrorString(error);
1478#else
1479 message = _("Unable to establish a secure connection to host.");
1480#endif /* HAVE_CSSMERRORSTRING */
1481
1482 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, message, 1);
1483
1484 return (-1);
1485 }
1486
1487 return (0);
1488}
1489
1490
1491/*
25731360 1492 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
2c85b752
MS
1493 */
1494
25731360
MS
1495void
1496_httpTLSStop(http_t *http) /* I - HTTP connection */
2c85b752
MS
1497{
1498 while (SSLClose(http->tls) == errSSLWouldBlock)
1499 usleep(1000);
1500
1501 CFRelease(http->tls);
1502
1503 if (http->tls_credentials)
1504 CFRelease(http->tls_credentials);
1505
1506 http->tls = NULL;
1507 http->tls_credentials = NULL;
1508}
1509
1510
1511/*
25731360 1512 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
2c85b752
MS
1513 */
1514
25731360
MS
1515int /* O - Bytes written */
1516_httpTLSWrite(http_t *http, /* I - HTTP connection */
2c85b752
MS
1517 const char *buf, /* I - Buffer holding data */
1518 int len) /* I - Length of buffer */
1519{
1520 ssize_t result; /* Return value */
1521 OSStatus error; /* Error info */
1522 size_t processed; /* Number of bytes processed */
1523
1524
25731360 1525 DEBUG_printf(("2_httpTLSWrite(http=%p, buf=%p, len=%d)", http, buf, len));
2c85b752 1526
7e86f2f6 1527 error = SSLWrite(http->tls, buf, (size_t)len, &processed);
2c85b752
MS
1528
1529 switch (error)
1530 {
1531 case 0 :
1532 result = (int)processed;
1533 break;
1534
1535 case errSSLWouldBlock :
1536 if (processed)
1537 {
1538 result = (int)processed;
1539 }
1540 else
1541 {
1542 result = -1;
1543 errno = EINTR;
1544 }
1545 break;
1546
1547 case errSSLClosedGraceful :
1548 default :
1549 if (processed)
1550 {
1551 result = (int)processed;
1552 }
1553 else
1554 {
1555 result = -1;
1556 errno = EPIPE;
1557 }
1558 break;
1559 }
1560
25731360 1561 DEBUG_printf(("3_httpTLSWrite: Returning %d.", (int)result));
2c85b752
MS
1562
1563 return ((int)result);
1564}
1565
1566
88f1e9c8 1567#ifdef HAVE_SECKEYCHAINOPEN
2c85b752 1568/*
88f1e9c8 1569 * 'http_cdsa_copy_server()' - Find and copy server credentials from the keychain.
2c85b752
MS
1570 */
1571
88f1e9c8
MS
1572static CFArrayRef /* O - Array of certificates or NULL */
1573http_cdsa_copy_server(
1574 const char *common_name) /* I - Server's hostname */
2c85b752 1575{
88f1e9c8
MS
1576 OSStatus err; /* Error info */
1577 SecIdentitySearchRef search = NULL; /* Search reference */
1578 SecIdentityRef identity = NULL;/* Identity */
1579 CFArrayRef certificates = NULL;
1580 /* Certificate array */
1581 SecPolicyRef policy = NULL; /* Policy ref */
1582 CFStringRef cfcommon_name = NULL;
1583 /* Server name */
1584 CFMutableDictionaryRef query = NULL; /* Query qualifiers */
1585 CFArrayRef list = NULL; /* Keychain list */
2c85b752 1586
2c85b752 1587
88f1e9c8 1588 cfcommon_name = CFStringCreateWithCString(kCFAllocatorDefault, common_name, kCFStringEncodingUTF8);
2c85b752 1589
88f1e9c8
MS
1590 policy = SecPolicyCreateSSL(1, cfcommon_name);
1591
1592 if (cfcommon_name)
1593 CFRelease(cfcommon_name);
1594
1595 if (!policy)
1596 goto cleanup;
1597
1598 if (!(query = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)))
1599 goto cleanup;
1600
f93b32b6
MS
1601 _cupsMutexLock(&tls_mutex);
1602
88f1e9c8
MS
1603 list = CFArrayCreate(kCFAllocatorDefault, (const void **)&tls_keychain, 1, &kCFTypeArrayCallBacks);
1604
1605 CFDictionaryAddValue(query, kSecClass, kSecClassIdentity);
1606 CFDictionaryAddValue(query, kSecMatchPolicy, policy);
1607 CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
1608 CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
1609 CFDictionaryAddValue(query, kSecMatchSearchList, list);
1610
1611 CFRelease(list);
1612
1613 err = SecItemCopyMatching(query, (CFTypeRef *)&identity);
1614
f93b32b6
MS
1615 _cupsMutexUnlock(&tls_mutex);
1616
88f1e9c8
MS
1617 if (err)
1618 goto cleanup;
1619
1620 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
1621 goto cleanup;
1622
1623 if ((certificates = CFArrayCreate(NULL, (const void **)&identity, 1, &kCFTypeArrayCallBacks)) == NULL)
1624 goto cleanup;
1625
1626 cleanup :
1627
1628 if (search)
1629 CFRelease(search);
1630 if (identity)
1631 CFRelease(identity);
1632
1633 if (policy)
1634 CFRelease(policy);
1635 if (query)
1636 CFRelease(query);
1637
1638 return (certificates);
2c85b752 1639}
88f1e9c8 1640#endif /* HAVE_SECKEYCHAINOPEN */
2c85b752
MS
1641
1642
2ece34a9
MS
1643/*
1644 * 'http_cdsa_create_credential()' - Create a single credential in the internal format.
1645 */
1646
1647static SecCertificateRef /* O - Certificate */
1648http_cdsa_create_credential(
1649 http_credential_t *credential) /* I - Credential */
1650{
1651 if (!credential)
1652 return (NULL);
1653
1654 return (SecCertificateCreateWithBytes(kCFAllocatorDefault, credential->data, (CFIndex)credential->datalen));
1655}
1656
1657
005f7f1f
MS
1658/*
1659 * 'http_cdsa_default_path()' - Get the default keychain path.
1660 */
1661
1662static const char * /* O - Keychain path */
1663http_cdsa_default_path(char *buffer, /* I - Path buffer */
1664 size_t bufsize) /* I - Size of buffer */
1665{
1666 const char *home = getenv("HOME"); /* HOME environment variable */
1667
1668
1669 if (getuid() && home)
1670 snprintf(buffer, bufsize, "%s/Library/Keychains/login.keychain", home);
1671 else
1672 strlcpy(buffer, "/Library/Keychains/System.keychain", bufsize);
1673
1674 DEBUG_printf(("1http_cdsa_default_path: Using default path \"%s\".", buffer));
1675
1676 return (buffer);
1677}
1678
1679
2c85b752 1680/*
88f1e9c8 1681 * 'http_cdsa_read()' - Read function for the CDSA library.
2c85b752
MS
1682 */
1683
88f1e9c8
MS
1684static OSStatus /* O - -1 on error, 0 on success */
1685http_cdsa_read(
1686 SSLConnectionRef connection, /* I - SSL/TLS connection */
1687 void *data, /* I - Data buffer */
1688 size_t *dataLength) /* IO - Number of bytes */
2c85b752 1689{
88f1e9c8
MS
1690 OSStatus result; /* Return value */
1691 ssize_t bytes; /* Number of bytes read */
1692 http_t *http; /* HTTP connection */
2c85b752 1693
2c85b752 1694
88f1e9c8 1695 http = (http_t *)connection;
2c85b752 1696
88f1e9c8 1697 if (!http->blocking)
2c85b752
MS
1698 {
1699 /*
88f1e9c8 1700 * Make sure we have data before we read...
2c85b752
MS
1701 */
1702
88f1e9c8
MS
1703 while (!_httpWait(http, http->wait_value, 0))
1704 {
1705 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1706 continue;
1707
1708 http->error = ETIMEDOUT;
1709 return (-1);
1710 }
2c85b752
MS
1711 }
1712
88f1e9c8 1713 do
2c85b752 1714 {
88f1e9c8 1715 bytes = recv(http->fd, data, *dataLength, 0);
2c85b752 1716 }
88f1e9c8 1717 while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
2c85b752 1718
88f1e9c8
MS
1719 if ((size_t)bytes == *dataLength)
1720 {
1721 result = 0;
1722 }
1723 else if (bytes > 0)
1724 {
1725 *dataLength = (size_t)bytes;
1726 result = errSSLWouldBlock;
1727 }
1728 else
1729 {
1730 *dataLength = 0;
2c85b752 1731
88f1e9c8
MS
1732 if (bytes == 0)
1733 result = errSSLClosedGraceful;
1734 else if (errno == EAGAIN)
1735 result = errSSLWouldBlock;
1736 else
1737 result = errSSLClosedAbort;
1738 }
2c85b752 1739
88f1e9c8
MS
1740 return (result);
1741}
2c85b752 1742
2c85b752 1743
88f1e9c8
MS
1744/*
1745 * 'http_cdsa_set_credentials()' - Set the TLS credentials.
1746 */
2c85b752 1747
88f1e9c8
MS
1748static int /* O - Status of connection */
1749http_cdsa_set_credentials(http_t *http) /* I - HTTP connection */
1750{
1751 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
1752 OSStatus error = 0; /* Error code */
1753 http_tls_credentials_t credentials = NULL;
1754 /* TLS credentials */
2c85b752 1755
2c85b752 1756
88f1e9c8 1757 DEBUG_printf(("7http_tls_set_credentials(%p)", http));
2c85b752 1758
88f1e9c8
MS
1759 /*
1760 * Prefer connection specific credentials...
1761 */
2c85b752 1762
88f1e9c8
MS
1763 if ((credentials = http->tls_credentials) == NULL)
1764 credentials = cg->tls_credentials;
2c85b752 1765
88f1e9c8
MS
1766 if (credentials)
1767 {
1768 error = SSLSetCertificate(http->tls, credentials);
1769 DEBUG_printf(("4http_tls_set_credentials: SSLSetCertificate, error=%d",
1770 (int)error));
2c85b752 1771 }
88f1e9c8
MS
1772 else
1773 DEBUG_puts("4http_tls_set_credentials: No credentials to set.");
1774
1775 return (error);
1776}
1777
1778
1779/*
1780 * 'http_cdsa_write()' - Write function for the CDSA library.
1781 */
1782
1783static OSStatus /* O - -1 on error, 0 on success */
1784http_cdsa_write(
1785 SSLConnectionRef connection, /* I - SSL/TLS connection */
1786 const void *data, /* I - Data buffer */
1787 size_t *dataLength) /* IO - Number of bytes */
1788{
1789 OSStatus result; /* Return value */
1790 ssize_t bytes; /* Number of bytes read */
1791 http_t *http; /* HTTP connection */
2c85b752 1792
2c85b752 1793
88f1e9c8
MS
1794 http = (http_t *)connection;
1795
1796 do
2c85b752 1797 {
88f1e9c8
MS
1798 bytes = write(http->fd, data, *dataLength);
1799 }
1800 while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
1801
1802 if ((size_t)bytes == *dataLength)
1803 {
1804 result = 0;
1805 }
1806 else if (bytes >= 0)
1807 {
1808 *dataLength = (size_t)bytes;
1809 result = errSSLWouldBlock;
2c85b752
MS
1810 }
1811 else
88f1e9c8
MS
1812 {
1813 *dataLength = 0;
2c85b752 1814
88f1e9c8
MS
1815 if (errno == EAGAIN)
1816 result = errSSLWouldBlock;
1817 else
1818 result = errSSLClosedAbort;
1819 }
1820
1821 return (result);
2c85b752 1822}
2c85b752
MS
1823
1824
1825/*
1826 * End of "$Id$".
1827 */