<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[114814] trunk/dports/security/certsync/files/certsync-tiger.m</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="https://trac.macports.org/changeset/114814">114814</a></dd>
<dt>Author</dt> <dd>landonf@macports.org</dd>
<dt>Date</dt> <dd>2013-12-15 21:46:29 -0800 (Sun, 15 Dec 2013)</dd>
</dl>

<h3>Log Message</h3>
<pre>Partial implementation of certsync for Tiger.</pre>

<h3>Added Paths</h3>
<ul>
<li><a href="#trunkdportssecuritycertsyncfilescertsynctigerm">trunk/dports/security/certsync/files/certsync-tiger.m</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunkdportssecuritycertsyncfilescertsynctigerm"></a>
<div class="addfile"><h4>Added: trunk/dports/security/certsync/files/certsync-tiger.m (0 => 114814)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/dports/security/certsync/files/certsync-tiger.m                                (rev 0)
+++ trunk/dports/security/certsync/files/certsync-tiger.m        2013-12-16 05:46:29 UTC (rev 114814)
</span><span class="lines">@@ -0,0 +1,357 @@
</span><ins>+/*
+ * Author: Landon Fuller &lt;landonf@plausiblelabs.com&gt;
+ * Copyright (c) 2008-2013 Plausible Labs Cooperative, Inc.
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the &quot;Software&quot;), to deal in the Software without
+ * restriction, including without limitation the rights to use,
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following
+ * conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#import &lt;Foundation/Foundation.h&gt;
+#import &lt;Security/Security.h&gt;
+#import &lt;AvailabilityMacros.h&gt;
+
+#import &lt;unistd.h&gt;
+#import &lt;stdio.h&gt;
+
+/* A wrapper class that may be used to pass configuration through the
+ * FSEvent callback API */
+@interface MPCertSyncConfig : NSObject {
+@public
+    BOOL userAnchors;
+    NSString *outputFile;
+}
+@end
+
+@implementation MPCertSyncConfig
+- (void) dealloc {
+    [outputFile release];
+    [super dealloc];
+}
+@end
+
+/**
+ * Add CoreFoundation object to the current autorelease pool.
+ *
+ * @param cfObj Object to add to the current autorelease pool.
+ */
+CFTypeRef PLCFAutorelease (CFTypeRef cfObj) {
+    return [(id)cfObj autorelease];
+}
+
+int nsvfprintf (FILE *stream, NSString *format, va_list args) {
+    int retval;
+    
+    NSString *str;
+    str = (NSString *) CFStringCreateWithFormatAndArguments(NULL, NULL, (CFStringRef) format, args);
+    retval = fprintf(stream, &quot;%s&quot;, [str UTF8String]);
+    [str release];
+    
+    return retval;
+}
+
+int nsfprintf (FILE *stream, NSString *format, ...) {
+    va_list ap;
+    int retval;
+    
+    va_start(ap, format);
+    {
+        retval = nsvfprintf(stream, format, ap);
+    }
+    va_end(ap);
+    
+    return retval;
+}
+
+int nsprintf (NSString *format, ...) {
+    va_list ap;
+    int retval;
+    
+    va_start(ap, format);
+    {
+        retval = nsvfprintf(stderr, format, ap);
+    }
+    va_end(ap);
+    
+    return retval;
+}
+
+/**
+ * Fetch all trusted roots.
+ *
+ * @param outError On error, will contain an NSError instance describing the failure.
+ *
+ * @return Returns a (possibly empty) array of certificates on success, nil on failure.
+ */
+static NSArray *certificatesForTrustDomain (NSError **outError) {
+    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+    CFArrayRef certs = nil;
+    OSStatus err;
+    
+    /* Fetch all certificates in the given domain */
+    err = SecTrustCopyAnchorCertificates(&amp;certs);
+    if (err == noErr) {
+        PLCFAutorelease(certs);
+    } else if (err == errSecTrustNotAvailable) {
+        /* No data */
+        [pool release];
+        return [NSArray array];
+    } else if (err != noErr) {
+        /* Lookup failed */
+        if (outError != NULL)
+            *outError = [[NSError errorWithDomain: NSOSStatusErrorDomain code: err userInfo:nil] retain];
+        
+        [pool release];
+        [*outError autorelease];
+        return nil;
+    }
+    
+    /* Extract trusted roots */
+    NSMutableArray *results = [NSMutableArray arrayWithCapacity: CFArrayGetCount(certs)];
+    NSEnumerator *resultEnumerator = [(NSArray *)certs objectEnumerator];
+    id certObj;
+    while ((certObj = [resultEnumerator nextObject]) != nil) {
+        [results addObject: certObj];
+    }
+
+    [results retain];
+    [pool release];
+    return [results autorelease];
+}
+
+BOOL compare_oids (const CSSM_OID *oid1, const CSSM_OID *oid2) {
+    if (oid1 == NULL || oid2 == NULL)
+        return NO;
+
+    if (oid1-&gt;Length != oid2-&gt;Length)
+        return NO;
+
+    if (memcmp(oid1-&gt;Data, oid2-&gt;Data, oid1-&gt;Length) == 0)
+        return YES;
+
+    return NO;
+}
+
+static NSString *getCommonName (const CSSM_X509_NAME *x509Name) {
+    uint32 rdn_idx;
+    uint32 pair_idx;
+    
+    for (rdn_idx = 0; rdn_idx &lt; x509Name-&gt;numberOfRDNs; rdn_idx++) {
+        CSSM_X509_RDN_PTR rdn = &amp;x509Name-&gt;RelativeDistinguishedName[rdn_idx];
+
+        for (pair_idx = 0; pair_idx &lt; rdn-&gt;numberOfPairs; pair_idx++) {
+            CSSM_X509_TYPE_VALUE_PAIR *pair = &amp;rdn-&gt;AttributeTypeAndValue[pair_idx];
+            if (!compare_oids(&amp;pair-&gt;type, &amp;CSSMOID_CommonName))
+                continue;
+
+            switch (pair-&gt;valueType) {
+                case BER_TAG_PRINTABLE_STRING:
+                case BER_TAG_IA5_STRING:    
+                case BER_TAG_T61_STRING: {
+                    return (NSString *) PLCFAutorelease(CFStringCreateWithBytes(NULL, pair-&gt;value.Data, pair-&gt;value.Length, kCFStringEncodingUTF8, false));
+                    break;
+                }
+                default:
+                    return nil;
+            }
+        }
+    }
+    
+    return nil;
+}
+
+static int exportCertificates (NSString *outputFile) {
+    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+
+    /* Fetch all certificates */
+    NSArray *anchors;
+    NSError *error;
+    OSStatus err;
+
+    anchors = certificatesForTrustDomain(&amp;error);
+    if (anchors == nil) {
+        nsfprintf(stderr, @&quot;Failed to fetch system anchors: %@\n&quot;, error);
+        [pool release];
+        return EXIT_FAILURE;
+    }
+    
+    NSEnumerator *anchorEnumerator = [anchors objectEnumerator];
+    id certObj;
+    while ((certObj = [anchorEnumerator nextObject]) != nil) {
+        NSError *error = NULL;
+        const CSSM_X509_NAME *subject;
+        NSString *commonName = nil;
+
+        if ((err = SecCertificateGetSubject((SecCertificateRef) certObj, &amp;subject)) == noErr) {
+            commonName = getCommonName(subject);
+        } else {
+            NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys: @&quot;SecCertificateGetSubject() failed&quot;, NSLocalizedDescriptionKey, nil];
+            error = [NSError errorWithDomain: NSOSStatusErrorDomain code: err userInfo: userInfo];
+        }
+
+        if (commonName == nil) {
+            nsfprintf(stderr, @&quot;Failed to extract certificate description: %@\n&quot;, error);
+        } else {
+            nsfprintf(stderr, @&quot;Found %@\n&quot;, commonName);
+        }
+    }
+    
+    /*
+     * Perform export
+     */
+    CFDataRef pemData;
+    
+    /* Prefer the non-deprecated SecItemExport on Mac OS X &gt;= 10.7. We use an ifdef to keep the code buildable with earlier SDKs, too. */
+    nsfprintf(stderr, @&quot;Exporting certificates from the keychain\n&quot;);
+    err = SecKeychainItemExport((CFArrayRef) anchors, kSecFormatPEMSequence, kSecItemPemArmour, NULL, &amp;pemData);
+    PLCFAutorelease(pemData);
+
+    if (err != noErr) {
+        nsfprintf(stderr, @&quot;Failed to export certificates: %@\n&quot;, [NSError errorWithDomain: NSOSStatusErrorDomain code: err userInfo:nil]);
+        [pool release];
+        return EXIT_FAILURE;
+    }
+
+    nsfprintf(stderr, @&quot;Writing exported certificates\n&quot;);
+    if (outputFile == nil) {
+        NSString *str = [[[NSString alloc] initWithData: (NSData *) pemData encoding:NSUTF8StringEncoding] autorelease];
+        nsfprintf(stdout, @&quot;%@&quot;, str);
+    } else {
+        if (![(NSData *) pemData writeToFile: outputFile options: NSAtomicWrite error: &amp;error]) {
+            nsfprintf(stderr, @&quot;Failed to write to pem output file: %@\n&quot;, error);
+            [pool release];
+            return EXIT_FAILURE;
+        }
+    }
+    
+    [pool release];
+    return EXIT_SUCCESS;
+}
+
+static void usage (const char *progname) {
+    fprintf(stderr, &quot;Usage: %s [-u] [-o &lt;output file&gt;]\n&quot;, progname);
+    fprintf(stderr, &quot;\t-s\t\t\tDo not exit; observe the system keychain(s) for changes and update the output file accordingly.&quot;);
+    fprintf(stderr, &quot;\t-o &lt;output file&gt;\tWrite the PEM certificates to the target file, rather than stdout\n&quot;);
+}
+
+#if 0
+static void certsync_keychain_cb (ConstFSEventStreamRef streamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[])
+{
+    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+
+    MPCertSyncConfig *config = (MPCertSyncConfig *) clientCallBackInfo;
+
+    int ret;
+    if ((ret = exportCertificates(config-&gt;userAnchors, config-&gt;outputFile)) != EXIT_SUCCESS)
+        exit(ret);
+
+    [pool release];
+}
+#endif
+
+int main (int argc, char * const argv[]) {
+    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+
+    /* Parse the command line arguments */
+    BOOL runServer = NO;
+    NSString *outputFile = nil;
+    
+    int ch;
+    while ((ch = getopt(argc, argv, &quot;hsuo:&quot;)) != -1) {
+        switch (ch) {
+            case 's':
+                runServer = YES;
+                break;
+                
+            case 'o':
+                outputFile = [NSString stringWithUTF8String: optarg];
+                break;
+
+            case 'h':
+                usage(argv[0]);
+                exit(EXIT_SUCCESS);
+
+            default:
+                usage(argv[0]);
+                exit(EXIT_FAILURE);
+        }
+    }
+    argc -= optind;
+    argv += optind;
+    
+    /* Perform single-shot export  */
+    if (!runServer)
+        return exportCertificates(outputFile);
+   
+#if 0 
+    /* Formulate the list of directories to observe; We use FSEvents rather than SecKeychainAddCallback(), as during testing the keychain
+     * API never actually fired a callback for the target keychains. */
+    FSEventStreamRef eventStream;
+    {
+        NSAutoreleasePool *streamPool = [[NSAutoreleasePool alloc] init];
+
+        NSSearchPathDomainMask searchPathDomains = NSLocalDomainMask|NSSystemDomainMask;
+        if (userAnchors)
+            searchPathDomains |= NSUserDomainMask;
+
+        NSArray *libraryDirectories = NSSearchPathForDirectoriesInDomains(NSAllLibrariesDirectory, searchPathDomains, YES);
+        NSMutableArray *keychainDirectories = [NSMutableArray arrayWithCapacity: [libraryDirectories count]];
+        for (NSString *dir in libraryDirectories) {
+            [keychainDirectories addObject: [dir stringByAppendingPathComponent: @&quot;Keychains&quot;]];
+            [keychainDirectories addObject: [dir stringByAppendingPathComponent: @&quot;Security/Trust Settings&quot;]];
+        }
+
+        /* Configure the listener */
+        MPCertSyncConfig *config = [[[MPCertSyncConfig alloc] init] autorelease];
+        config-&gt;userAnchors = userAnchors;
+        config-&gt;outputFile = [outputFile retain];
+
+        FSEventStreamContext ctx = {
+            .version = 0,
+            .info = config,
+            .retain = CFRetain,
+            .release = CFRelease,
+            .copyDescription = CFCopyDescription
+        };
+        eventStream = FSEventStreamCreate(NULL, certsync_keychain_cb, &amp;ctx, (CFArrayRef)keychainDirectories, kFSEventStreamEventIdSinceNow, 0.0, kFSEventStreamCreateFlagUseCFTypes);
+        FSEventStreamScheduleWithRunLoop(eventStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
+        FSEventStreamStart(eventStream);
+        
+        [streamPool release];
+    }
+
+    /* Perform an initial one-shot export, and then run forever */
+    {
+    NSAutoreleasePool *shotPool = [[NSAutoreleasePool alloc] init];
+        int ret;
+        if ((ret = exportCertificates(userAnchors, outputFile)) != EXIT_SUCCESS)
+            return EXIT_FAILURE;
+        [shotPool release];
+    }
+
+    CFRunLoopRun();
+    FSEventStreamRelease(eventStream);
+#endif
+    [pool release];
+
+    return EXIT_SUCCESS;
+}
+
</ins></span></pre>
</div>
</div>

</body>
</html>