1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
|
/*
* Copyright (C) 2005, 2006, 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if ENABLE(NETSCAPE_PLUGIN_API)
#import "WebBaseNetscapePluginStream.h"
#import "WebBaseNetscapePluginView.h"
#import "WebKitErrorsPrivate.h"
#import "WebKitLogging.h"
#import "WebNSObjectExtras.h"
#import "WebNSURLExtras.h"
#import "WebNetscapePluginPackage.h"
#import <Foundation/NSURLResponse.h>
#import <WebCore/WebCoreObjCExtras.h>
#import <WebKitSystemInterface.h>
#import <wtf/HashMap.h>
#define WEB_REASON_NONE -1
static NSString *CarbonPathFromPOSIXPath(NSString *posixPath);
typedef HashMap<NPStream*, NPP> StreamMap;
static StreamMap& streams()
{
static StreamMap staticStreams;
return staticStreams;
}
@implementation WebBaseNetscapePluginStream
#ifndef BUILDING_ON_TIGER
+ (void)initialize
{
WebCoreObjCFinalizeOnMainThread(self);
}
#endif
+ (NPP)ownerForStream:(NPStream *)stream
{
return streams().get(stream);
}
+ (NPReason)reasonForError:(NSError *)error
{
if (error == nil) {
return NPRES_DONE;
}
if ([[error domain] isEqualToString:NSURLErrorDomain] && [error code] == NSURLErrorCancelled) {
return NPRES_USER_BREAK;
}
return NPRES_NETWORK_ERR;
}
- (NSError *)_pluginCancelledConnectionError
{
return [[[NSError alloc] _initWithPluginErrorCode:WebKitErrorPlugInCancelledConnection
contentURL:responseURL != nil ? responseURL : requestURL
pluginPageURL:nil
pluginName:[[pluginView pluginPackage] name]
MIMEType:MIMEType] autorelease];
}
- (NSError *)errorForReason:(NPReason)theReason
{
if (theReason == NPRES_DONE) {
return nil;
}
if (theReason == NPRES_USER_BREAK) {
return [NSError _webKitErrorWithDomain:NSURLErrorDomain
code:NSURLErrorCancelled
URL:responseURL != nil ? responseURL : requestURL];
}
return [self _pluginCancelledConnectionError];
}
- (id)initWithRequestURL:(NSURL *)theRequestURL
plugin:(NPP)thePlugin
notifyData:(void *)theNotifyData
sendNotification:(BOOL)flag
{
[super init];
// Temporarily set isTerminated to YES to avoid assertion failure in dealloc in case we are released in this method.
isTerminated = YES;
if (theRequestURL == nil || thePlugin == NULL) {
[self release];
return nil;
}
[self setRequestURL:theRequestURL];
[self setPlugin:thePlugin];
notifyData = theNotifyData;
sendNotification = flag;
fileDescriptor = -1;
streams().add(&stream, thePlugin);
isTerminated = NO;
return self;
}
- (void)dealloc
{
ASSERT(!plugin);
ASSERT(isTerminated);
ASSERT(stream.ndata == nil);
// The stream file should have been deleted, and the path freed, in -_destroyStream
ASSERT(!path);
ASSERT(fileDescriptor == -1);
[requestURL release];
[responseURL release];
[MIMEType release];
[pluginView release];
[deliveryData release];
free((void *)stream.url);
free(path);
free(headers);
streams().remove(&stream);
[super dealloc];
}
- (void)finalize
{
ASSERT_MAIN_THREAD();
ASSERT(isTerminated);
ASSERT(stream.ndata == nil);
// The stream file should have been deleted, and the path freed, in -_destroyStream
ASSERT(!path);
ASSERT(fileDescriptor == -1);
free((void *)stream.url);
free(path);
free(headers);
streams().remove(&stream);
[super finalize];
}
- (uint16)transferMode
{
return transferMode;
}
- (NPP)plugin
{
return plugin;
}
- (void)setRequestURL:(NSURL *)theRequestURL
{
[theRequestURL retain];
[requestURL release];
requestURL = theRequestURL;
}
- (void)setResponseURL:(NSURL *)theResponseURL
{
[theResponseURL retain];
[responseURL release];
responseURL = theResponseURL;
}
- (void)setPlugin:(NPP)thePlugin
{
if (thePlugin) {
plugin = thePlugin;
pluginView = [(WebBaseNetscapePluginView *)plugin->ndata retain];
WebNetscapePluginPackage *pluginPackage = [pluginView pluginPackage];
NPP_NewStream = [pluginPackage NPP_NewStream];
NPP_WriteReady = [pluginPackage NPP_WriteReady];
NPP_Write = [pluginPackage NPP_Write];
NPP_StreamAsFile = [pluginPackage NPP_StreamAsFile];
NPP_DestroyStream = [pluginPackage NPP_DestroyStream];
NPP_URLNotify = [pluginPackage NPP_URLNotify];
} else {
WebBaseNetscapePluginView *view = pluginView;
plugin = NULL;
NPP_NewStream = NULL;
NPP_WriteReady = NULL;
NPP_Write = NULL;
NPP_StreamAsFile = NULL;
NPP_DestroyStream = NULL;
NPP_URLNotify = NULL;
pluginView = nil;
[view disconnectStream:self];
[view release];
}
}
- (void)setMIMEType:(NSString *)theMIMEType
{
[theMIMEType retain];
[MIMEType release];
MIMEType = theMIMEType;
}
- (void)startStreamResponseURL:(NSURL *)URL
expectedContentLength:(long long)expectedContentLength
lastModifiedDate:(NSDate *)lastModifiedDate
MIMEType:(NSString *)theMIMEType
headers:(NSData *)theHeaders
{
ASSERT(!isTerminated);
[self setResponseURL:URL];
[self setMIMEType:theMIMEType];
free((void *)stream.url);
stream.url = strdup([responseURL _web_URLCString]);
stream.ndata = self;
stream.end = expectedContentLength > 0 ? (uint32)expectedContentLength : 0;
stream.lastmodified = (uint32)[lastModifiedDate timeIntervalSince1970];
stream.notifyData = notifyData;
if (theHeaders) {
unsigned len = [theHeaders length];
headers = (char*) malloc(len + 1);
[theHeaders getBytes:headers];
headers[len] = 0;
stream.headers = headers;
}
transferMode = NP_NORMAL;
offset = 0;
reason = WEB_REASON_NONE;
// FIXME: If WebNetscapePluginStream called our initializer we wouldn't have to do this here.
fileDescriptor = -1;
// FIXME: Need a way to check if stream is seekable
WebBaseNetscapePluginView *pv = pluginView;
[pv willCallPlugInFunction];
NPError npErr = NPP_NewStream(plugin, (char *)[MIMEType UTF8String], &stream, NO, &transferMode);
[pv didCallPlugInFunction];
LOG(Plugins, "NPP_NewStream URL=%@ MIME=%@ error=%d", responseURL, MIMEType, npErr);
if (npErr != NPERR_NO_ERROR) {
LOG_ERROR("NPP_NewStream failed with error: %d responseURL: %@", npErr, responseURL);
// Calling cancelLoadWithError: cancels the load, but doesn't call NPP_DestroyStream.
[self cancelLoadWithError:[self _pluginCancelledConnectionError]];
return;
}
switch (transferMode) {
case NP_NORMAL:
LOG(Plugins, "Stream type: NP_NORMAL");
break;
case NP_ASFILEONLY:
LOG(Plugins, "Stream type: NP_ASFILEONLY");
break;
case NP_ASFILE:
LOG(Plugins, "Stream type: NP_ASFILE");
break;
case NP_SEEK:
LOG_ERROR("Stream type: NP_SEEK not yet supported");
[self cancelLoadAndDestroyStreamWithError:[self _pluginCancelledConnectionError]];
break;
default:
LOG_ERROR("unknown stream type");
}
}
- (void)startStreamWithResponse:(NSURLResponse *)r
{
NSMutableData *theHeaders = nil;
long long expectedContentLength = [r expectedContentLength];
if ([r isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)r;
theHeaders = [NSMutableData dataWithCapacity:1024];
// FIXME: it would be nice to be able to get the raw HTTP header block.
// This includes the HTTP version, the real status text,
// all headers in their original order and including duplicates,
// and all original bytes verbatim, rather than sent through Unicode translation.
// Unfortunately NSHTTPURLResponse doesn't provide access at that low a level.
[theHeaders appendBytes:"HTTP " length:5];
char statusStr[10];
long statusCode = [httpResponse statusCode];
snprintf(statusStr, sizeof(statusStr), "%ld", statusCode);
[theHeaders appendBytes:statusStr length:strlen(statusStr)];
[theHeaders appendBytes:" OK\n" length:4];
// HACK: pass the headers through as UTF-8.
// This is not the intended behavior; we're supposed to pass original bytes verbatim.
// But we don't have the original bytes, we have NSStrings built by the URL loading system.
// It hopefully shouldn't matter, since RFC2616/RFC822 require ASCII-only headers,
// but surely someone out there is using non-ASCII characters, and hopefully UTF-8 is adequate here.
// It seems better than NSASCIIStringEncoding, which will lose information if non-ASCII is used.
NSDictionary *headerDict = [httpResponse allHeaderFields];
NSArray *keys = [[headerDict allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
NSEnumerator *i = [keys objectEnumerator];
NSString *k;
while ((k = [i nextObject]) != nil) {
NSString *v = [headerDict objectForKey:k];
[theHeaders appendData:[k dataUsingEncoding:NSUTF8StringEncoding]];
[theHeaders appendBytes:": " length:2];
[theHeaders appendData:[v dataUsingEncoding:NSUTF8StringEncoding]];
[theHeaders appendBytes:"\n" length:1];
}
// If the content is encoded (most likely compressed), then don't send its length to the plugin,
// which is only interested in the decoded length, not yet known at the moment.
// <rdar://problem/4470599> tracks a request for -[NSURLResponse expectedContentLength] to incorporate this logic.
NSString *contentEncoding = (NSString *)[[(NSHTTPURLResponse *)r allHeaderFields] objectForKey:@"Content-Encoding"];
if (contentEncoding && ![contentEncoding isEqualToString:@"identity"])
expectedContentLength = -1;
// startStreamResponseURL:... will null-terminate.
}
[self startStreamResponseURL:[r URL]
expectedContentLength:expectedContentLength
lastModifiedDate:WKGetNSURLResponseLastModifiedDate(r)
MIMEType:[r MIMEType]
headers:theHeaders];
}
- (void)_destroyStream
{
if (isTerminated)
return;
[self retain];
ASSERT(reason != WEB_REASON_NONE);
ASSERT([deliveryData length] == 0);
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_deliverData) object:nil];
if (stream.ndata != nil) {
if (reason == NPRES_DONE && (transferMode == NP_ASFILE || transferMode == NP_ASFILEONLY)) {
ASSERT(fileDescriptor == -1);
ASSERT(path != NULL);
NSString *carbonPath = CarbonPathFromPOSIXPath(path);
ASSERT(carbonPath != NULL);
WebBaseNetscapePluginView *pv = pluginView;
[pv willCallPlugInFunction];
NPP_StreamAsFile(plugin, &stream, [carbonPath fileSystemRepresentation]);
[pv didCallPlugInFunction];
LOG(Plugins, "NPP_StreamAsFile responseURL=%@ path=%s", responseURL, carbonPath);
}
if (path) {
// Delete the file after calling NPP_StreamAsFile(), instead of in -dealloc/-finalize. It should be OK
// to delete the file here -- NPP_StreamAsFile() is always called immediately before NPP_DestroyStream()
// (the stream destruction function), so there can be no expectation that a plugin will read the stream
// file asynchronously after NPP_StreamAsFile() is called.
unlink([path fileSystemRepresentation]);
[path release];
path = nil;
if (isTerminated)
goto exit;
}
if (fileDescriptor != -1) {
// The file may still be open if we are destroying the stream before it completed loading.
close(fileDescriptor);
fileDescriptor = -1;
}
NPError npErr;
WebBaseNetscapePluginView *pv = pluginView;
[pv willCallPlugInFunction];
npErr = NPP_DestroyStream(plugin, &stream, reason);
[pv didCallPlugInFunction];
LOG(Plugins, "NPP_DestroyStream responseURL=%@ error=%d", responseURL, npErr);
free(headers);
headers = NULL;
stream.headers = NULL;
stream.ndata = nil;
if (isTerminated)
goto exit;
}
if (sendNotification) {
// NPP_URLNotify expects the request URL, not the response URL.
WebBaseNetscapePluginView *pv = pluginView;
[pv willCallPlugInFunction];
NPP_URLNotify(plugin, [requestURL _web_URLCString], reason, notifyData);
[pv didCallPlugInFunction];
LOG(Plugins, "NPP_URLNotify requestURL=%@ reason=%d", requestURL, reason);
}
isTerminated = YES;
[self setPlugin:NULL];
exit:
[self release];
}
- (void)_destroyStreamWithReason:(NPReason)theReason
{
reason = theReason;
if (reason != NPRES_DONE) {
// Stop any pending data from being streamed.
[deliveryData setLength:0];
} else if ([deliveryData length] > 0) {
// There is more data to be streamed, don't destroy the stream now.
return;
}
[self _destroyStream];
ASSERT(stream.ndata == nil);
}
- (void)cancelLoadWithError:(NSError *)error
{
// Overridden by subclasses.
ASSERT_NOT_REACHED();
}
- (void)destroyStreamWithError:(NSError *)error
{
[self _destroyStreamWithReason:[[self class] reasonForError:error]];
}
- (void)cancelLoadAndDestroyStreamWithError:(NSError *)error
{
[self retain];
[self cancelLoadWithError:error];
[self destroyStreamWithError:error];
[self setPlugin:NULL];
[self release];
}
- (void)_deliverData
{
if (!stream.ndata || [deliveryData length] == 0)
return;
[self retain];
int32 totalBytes = [deliveryData length];
int32 totalBytesDelivered = 0;
while (totalBytesDelivered < totalBytes) {
WebBaseNetscapePluginView *pv = pluginView;
[pv willCallPlugInFunction];
int32 deliveryBytes = NPP_WriteReady(plugin, &stream);
[pv didCallPlugInFunction];
LOG(Plugins, "NPP_WriteReady responseURL=%@ bytes=%d", responseURL, deliveryBytes);
if (isTerminated)
goto exit;
if (deliveryBytes <= 0) {
// Plug-in can't receive anymore data right now. Send it later.
[self performSelector:@selector(_deliverData) withObject:nil afterDelay:0];
break;
} else {
deliveryBytes = MIN(deliveryBytes, totalBytes - totalBytesDelivered);
NSData *subdata = [deliveryData subdataWithRange:NSMakeRange(totalBytesDelivered, deliveryBytes)];
pv = pluginView;
[pv willCallPlugInFunction];
deliveryBytes = NPP_Write(plugin, &stream, offset, [subdata length], (void *)[subdata bytes]);
[pv didCallPlugInFunction];
if (deliveryBytes < 0) {
// Netscape documentation says that a negative result from NPP_Write means cancel the load.
[self cancelLoadAndDestroyStreamWithError:[self _pluginCancelledConnectionError]];
return;
}
deliveryBytes = MIN((unsigned)deliveryBytes, [subdata length]);
offset += deliveryBytes;
totalBytesDelivered += deliveryBytes;
LOG(Plugins, "NPP_Write responseURL=%@ bytes=%d total-delivered=%d/%d", responseURL, deliveryBytes, offset, stream.end);
}
}
if (totalBytesDelivered > 0) {
if (totalBytesDelivered < totalBytes) {
NSMutableData *newDeliveryData = [[NSMutableData alloc] initWithCapacity:totalBytes - totalBytesDelivered];
[newDeliveryData appendBytes:(char *)[deliveryData bytes] + totalBytesDelivered length:totalBytes - totalBytesDelivered];
[deliveryData release];
deliveryData = newDeliveryData;
} else {
[deliveryData setLength:0];
if (reason != WEB_REASON_NONE) {
[self _destroyStream];
}
}
}
exit:
[self release];
}
- (void)_deliverDataToFile:(NSData *)data
{
if (fileDescriptor == -1 && !path) {
NSString *temporaryFileMask = [NSTemporaryDirectory() stringByAppendingPathComponent:@"WebKitPlugInStreamXXXXXX"];
char *temporaryFileName = strdup([temporaryFileMask fileSystemRepresentation]);
fileDescriptor = mkstemp(temporaryFileName);
if (fileDescriptor == -1) {
LOG_ERROR("Can't create a temporary file.");
// This is not a network error, but the only error codes are "network error" and "user break".
[self _destroyStreamWithReason:NPRES_NETWORK_ERR];
free(temporaryFileName);
return;
}
path = [[NSString stringWithUTF8String:temporaryFileName] retain];
free(temporaryFileName);
}
int dataLength = [data length];
if (!dataLength)
return;
int byteCount = write(fileDescriptor, [data bytes], dataLength);
if (byteCount != dataLength) {
// This happens only rarely, when we are out of disk space or have a disk I/O error.
LOG_ERROR("error writing to temporary file, errno %d", errno);
close(fileDescriptor);
fileDescriptor = -1;
// This is not a network error, but the only error codes are "network error" and "user break".
[self _destroyStreamWithReason:NPRES_NETWORK_ERR];
[path release];
path = nil;
}
}
- (void)finishedLoading
{
if (!stream.ndata)
return;
if (transferMode == NP_ASFILE || transferMode == NP_ASFILEONLY) {
// Fake the delivery of an empty data to ensure that the file has been created
[self _deliverDataToFile:[NSData data]];
if (fileDescriptor != -1)
close(fileDescriptor);
fileDescriptor = -1;
}
[self _destroyStreamWithReason:NPRES_DONE];
}
- (void)receivedData:(NSData *)data
{
ASSERT([data length] > 0);
if (transferMode != NP_ASFILEONLY) {
if (!deliveryData) {
deliveryData = [[NSMutableData alloc] initWithCapacity:[data length]];
}
[deliveryData appendData:data];
[self _deliverData];
}
if (transferMode == NP_ASFILE || transferMode == NP_ASFILEONLY)
[self _deliverDataToFile:data];
}
@end
static NSString *CarbonPathFromPOSIXPath(NSString *posixPath)
{
// Doesn't add a trailing colon for directories; this is a problem for paths to a volume,
// so this function would need to be revised if we ever wanted to call it with that.
CFURLRef url = (CFURLRef)[NSURL fileURLWithPath:posixPath];
if (!url)
return nil;
return WebCFAutorelease(CFURLCopyFileSystemPath(url, kCFURLHFSPathStyle));
}
#endif
|