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.

Associative References

If you’ve been developing with Objective-C for a while you know it’s powerful stuff. While it’s not as elegant looking as some languages, such as Ruby, it does have a rather impressive array of features that make it just flexible as new languages, such as Ruby.

One of the flexible features of Objective-C is Categories. Categories allow developers to snap on methods to classes they didn’t create and don’t have access to their source code. Beyond that, these methods become part of the class hierarchy.

One complaint that I’ve had with Categories is that you can’t add properties as part of the category snap on. Recently I wanted to extend UITextView so that it would be easier to take advantage of AttributesStrings. My first thought was to create a Category and initially it seemed I was on the right track. That was, until I realized that I wanted to have the UITextView keep track of default fonts. Default fonts mean properties and properties mean so long Category … or does it?

After building a subclass of UITextView, to do the things I want AND adding new properties, I wasn’t happy with the way thing looked. It’s not that the code wouldn’t do it’s job but it just didn’t feel as clean as it could be. I tried to improve my code by splitting off some capability into a Category.

As I wrote the Category it just felt right so I started trying to move the rest of my code into the category but still there were these properties. A little research on the net turned over something new, Associative References.

Associative References make it possible, like Categories, to attach (or associate) an object instance variables to an existing class and as the French would say “et voila” there you go, Categories with Properties.

Ok, so how do you make use of Associative References? First stop is to add properties to your Category:

@interface UITextView (Utilities)

@property (nonatomic, strong) UIFont *regularFont;

Now, Xcode will complain that since this is a category you’re going to have to implement the getter and setter for this property. So let’s get to implementing:

#import <objc/runtime.h>

static void *RegularFontKey;

@implementation UITextView (Utilities)

- (UIFont *)regularFont{
    return objc_getAssociatedObject(self, &RegularFontKey);
}

- (void)setRegularFont:(UIFont *)regularFont{
    objc_setAssociatedObject(self, &RegularFontKey, regularFont, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

Lines 7-9 and 11-13 are the methods that addresses Xcodes complaint. Pretty boiler plate. The magic happens on lines 8 and 12. Line 12 sets the value of the property and line 8 gets the value of the property. In both cases you’ll notice the use of the void pointer from line 3. This is a key that makes the association possible and it needs to be unique per property  and per class but not per property. This means that a developer simply has to replicate the pattern in line 3 per key.

In general, I would say simply replicate the pattern laid out in the code above to add properties to a category.

Happy Hunting

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.

Warning be gone

In a previous post I talked about getting clang to be quite, ie every once in a blue moon you want a warning to simply go away. As I said, I’m really not a big fan of doing this, a warning usually means that something is wrong and you should fix it and not just ignore it.

For that once in a blue moon event I’ve got more detail on how to turn the warning suppression from a blunt instrument to a nice precision surgical instrument.

Inserting the following line in your code will suppress ARC performSelector warnings.

#pragma clang diagnostic ignored "-Warc-performSelector-leaks"

If you add a little more code

#pragma clang diagnostics push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
// code  that needs a warning suppressed
#pragma clang diagnostics pop

You limit the impact of the suppression to just the bounds of the push and pop.

Of course the next part of the magic act is to figure out what exactly is the warning you want to suppress. Xcode does a fantastic job of giving you the human readable version. It actually gives you a running start before you slam into the brick wall. The problem is that there doesn’t appear to be a very good/complete list of human redable warnings and their official flag counterparts. So, what is one to do now?

Turn out that if you’re willing to peal away a layer of Xcode you can find the actual warning flag. Start by compiling your code, which will bring up the warning. Next, press Apple-7. This will bring up the Log Navigator. Click on the top log and scroll down until you find your warning. Click the detail button, its the rounded button with a set of horizontal lines. Now you see behind the Xcode curtain and see the gory detail. The top part of the details is the exact command used to compile your problem file. The bottom part gives you the details of the warning. If you examine the warning you’ll see that the ling ends with a [-Wwarning]. That’s it. This is the flag you want.

This is where I found info about the warning suppression push and pop ‘Disabling Clang Compiler Warnings’

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.

The Literals are Coming, the Literals are Coming

It’s just days before WWDC and the rumors are flying about what Apple will introduce. Will it be iOS 6? new iPhone hardware? MacBook Pros? how about Mac Pros? One addition that isn’t actually a rumor but pretty much a confirmed fact is the addition of literals to Objective-C and the arrival of the Apple LLVM compiler.

The cat escaped the bag back in March when Apple checked in code to the open source clang trunk, over at LLVM.org, adding capabilities to make literals possible. Along with checking in the code came some very nice documentation that details what literals mean for developers. The Big Nerd Ranch Weblog followed the release by Apple with a slightly shorter explanation on literals.

If you have the time I would definitely recommend reading the LLVM.org article. The short version on literals is that Apple is bringing some of the comforts of Ruby to Objective-C by extending the responsibilities of the ‘@’ symbole. The slightly longer version is the Apple is adding syntactical sugar to NSNumber, NSArray, and NSDictionary.

For NSNumber Apple has simplified the process of creating them. You can now prepend a number with the ‘@’ symbol and presto, you’ve got an NSNumber object. There isn’t an equivalent way to get your number back out of NSNumber but this is definitely a good start.

For NSArray and NSDictionary Apple has added a bit of magic too. Now you can create an NSArray by putting your array inside a ‘@[]’ and an NSDictionary by putting your dictionary inside a ‘@{}’. Unlike NSNumber Apple added a nice way to get data back out of both NSArray and NSDictionary. The secret is ‘[]’. You put square brakets after either your NSArray or NSDictionary and then put your index, either number or object, inside the square brackets.

If you’re feeling particularly adventures you can download the current build of both llvm and clang from LLVM.org. Unfortunately at the moment Xcode doesn’t have these new features but wait a moment, well at least until Monday, and you’ll have Objective-C with Literals.

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.

A Little Insperation

Every now and than I come across some good inspiring video. Not too long ago I came across this video of the winner of the Moth GrandSLAM. The main guy talking is Moran Cerf, an Israeli, and he gives a very engaging talk about his background and the story that led him to becoming a researcher.

All in all this is a great video and well worth the 10 minutes.