[Mac, iOS] Crash log application information contains latest main frame URL instead...
[WebKit-https.git] / Tools / DumpRenderTree / mac / ResourceLoadDelegate.mm
1 /*
2  * Copyright (C) 2007, 2011 Apple Inc.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer. 
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution. 
13  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission. 
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #import "config.h"
30 #import "ResourceLoadDelegate.h"
31
32 #import "DumpRenderTree.h"
33 #import "TestRunner.h"
34 #import <WebKit/WebKit.h>
35 #import <WebKit/WebDataSourcePrivate.h>
36 #import <wtf/Assertions.h>
37
38 using namespace std;
39
40 @interface NSURL (DRTExtras)
41 - (NSString *)_drt_descriptionSuitableForTestResult;
42 @end
43
44 @interface NSError (DRTExtras)
45 - (NSString *)_drt_descriptionSuitableForTestResult;
46 @end
47
48 @interface NSURLResponse (DRTExtras)
49 - (NSString *)_drt_descriptionSuitableForTestResult;
50 @end
51
52 @interface NSURLRequest (DRTExtras)
53 - (NSString *)_drt_descriptionSuitableForTestResult;
54 @end
55
56 @implementation NSError (DRTExtras)
57 - (NSString *)_drt_descriptionSuitableForTestResult 
58 {
59     NSString *str = [NSString stringWithFormat:@"<NSError domain %@, code %ld", [self domain], static_cast<long>([self code])];
60     NSURL *failingURL;
61
62     if ((failingURL = [[self userInfo] objectForKey:@"NSErrorFailingURLKey"]))
63         str = [str stringByAppendingFormat:@", failing URL \"%@\"", [failingURL _drt_descriptionSuitableForTestResult]];
64
65     str = [str stringByAppendingFormat:@">"];
66
67     return str;
68 }
69
70 @end
71
72 @implementation NSURL (DRTExtras)
73
74 - (NSString *)_drt_descriptionSuitableForTestResult 
75 {
76     if (![self isFileURL])
77         return [self absoluteString];
78
79     WebDataSource *dataSource = [mainFrame dataSource];
80     if (!dataSource)
81         dataSource = [mainFrame provisionalDataSource];
82
83     NSString *basePath = [[[[dataSource request] URL] path] stringByDeletingLastPathComponent];
84     basePath = [basePath stringByAppendingString:@"/"];
85
86     if (basePath && [[self path] hasPrefix:basePath])
87         return [[self path] substringFromIndex:[basePath length]];
88     return [self lastPathComponent]; // We lose some information here, but it's better than exposing a full path, which is always machine specific.
89 }
90
91 @end
92
93 @implementation NSURLResponse (DRTExtras)
94
95 - (NSString *)_drt_descriptionSuitableForTestResult
96 {
97     int statusCode = 0;
98     if ([self isKindOfClass:[NSHTTPURLResponse class]])
99         statusCode = [(NSHTTPURLResponse *)self statusCode];
100     return [NSString stringWithFormat:@"<NSURLResponse %@, http status code %i>", [[self URL] _drt_descriptionSuitableForTestResult], statusCode];
101 }
102
103 @end
104
105 @implementation NSURLRequest (DRTExtras)
106
107 - (NSString *)_drt_descriptionSuitableForTestResult
108 {
109     NSString *httpMethod = [self HTTPMethod];
110     if (!httpMethod)
111         httpMethod = @"(none)";
112     return [NSString stringWithFormat:@"<NSURLRequest URL %@, main document URL %@, http method %@>", [[self URL] _drt_descriptionSuitableForTestResult], [[self mainDocumentURL] _drt_descriptionSuitableForTestResult], httpMethod];
113 }
114
115 @end
116
117 @implementation ResourceLoadDelegate
118
119 - (id)webView: (WebView *)wv identifierForInitialRequest: (NSURLRequest *)request fromDataSource: (WebDataSource *)dataSource
120 {
121     ASSERT([[dataSource webFrame] dataSource] || [[dataSource webFrame] provisionalDataSource]);
122
123     if (!done)
124         return [[request URL] _drt_descriptionSuitableForTestResult];
125
126     return @"<unknown>";
127 }
128
129 BOOL isLocalhost(NSString *host)
130 {
131     // FIXME: Support IPv6 loopbacks.
132     return NSOrderedSame == [host compare:@"127.0.0.1"] || NSOrderedSame == [host caseInsensitiveCompare:@"localhost"];
133 }
134
135 BOOL hostIsUsedBySomeTestsToGenerateError(NSString *host)
136 {
137     return NSOrderedSame == [host compare:@"255.255.255.255"];
138 }
139
140 -(NSURLRequest *)webView: (WebView *)wv resource:identifier willSendRequest: (NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)dataSource
141 {
142     if (!done && gTestRunner->dumpResourceLoadCallbacks()) {
143         NSString *string = [NSString stringWithFormat:@"%@ - willSendRequest %@ redirectResponse %@", identifier, [request _drt_descriptionSuitableForTestResult],
144             [redirectResponse _drt_descriptionSuitableForTestResult]];
145         printf("%s\n", [string UTF8String]);
146     }
147
148     if (!done && !gTestRunner->deferMainResourceDataLoad()) {
149         [dataSource _setDeferMainResourceDataLoad:false];
150     }
151
152     if (!done && gTestRunner->willSendRequestReturnsNull())
153         return nil;
154
155     if (!done && gTestRunner->willSendRequestReturnsNullOnRedirect() && redirectResponse) {
156         printf("Returning null for this redirect\n");
157         return nil;
158     }
159
160     NSURL *url = [request URL];
161     NSString *host = [url host];
162     if (host && (NSOrderedSame == [[url scheme] caseInsensitiveCompare:@"http"] || NSOrderedSame == [[url scheme] caseInsensitiveCompare:@"https"])) {
163         NSString *testURL = [NSString stringWithUTF8String:gTestRunner->testURL().c_str()];
164         NSString *lowercaseTestURL = [testURL lowercaseString];
165         NSString *testHost = 0;
166         if ([lowercaseTestURL hasPrefix:@"http:"] || [lowercaseTestURL hasPrefix:@"https:"])
167             testHost = [[NSURL URLWithString:testURL] host];
168         if (!isLocalhost(host) && !hostIsUsedBySomeTestsToGenerateError(host) && (!testHost || isLocalhost(testHost))) {
169             printf("Blocked access to external URL %s\n", [[url absoluteString] cStringUsingEncoding:NSUTF8StringEncoding]);
170             return nil;
171         }
172     }
173
174     if (disallowedURLs && CFSetContainsValue(disallowedURLs, url))
175         return nil;
176
177     NSMutableURLRequest *newRequest = [request mutableCopy];
178     const set<string>& clearHeaders = gTestRunner->willSendRequestClearHeaders();
179     for (set<string>::const_iterator header = clearHeaders.begin(); header != clearHeaders.end(); ++header) {
180         NSString *nsHeader = [[NSString alloc] initWithUTF8String:header->c_str()];
181         [newRequest setValue:nil forHTTPHeaderField:nsHeader];
182         [nsHeader release];
183     }
184     const std::string& destination = gTestRunner->redirectionDestinationForURL([[url absoluteString] UTF8String]);
185     if (destination.length())
186         [newRequest setURL:[NSURL URLWithString:[NSString stringWithUTF8String:destination.data()]]];
187
188     return [newRequest autorelease];
189 }
190
191 - (void)webView:(WebView *)wv resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource
192 {
193     if (!gTestRunner->handlesAuthenticationChallenges()) {
194         NSString *string = [NSString stringWithFormat:@"%@ - didReceiveAuthenticationChallenge - Simulating cancelled authentication sheet", identifier];
195         printf("%s\n", [string UTF8String]);
196
197         [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
198         return;
199     }
200     
201     const char* user = gTestRunner->authenticationUsername().c_str();
202     NSString *nsUser = [NSString stringWithFormat:@"%s", user ? user : ""];
203
204     const char* password = gTestRunner->authenticationPassword().c_str();
205     NSString *nsPassword = [NSString stringWithFormat:@"%s", password ? password : ""];
206
207     NSString *string = [NSString stringWithFormat:@"%@ - didReceiveAuthenticationChallenge - Responding with %@:%@", identifier, nsUser, nsPassword];
208     printf("%s\n", [string UTF8String]);
209     
210     [[challenge sender] useCredential:[NSURLCredential credentialWithUser:nsUser password:nsPassword persistence:NSURLCredentialPersistenceForSession]
211                               forAuthenticationChallenge:challenge];
212 }
213
214 - (void)webView:(WebView *)wv resource:(id)identifier didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource
215 {
216 }
217
218 -(void)webView: (WebView *)wv resource:identifier didReceiveResponse: (NSURLResponse *)response fromDataSource:(WebDataSource *)dataSource
219 {
220     if (!done && gTestRunner->dumpResourceLoadCallbacks()) {
221         NSString *string = [NSString stringWithFormat:@"%@ - didReceiveResponse %@", identifier, [response _drt_descriptionSuitableForTestResult]];
222         printf("%s\n", [string UTF8String]);
223     }
224     if (!done && gTestRunner->dumpResourceResponseMIMETypes())
225         printf("%s has MIME type %s\n", [[[[response URL] relativePath] lastPathComponent] UTF8String], [[response MIMEType] UTF8String]);
226 }
227
228 -(void)webView: (WebView *)wv resource:identifier didReceiveContentLength: (NSInteger)length fromDataSource:(WebDataSource *)dataSource
229 {
230 }
231
232 -(void)webView: (WebView *)wv resource:identifier didFinishLoadingFromDataSource:(WebDataSource *)dataSource
233 {
234     if (!done && gTestRunner->dumpResourceLoadCallbacks()) {
235         NSString *string = [NSString stringWithFormat:@"%@ - didFinishLoading", identifier];
236         printf("%s\n", [string UTF8String]);
237     }
238 }
239
240 -(void)webView: (WebView *)wv resource:identifier didFailLoadingWithError:(NSError *)error fromDataSource:(WebDataSource *)dataSource
241 {
242     if (!done && gTestRunner->dumpResourceLoadCallbacks()) {
243         NSString *string = [NSString stringWithFormat:@"%@ - didFailLoadingWithError: %@", identifier, [error _drt_descriptionSuitableForTestResult]];
244         printf("%s\n", [string UTF8String]);
245     }
246 }
247
248 - (void)webView: (WebView *)wv plugInFailedWithError:(NSError *)error dataSource:(WebDataSource *)dataSource
249 {
250 #if !PLATFORM(IOS)
251     // The call to -display here simulates the "Plug-in not found" sheet that Safari shows.
252     // It is used for platform/mac/plugins/update-widget-from-style-recalc.html
253     [wv display];
254 #endif
255 }
256
257 -(NSCachedURLResponse *) webView: (WebView *)wv resource:(id)identifier willCacheResponse:(NSCachedURLResponse *)response fromDataSource:(WebDataSource *)dataSource
258 {
259     if (!done && gTestRunner->dumpWillCacheResponse()) {
260         NSString *string = [NSString stringWithFormat:@"%@ - willCacheResponse: called", identifier];
261         printf("%s\n", [string UTF8String]);
262     }
263     return response;
264 }
265
266 -(BOOL)webView: (WebView*)webView shouldPaintBrokenImageForURL:(NSURL*)imageURL
267 {
268     // Only log the message when shouldPaintBrokenImage() returns NO; this avoids changing results of layout tests with failed
269     // images, e.g., security/block-test-no-port.html.
270     if (!done && gTestRunner->dumpResourceLoadCallbacks() && !gTestRunner->shouldPaintBrokenImage()) {
271         NSString *string = [NSString stringWithFormat:@"%@ - shouldPaintBrokenImage: NO", [imageURL _drt_descriptionSuitableForTestResult]];
272         printf("%s\n", [string UTF8String]);
273     }
274
275     return gTestRunner->shouldPaintBrokenImage();
276 }
277 @end