Oblivious DNS over HTTPS (ODoH)

One of the oldest corner stones of the internet has been the domain name service (DNS). Those three little letters have saved us all from having to remember IP addresses and replaced them with fun host names (much easier to remember Google.com then 172.217.7.14). Being one of the oldest protocols on the net it’s also one that has seen less change especially in the area of privacy and security. 

For those that don’t know, many DNS queries still travel the highways and byways of the internet in cleartext. Not only can someone see what host you are trying to look up but also that YOU are looking it up and like every other bit of data that can be collected about you on the internet your DNS queries have become one more piece of data that’s collected and monetized.

More recently the IETF has introduced some standards (DoH and DoT) that help protect your DNS queries from being intercepted, redirected, or modified. Which is great news for protecting your DNS queries on their way to the DNS resolver but don’t prevent your resolver (Usually run by your ISP) from mining your DNS queries and monetizing them.

To address this problem the good engineers at Cloudflare, Apple, and Fastly introduced a new DNS standard called Oblivious DNS over HTTPS (ODoH). At its core, the standard introduces a proxy into the DNS equation that helps separate the hostname from the querying IP address. The end result is that the DNS resolver only knows that someone is asking to resolve a hostname and the proxy only knows that you are asking to resolve some hostname but neither has the full picture. Privacy restored. Mind you, I’ve boiled things down substantially here so if you’re interested in the fine-grain details check out the Cloudflare blog post (link)

As with any other proposed standard, ODoH will take some time to make its way out into the world but I, for one, look forward to seeing it fully implemented and widely adopted.

Transitioning to iOS7

A lot of people are taking the plunge, like it or not, into iOS7 “optimized” apps. Some folks were going to take their time and transition slowly but Apples recent announcement to developers that February was it and that like it or not they HAD to build iOS7 apps by February has pushed timelines into hyperdrive.

Here are a few useful things I’ve learned along the way that might may others transition to iOS7 a little easier:

1. iOS7 or not
This little bit of code

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1)

can easily detect if you’re running on iOS6.1 or older. Of course the opposite is also true. You can use this code

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)

can detect if you’re running on iOS7 or newer. Very helpful if you want to keep your old code in place, to look nice for your customers running iOS6.1 or older.

In case you have to continue supporting iOS6 / Xcode 4 then creating the following header file

#ifndef PK_Xcode4_support_h
#define PK_Xcode4_support_h

#ifndef NSFoundationVersionNumber_iOS_6_0
    #define NSFoundationVersionNumber_iOS_6_0  993.00
#endif

#ifndef NSFoundationVersionNumber_iOS_6_1
    #define NSFoundationVersionNumber_iOS_6_1  993.00
#endif

#endif

will ensure that your code behaves properly when compiled with Xcode 4 or Xcode 5. By the way a quick look in NSObjCRuntime.h will confirm that both NSFoundationVersionNumber_iOS_6_0 and NSFoundationVersionNumber_iOS_6_1 are supposed to be defined as 993.00.

2. Mind the gap
One of the new features of iOS7 is that your views can slide under the navigation bar. If you want to do this on purpose then more power to you but if you’re just trying to get your app to look reasonable then this little bit of code

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
    // Setting traslucent make sure that the view doesn't slide under in iOS7
    self.navigationController.navigationBar.translucent = NO;
}

3. Wrapping table cells
Some code relies on the fact that the superview of a UITableViewCell to be a UITableView. This is no long true under iOS7. As of iOS7 UITableViewCell superview is actually UITableViewCellScrollView (which is so to support sliding table cells for delete etc). In general it’s probably a bad idea to depend on the view hierarchy (Apple can and does change it) but if you’re going to this little bit of code

id cellSuperview = [cell superview];
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
     cellSuperview = [cellSuperview superview];
}

will do the trick. cellSuperview should, at the end of this code, point to the UITableView that the cell lives in.

4. Popovers
One problem that became apparent very quickly, as I was transitioning code to iOS7, is that UIPopoverController‘s we’re a very happy bunch. All of the popovers looked wrong. After much digging and searching I discovered that iOS7 UIPopoverControllers looked at the contents preferred content size. To that end I wrote this method

- (void)setContentSize:(CGSize)contentSize animated:(BOOL)animated{
    if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
        CGSize size = contentSize;
        if (size.width == 0){
            size.width = 320;
        }
        if ((size.height == 0) || (size.height == 44)){
            size.height = 1100;
        }
        [self.contentViewController setValue:[NSValue valueWithCGSize:size] forKey:@"preferredContentSize"];
    } else {
        [self setPopoverContentSize:contentSize animated:animated];
    }
}

in a category class for UIPopoverController. This code checks if we’re running under iOS7 or 6. If we’re running under iOS7 it looks at the size being passed in. The code assumes that the argument contentSize is from a call to the contents UIViewController method contentSizeForViewInPopover. Under iOS7 this method has been deprecated and returns width=0 and height=0. Previously this method would have returned width=320 and height=1100. This category method then sets the size back to the original default and then sets the preferredContentSize of the contentViewController so that the UIPopoverController will once again be happy.

5. Searching Popovers
One problem I came across, which is less of an iOS6 to iOS7 problem and more of an iOS7 to iOS7.1 problem, is searching in popovers. There seems to be a problem with the search view not properly managing the search view. The result is that as you type and get results for the search the view overwrites the underlying view BUT the underlying view remains active. This is a serious mess. So far I haven’t found a good answer other then using iOS7.1. Apparently this is a good solid iOS7 SDK bug that Apple has fixed. As of yet I haven’t found a good backwards fix.

Well, that’s all for now. As I discover more of the tips I’ll post the.

Finding the words

Recently I was challenged to build some code that could brake up an NSString into an array of NSStrings that would fit into a given width in an iOS app. Seems fairly straight forward, given that Apple has it in their text GUI elements. No dice my friends. While Apple does give you the ability to discover the dimensions of an NSString given a UIFont and, optionally, some size constraints it wont tell you how to break up the NSString into the individual lines.

So, what is one to do? Time to replicate some existing Apple capability. The basic idea is to split up a string into words, then build a line by adding a word at a time until it’s too long, then repeat until you’ve run out of tokens.

Splitting a string into words isn’t easy. My first stop was to use ParseKit. It’s a nice fast parser for Objective-C but it seems to have lost its support and hasn’t been updated in some time. The fact that it hasn’t been updated in a while made it a bit harder to integrate into the project. After a bit of pushing and pulling I managed to stuff it into the project.

Over all the ParseKit worked well enough and its compiled library wasn’t particularly big but it was a pain to install and has quiet a few warnings. I ended up fixing a bit of code and also adding a bunch of warning suppression so that I could work in peace.

I got the code to work but I wasn’t happy with all the extra code that was hanging around to make ParseKit work. So it was back to the drawing board. I dug around the net but didn’t find anything that I was happy with, time to reinvent the wheel.

What I ended up doing was making use of Objective-C regular expression engine, NSRegularExpression, and hand built a regular expression.

    NSMutableString *regexPattern = [NSMutableString string];
    // A number or dollar amount
    [regexPattern appendString:@"(\\$?\\d+(\\.\\d+)?)"];
    // or
    [regexPattern appendString:@"|"];
    // possibly starting with a quote, a word, possibly trailing by punctuation
    [regexPattern appendString:@"\\\"?([\\w\\']*)(\\.\\.\\.|\\.|,|-|!|\\?|:|;|\\\")?"];
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexPattern options:NSRegularExpressionCaseInsensitive error:&error];

Lines 3,5, and 7 or the different parts of the regular expression I built to parse words. Line 3 matches numbers as well as dollar values. line 5 is a simple ‘or’, and line 7 matches a word, consuming the leading quote if there is one, consuming trailing punctuation if that exists. The rest of the code in that method simply builds an array of all the tokens.

Here is the full code for turning a string into an array of words:

- (NSArray *)stringToWords{
    NSMutableString *regexPattern = [NSMutableString string];
    // A number or dollar amount
    [regexPattern appendString:@"(\\$?\\d+(\\.\\d+)?)"];
    // or
    [regexPattern appendString:@"|"];
    // possibly starting with a quote, a word, possibly trailing by punctuation
    [regexPattern appendString:@"\\\"?([\\w\\']*)(\\.\\.\\.|\\.|,|-|!|\\?|:|;|\\\")?"];
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexPattern options:NSRegularExpressionCaseInsensitive error:&error];

    NSArray *matches = [regex matchesInString:self
                                      options:0
                                        range:NSMakeRange(0, [self length])];
    NSMutableArray *tokens = [NSMutableArray array];
    NSUInteger endOfLastToken = 0;
    for (NSTextCheckingResult *match in matches) {
        NSRange matchRange = [match range];
        if (matchRange.location != endOfLastToken){
            NSRange tempRange = NSMakeRange(endOfLastToken, matchRange.location - endOfLastToken);
            [tokens addObject:[self substringWithRange:tempRange]];
        }
        [tokens addObject:[self substringWithRange:matchRange]];
        endOfLastToken = matchRange.location + matchRange.length;
    }

    return tokens;
}

And here is the full code for using that array of tokens to an array of lines:

- (NSArray *)linesConstrainedToWidth:(CGFloat)maxWidth withFirstLineIndent:(CGFloat)indent andFont:(UIFont *)font{
    CGSize maxSize = CGSizeMake(maxWidth - indent, FLT_MAX);

    NSMutableArray *strings = [NSMutableArray array];
    NSMutableString *newString = [NSMutableString string];
    NSMutableString *oldString = [NSMutableString string];

    NSArray *tokens = [self stringToWords];
    for (NSString *token in tokens){
        //NSLog(@"(%@) (%.1f) : %@", token.stringValue, token.floatValue, [token debugDescription]);
        [newString appendString:token];
        CGSize size = [newString sizeWithFont:font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];
        if (size.height > font.lineHeight){
            [strings addObject:oldString];
            newString = [NSMutableString stringWithString:token];
            maxSize = CGSizeMake(maxWidth, 2000.0);
        } else {
            oldString = [NSMutableString stringWithString:newString];
        }
    }
    [strings addObject:newString];

    return strings;
}

As you can see this method allows you to constrain the line to a specific width as well as setting a first line indent, just in case.

Objective-C Duck Punching

Objective-C is a cool language for many reasons. One reason is that it’s a dynamic language that allows you to do all kinds of fun things at runtime. Allas one of those features has gone away with the introduction to ARC.

Once upon a time you could send any message you like to an Objective-C object and it would try to respond. If you inherited from NSObject you could make use of the invocationForwarding method to handle any method you didn’t expressly implement. Over time the compiler got smarter and wouldn’t let you send just any message to Objective-C objects so you had to switch to using the id type. id would catch anything. This is no more.

I came across this thread ARC: error: no known instance method for selector. One of the contributors to the thread, John McCall of Apple, made the following statement:

Our reasoning was split about 50/50 between (1) needing to be more careful about types and ownership and (2) wanting to eliminate an embarrassing wart in the language (not being allowed to complain about completely unknown methods with anything more strenuous than a warning).  There is really no legitimate reason to call a method that's not even declared somewhere.  The ability to do this makes some really trivial bugs (e.g. typos in selectors) runtime failures instead of compile failures.  We have always warned about it.  Fix your code.

John.

You can follow the whole thread but the short is that Apple made the call to be more cautious about types and ownership and traded away the flexability of id. Is this the end of the world? Nah, it just takes out a nice little quirky feature of the language.

Telling clang to be quiet

When using Xcode I’m a big believer in clearing out not just the error messages that I get but also all the warnings. 99% of the time if I ignore a warning it usually results in something crashing or a weird bug expressing itself. BUT there is that 1% of the time when Xcode produces a false positive and you get a warning that isn’t and all you want to do is make it go away. Today was such a day and thankfully I found how to tell clang to ignore the warning.

I have some code:

[component performSelector:componentSelector];

clang really doesn’t like this code. The problem is that ‘componentSelector’ is a variable and clang doesn’t have a enough information about it so it raises a flag about possible memory leak. Now, I know, since I wrote the code, that ‘componentSelector’ is good and won’t cause a memory leak so to silence the warning I add the following:

#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[component performSelector:componentSelector];

this is a very nicely specific flag telling clang to ignore the performSelector leaks warning. I’d really rather find away around this, ie making clang happy, but thus far no luck so it’s the ignore flag till I do.

clang, It’s not just a Objective-C compiler frontend

One of the things I discovered while investigating building my own programming language was the fact that clang is much more then your typical front end to the llvm compiler. It turns out that clang can do all kinds of useful things for you if you’re trying to build your own C/C++/Objective-C IDE. Closer inspection of clang reveals that it can do all kinds of wonderful things like code completion, pointing to specific lines where you have coding mistakes, and much more. It’s a fantastic treasure trove of tools.

If you’re interested in learning more I would highly recommend taking a look at Doug Gregor’s LLVM Developer Meeting presentation titled “libclang: Thinking Beyond the Compiler” (slides/video) It’s a great presentation and it will get you on your way to building your own IDE or at least giving it some serious thought.