What Do You Call One Search Result From StackOverflow?

Windows Phone 7 301 Redirect Bug

I checked with the Windows Phone 7 team before putting this post out, and got the OK to write about it.  I hit this bug when building out my FriendLinks Windows Phone 7 application, and was surprised to find it was a bona fide bug and not a problem with my coding skills.  If there was a default value in the constructor for any new project I start, it would look something like:

codingErrorResponsibilty == this.programmerName;

 

In any event, here’s the cruxt of the bug.  If you are using HttpWebRequest developing on Windows Phone 7, and you get a 301 redirect returned from the web server, and that web server sets a cookie, the current build (as of 03/16/10 at Mix10) of Windows Phone 7 will throw an exception.

In the case of my applications, I was trying to determine the title of the page as defined by the “<title></title>” tags for a given URL.  The function I wrote for this was:

try
{
    WebResponse response = ((HttpWebRequest)result.AsyncState)
                            .EndGetResponse(result);
    StreamReader reader = new StreamReader(response.GetResponseStream());
    string responseString = reader.ReadToEnd();
    string regex = @"(?<=<title.*>)([\s\S]*)(?=</title>)";

    if (new List<string>(response.Headers.AllKeys).Contains("Content-Type"))
    {
        if (response.Headers["Content-Type"].StartsWith("text/html"))
        {
            Regex ex = new Regex(regex, RegexOptions.IgnoreCase);

            selectedUrlTitle = ex.Match(responseString).Value.Trim();

            if (String.IsNullOrEmpty(selectedUrlTitle))
            {
                selectedUrlTitle = "No title for page";
            }
        }

    }
    
    UrlTitleRequestCompleted(this, EventArgs.Empty);
}

For some URLs this was throwing the most elusive of all exceptions: CookieException.  Behold, I present to you a StackOverflowWhack! [note: a nod to GoogleWhacks]  There should really be a better name for that.

image

There is only one response for this search query at StackOverflow.  Interestingly enough, when I first hit this bug, there were no questions – this one was asked in the last week.

The debug information from Visual Studio was even less useful.  It was telling me that the cookie was too big.  A little searching revealed that this exception is thrown when you try to set a cookie larger than MaxCookieSize for a CookieContainer.  That value cannot be changed in Silverlight, and since I don’t control the remote web servers, I can’t control the cookie coming back.  Worse, whether or not the cookie was being set on the 301 redirects varied from domain to domain.  Some set it, some didn’t.

In using Fiddler2 to debug this problem, here is what a redirect looks like that won’t throw the CookieException:

HTTP/1.1 301 Moved Permanently
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Transfer-Encoding: chunked
Via: 1.1 RED-PRXY-21
Date: Wed, 03 Mar 2010 02:55:15 GMT
Location: http://blogs.bnet.com/career-advice/?p=101
Content-Type: text/html; charset=UTF-8
Server: Apache
Set-Cookie: supr=supr301; path=/; domain=.su.pr
Vary: Accept-Encoding

 

In this case, su.pr didn’t try to set the cookie.  And here is a 301 redirect that tries to set a cookie:

HTTP/1.1 301 Moved
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Content-Length: 381
Via: 1.1 RED-PRXY-21
Date: Wed, 03 Mar 2010 02:57:15 GMT
Location: http://www.allfacebook.com/2010/03/facebook-developers-see-
               dramatic-drop-in-traffic-following-removal-of-notifications/
Content-Type: text/html; charset=utf-8
Server: nginx/0.7.42
Set-Cookie: _bit=4b8dd00b-0013c-01992-b5a08fa8;domain=.bit.ly;
                expires=Sun Aug 29 22:57:15 2010;path=/; HttpOnly
MIME-Version: 1.0

In this case, bit.ly is in fact trying to set a cookie.  What helped lead me down the path of figuring this out was a short.to link that forwarded to a bit.ly link.  Here’s the chain of raw headers:

HTTP/1.1 301 Moved Permanently
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Content-Length: 0
Via: 1.1 RED-PRXY-21
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Date: Wed, 03 Mar 2010 02:58:43 GMT
Location: http://bit.ly/8ZyVoz
Content-Type: text/html; charset=utf-8
Server: Google Frontend
Cache-Control: no-cache
X-XSS-Protection: 0

HTTP/1.1 301 Moved
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Content-Length: 312
Via: 1.1 RED-PRXY-21
Date: Wed, 03 Mar 2010 02:58:44 GMT
Location: http://news.cnet.com/8301-13578_3-10462563-38.html
Content-Type: text/html; charset=utf-8
Server: nginx/0.7.42
Set-Cookie: _bit=4b8dd064-000f6-0198d-b5a08fa8;domain=.bit.ly;
                expires=Sun Aug 29 22:58:44 2010;path=/; HttpOnly
MIME-Version: 1.0

 

As you can see here, the first header revealed a 301 to a bit.ly URL, which then tried to redirect to a news.com article.  Some other offenders of this cookie setting on 301 redirects are FourSquare and TechCrunch.  Mind you, this isn’t a bug in their 301 redirect, it’s a bug in how Windows Phone 7 handles the redirect.

I ultimately had to abandon this path to get the page title because once that CookieException is thrown, there is no data in the exception that allows you to get access to the header.  The exception is thrown when the WebResponse object is being set to the result of reading to the end of the asynch response.  The CookieException itself doesn’t reveal any of the 301 redirect information, so recovering from this exception is next to impossible, except to abandon trying to get the URL title.

For my specific app, I needed to get that title information, and since the vast majority of links coming through Twitter were bit.ly, I needed another way.  Mercifully, TechMeme reveals this information through their API.

So there you go – if you are getting a 301 redirect in a HttpWebRequest, and your code is throwing a CookieException, now you know why.  This is a filed bug and should be fixed, but given the amount of excitement around Windows Phone 7 development right now, I wanted to try and save people pain and suffering.  It’s better that only one of us lose hair.