Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(324)

Side by Side Diff: Source/core/xml/XMLHttpRequest.cpp

Issue 346033003: [XHR] Move bools to end of class declaration for better padding (Closed) Base URL: https://chromium.googlesource.com/chromium/blink.git@master
Patch Set: Created 6 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* 1 /*
2 * Copyright (C) 2004, 2006, 2008 Apple Inc. All rights reserved. 2 * Copyright (C) 2004, 2006, 2008 Apple Inc. All rights reserved.
3 * Copyright (C) 2005-2007 Alexey Proskuryakov <ap@webkit.org> 3 * Copyright (C) 2005-2007 Alexey Proskuryakov <ap@webkit.org>
4 * Copyright (C) 2007, 2008 Julien Chaffraix <jchaffraix@webkit.org> 4 * Copyright (C) 2007, 2008 Julien Chaffraix <jchaffraix@webkit.org>
5 * Copyright (C) 2008, 2011 Google Inc. All rights reserved. 5 * Copyright (C) 2008, 2011 Google Inc. All rights reserved.
6 * Copyright (C) 2012 Intel Corporation 6 * Copyright (C) 2012 Intel Corporation
7 * 7 *
8 * This library is free software; you can redistribute it and/or 8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public 9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either 10 * License as published by the Free Software Foundation; either
(...skipping 149 matching lines...) Expand 10 before | Expand all | Expand 10 after
160 PassRefPtrWillBeRawPtr<XMLHttpRequest> XMLHttpRequest::create(ExecutionContext* context, PassRefPtr<SecurityOrigin> securityOrigin) 160 PassRefPtrWillBeRawPtr<XMLHttpRequest> XMLHttpRequest::create(ExecutionContext* context, PassRefPtr<SecurityOrigin> securityOrigin)
161 { 161 {
162 RefPtrWillBeRawPtr<XMLHttpRequest> xmlHttpRequest = adoptRefWillBeRefCounted GarbageCollected(new XMLHttpRequest(context, securityOrigin)); 162 RefPtrWillBeRawPtr<XMLHttpRequest> xmlHttpRequest = adoptRefWillBeRefCounted GarbageCollected(new XMLHttpRequest(context, securityOrigin));
163 xmlHttpRequest->suspendIfNeeded(); 163 xmlHttpRequest->suspendIfNeeded();
164 164
165 return xmlHttpRequest.release(); 165 return xmlHttpRequest.release();
166 } 166 }
167 167
168 XMLHttpRequest::XMLHttpRequest(ExecutionContext* context, PassRefPtr<SecurityOri gin> securityOrigin) 168 XMLHttpRequest::XMLHttpRequest(ExecutionContext* context, PassRefPtr<SecurityOri gin> securityOrigin)
169 : ActiveDOMObject(context) 169 : ActiveDOMObject(context)
170 , m_async(true) 170 , m_xhrFlags(0)
171 , m_includeCredentials(false)
172 , m_timeoutMilliseconds(0) 171 , m_timeoutMilliseconds(0)
173 , m_state(UNSENT) 172 , m_state(UNSENT)
174 , m_createdDocument(false)
175 , m_downloadedBlobLength(0) 173 , m_downloadedBlobLength(0)
176 , m_error(false)
177 , m_uploadEventsAllowed(true)
178 , m_uploadComplete(false)
179 , m_sameOriginRequest(true)
180 , m_receivedLength(0) 174 , m_receivedLength(0)
181 , m_lastSendLineNumber(0) 175 , m_lastSendLineNumber(0)
182 , m_exceptionCode(0) 176 , m_exceptionCode(0)
183 , m_progressEventThrottle(this) 177 , m_progressEventThrottle(this)
184 , m_responseTypeCode(ResponseTypeDefault) 178 , m_responseTypeCode(ResponseTypeDefault)
185 , m_dropProtectionRunner(this, &XMLHttpRequest::dropProtection) 179 , m_dropProtectionRunner(this, &XMLHttpRequest::dropProtection)
186 , m_securityOrigin(securityOrigin) 180 , m_securityOrigin(securityOrigin)
187 { 181 {
182 // Set default values.
183 m_xhrFlags = IsAsync | IsUploadEventsAllowed | IsSameOriginRequest;
Inactive 2014/06/21 00:40:41 Why isn't this done in the initializer list?
maheshkk 2014/06/23 18:32:16 Done.
184
188 initializeXMLHttpRequestStaticData(); 185 initializeXMLHttpRequestStaticData();
189 #ifndef NDEBUG 186 #ifndef NDEBUG
190 xmlHttpRequestCounter.increment(); 187 xmlHttpRequestCounter.increment();
191 #endif 188 #endif
192 ScriptWrappable::init(this); 189 ScriptWrappable::init(this);
193 } 190 }
194 191
195 XMLHttpRequest::~XMLHttpRequest() 192 XMLHttpRequest::~XMLHttpRequest()
196 { 193 {
197 #ifndef NDEBUG 194 #ifndef NDEBUG
(...skipping 16 matching lines...) Expand all
214 { 211 {
215 return m_state; 212 return m_state;
216 } 213 }
217 214
218 ScriptString XMLHttpRequest::responseText(ExceptionState& exceptionState) 215 ScriptString XMLHttpRequest::responseText(ExceptionState& exceptionState)
219 { 216 {
220 if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != Respo nseTypeText) { 217 if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != Respo nseTypeText) {
221 exceptionState.throwDOMException(InvalidStateError, "The value is only a ccessible if the object's 'responseType' is '' or 'text' (was '" + responseType( ) + "')."); 218 exceptionState.throwDOMException(InvalidStateError, "The value is only a ccessible if the object's 'responseType' is '' or 'text' (was '" + responseType( ) + "').");
222 return ScriptString(); 219 return ScriptString();
223 } 220 }
224 if (m_error || (m_state != LOADING && m_state != DONE)) 221 if (getFlag(HasError) || (m_state != LOADING && m_state != DONE))
225 return ScriptString(); 222 return ScriptString();
226 return m_responseText; 223 return m_responseText;
227 } 224 }
228 225
229 ScriptString XMLHttpRequest::responseJSONSource() 226 ScriptString XMLHttpRequest::responseJSONSource()
230 { 227 {
231 ASSERT(m_responseTypeCode == ResponseTypeJSON); 228 ASSERT(m_responseTypeCode == ResponseTypeJSON);
232 229
233 if (m_error || m_state != DONE) 230 if (getFlag(HasError) || m_state != DONE)
234 return ScriptString(); 231 return ScriptString();
235 return m_responseText; 232 return m_responseText;
236 } 233 }
237 234
238 Document* XMLHttpRequest::responseXML(ExceptionState& exceptionState) 235 Document* XMLHttpRequest::responseXML(ExceptionState& exceptionState)
239 { 236 {
240 if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != Respo nseTypeDocument) { 237 if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != Respo nseTypeDocument) {
241 exceptionState.throwDOMException(InvalidStateError, "The value is only a ccessible if the object's 'responseType' is '' or 'document' (was '" + responseT ype() + "')."); 238 exceptionState.throwDOMException(InvalidStateError, "The value is only a ccessible if the object's 'responseType' is '' or 'document' (was '" + responseT ype() + "').");
242 return 0; 239 return 0;
243 } 240 }
244 241
245 if (m_error || m_state != DONE) 242 if (getFlag(HasError) || m_state != DONE)
246 return 0; 243 return 0;
247 244
248 if (!m_createdDocument) { 245 if (!getFlag(IsDocumentCreated)) {
249 AtomicString mimeType = responseMIMEType(); 246 AtomicString mimeType = responseMIMEType();
250 bool isHTML = equalIgnoringCase(mimeType, "text/html"); 247 bool isHTML = equalIgnoringCase(mimeType, "text/html");
251 248
252 // The W3C spec requires the final MIME type to be some valid XML type, or text/html. 249 // The W3C spec requires the final MIME type to be some valid XML type, or text/html.
253 // If it is text/html, then the responseType of "document" must have bee n supplied explicitly. 250 // If it is text/html, then the responseType of "document" must have bee n supplied explicitly.
254 if ((m_response.isHTTP() && !responseIsXML() && !isHTML) 251 if ((m_response.isHTTP() && !responseIsXML() && !isHTML)
255 || (isHTML && m_responseTypeCode == ResponseTypeDefault) 252 || (isHTML && m_responseTypeCode == ResponseTypeDefault)
256 || executionContext()->isWorkerGlobalScope()) { 253 || executionContext()->isWorkerGlobalScope()) {
257 m_responseDocument = nullptr; 254 m_responseDocument = nullptr;
258 } else { 255 } else {
259 DocumentInit init = DocumentInit::fromContext(document()->contextDoc ument(), m_url); 256 DocumentInit init = DocumentInit::fromContext(document()->contextDoc ument(), m_url);
260 if (isHTML) 257 if (isHTML)
261 m_responseDocument = HTMLDocument::create(init); 258 m_responseDocument = HTMLDocument::create(init);
262 else 259 else
263 m_responseDocument = XMLDocument::create(init); 260 m_responseDocument = XMLDocument::create(init);
264 // FIXME: Set Last-Modified. 261 // FIXME: Set Last-Modified.
265 m_responseDocument->setContent(m_responseText.flattenToString()); 262 m_responseDocument->setContent(m_responseText.flattenToString());
266 m_responseDocument->setSecurityOrigin(securityOrigin()); 263 m_responseDocument->setSecurityOrigin(securityOrigin());
267 m_responseDocument->setContextFeatures(document()->contextFeatures() ); 264 m_responseDocument->setContextFeatures(document()->contextFeatures() );
268 m_responseDocument->setMimeType(mimeType); 265 m_responseDocument->setMimeType(mimeType);
269 if (!m_responseDocument->wellFormed()) 266 if (!m_responseDocument->wellFormed())
270 m_responseDocument = nullptr; 267 m_responseDocument = nullptr;
271 } 268 }
272 m_createdDocument = true; 269 setFlag(IsDocumentCreated);
273 } 270 }
274 271
275 return m_responseDocument.get(); 272 return m_responseDocument.get();
276 } 273 }
277 274
278 Blob* XMLHttpRequest::responseBlob() 275 Blob* XMLHttpRequest::responseBlob()
279 { 276 {
280 ASSERT(m_responseTypeCode == ResponseTypeBlob); 277 ASSERT(m_responseTypeCode == ResponseTypeBlob);
281 ASSERT(!m_binaryResponseBuilder.get()); 278 ASSERT(!m_binaryResponseBuilder.get());
282 279
283 // We always return null before DONE. 280 // We always return null before DONE.
284 if (m_error || m_state != DONE) 281 if (getFlag(HasError) || m_state != DONE)
285 return 0; 282 return 0;
286 283
287 if (!m_responseBlob) { 284 if (!m_responseBlob) {
288 // When responseType is set to "blob", we redirect the downloaded data 285 // When responseType is set to "blob", we redirect the downloaded data
289 // to a file-handle directly in the browser process. We get the 286 // to a file-handle directly in the browser process. We get the
290 // file-path from the ResourceResponse directly instead of copying the 287 // file-path from the ResourceResponse directly instead of copying the
291 // bytes between the browser and the renderer. 288 // bytes between the browser and the renderer.
292 OwnPtr<BlobData> blobData = BlobData::create(); 289 OwnPtr<BlobData> blobData = BlobData::create();
293 String filePath = m_response.downloadedFilePath(); 290 String filePath = m_response.downloadedFilePath();
294 // If we errored out or got no data, we still return a blob, just an 291 // If we errored out or got no data, we still return a blob, just an
295 // empty one. 292 // empty one.
296 if (!filePath.isEmpty() && m_downloadedBlobLength) { 293 if (!filePath.isEmpty() && m_downloadedBlobLength) {
297 blobData->appendFile(filePath); 294 blobData->appendFile(filePath);
298 blobData->setContentType(responseMIMEType()); // responseMIMEType de faults to text/xml which may be incorrect. 295 blobData->setContentType(responseMIMEType()); // responseMIMEType de faults to text/xml which may be incorrect.
299 } 296 }
300 m_responseBlob = Blob::create(BlobDataHandle::create(blobData.release(), m_downloadedBlobLength)); 297 m_responseBlob = Blob::create(BlobDataHandle::create(blobData.release(), m_downloadedBlobLength));
301 } 298 }
302 299
303 return m_responseBlob.get(); 300 return m_responseBlob.get();
304 } 301 }
305 302
306 ArrayBuffer* XMLHttpRequest::responseArrayBuffer() 303 ArrayBuffer* XMLHttpRequest::responseArrayBuffer()
307 { 304 {
308 ASSERT(m_responseTypeCode == ResponseTypeArrayBuffer); 305 ASSERT(m_responseTypeCode == ResponseTypeArrayBuffer);
309 306
310 if (m_error || m_state != DONE) 307 if (getFlag(HasError) || m_state != DONE)
311 return 0; 308 return 0;
312 309
313 if (!m_responseArrayBuffer.get()) { 310 if (!m_responseArrayBuffer.get()) {
314 if (m_binaryResponseBuilder.get() && m_binaryResponseBuilder->size() > 0 ) { 311 if (m_binaryResponseBuilder.get() && m_binaryResponseBuilder->size() > 0 ) {
315 m_responseArrayBuffer = m_binaryResponseBuilder->getAsArrayBuffer(); 312 m_responseArrayBuffer = m_binaryResponseBuilder->getAsArrayBuffer();
316 if (!m_responseArrayBuffer) { 313 if (!m_responseArrayBuffer) {
317 // m_binaryResponseBuilder failed to allocate an ArrayBuffer. 314 // m_binaryResponseBuilder failed to allocate an ArrayBuffer.
318 // We need to crash the renderer since there's no way defined in 315 // We need to crash the renderer since there's no way defined in
319 // the spec to tell this to the user. 316 // the spec to tell this to the user.
320 CRASH(); 317 CRASH();
321 } 318 }
322 m_binaryResponseBuilder.clear(); 319 m_binaryResponseBuilder.clear();
323 } else { 320 } else {
324 m_responseArrayBuffer = ArrayBuffer::create(static_cast<void*>(0), 0 ); 321 m_responseArrayBuffer = ArrayBuffer::create(static_cast<void*>(0), 0 );
325 } 322 }
326 } 323 }
327 324
328 return m_responseArrayBuffer.get(); 325 return m_responseArrayBuffer.get();
329 } 326 }
330 327
331 Stream* XMLHttpRequest::responseStream() 328 Stream* XMLHttpRequest::responseStream()
332 { 329 {
333 ASSERT(m_responseTypeCode == ResponseTypeStream); 330 ASSERT(m_responseTypeCode == ResponseTypeStream);
334 331
335 if (m_error || (m_state != LOADING && m_state != DONE)) 332 if (getFlag(HasError) || (m_state != LOADING && m_state != DONE))
336 return 0; 333 return 0;
337 334
338 return m_responseStream.get(); 335 return m_responseStream.get();
339 } 336 }
340 337
341 void XMLHttpRequest::setTimeout(unsigned long timeout, ExceptionState& exception State) 338 void XMLHttpRequest::setTimeout(unsigned long timeout, ExceptionState& exception State)
342 { 339 {
343 // FIXME: Need to trigger or update the timeout Timer here, if needed. http: //webkit.org/b/98156 340 // FIXME: Need to trigger or update the timeout Timer here, if needed. http: //webkit.org/b/98156
344 // XHR2 spec, 4.7.3. "This implies that the timeout attribute can be set whi le fetching is in progress. If that occurs it will still be measured relative to the start of fetching." 341 // XHR2 spec, 4.7.3. "This implies that the timeout attribute can be set whi le fetching is in progress. If that occurs it will still be measured relative to the start of fetching."
345 if (executionContext()->isDocument() && !m_async) { 342 if (executionContext()->isDocument() && !getFlag(IsAsync)) {
346 exceptionState.throwDOMException(InvalidAccessError, "Timeouts cannot be set for synchronous requests made from a document."); 343 exceptionState.throwDOMException(InvalidAccessError, "Timeouts cannot be set for synchronous requests made from a document.");
347 return; 344 return;
348 } 345 }
349 m_timeoutMilliseconds = timeout; 346 m_timeoutMilliseconds = timeout;
350 } 347 }
351 348
352 void XMLHttpRequest::setResponseType(const String& responseType, ExceptionState& exceptionState) 349 void XMLHttpRequest::setResponseType(const String& responseType, ExceptionState& exceptionState)
353 { 350 {
354 if (m_state >= LOADING) { 351 if (m_state >= LOADING) {
355 exceptionState.throwDOMException(InvalidStateError, "The response type c annot be set if the object's state is LOADING or DONE."); 352 exceptionState.throwDOMException(InvalidStateError, "The response type c annot be set if the object's state is LOADING or DONE.");
356 return; 353 return;
357 } 354 }
358 355
359 // Newer functionality is not available to synchronous requests in window co ntexts, as a spec-mandated 356 // Newer functionality is not available to synchronous requests in window co ntexts, as a spec-mandated
360 // attempt to discourage synchronous XHR use. responseType is one such piece of functionality. 357 // attempt to discourage synchronous XHR use. responseType is one such piece of functionality.
361 if (!m_async && executionContext()->isDocument()) { 358 if (!getFlag(IsAsync) && executionContext()->isDocument()) {
362 exceptionState.throwDOMException(InvalidAccessError, "The response type can only be changed for asynchronous HTTP requests made from a document."); 359 exceptionState.throwDOMException(InvalidAccessError, "The response type can only be changed for asynchronous HTTP requests made from a document.");
363 return; 360 return;
364 } 361 }
365 362
366 if (responseType == "") { 363 if (responseType == "") {
367 m_responseTypeCode = ResponseTypeDefault; 364 m_responseTypeCode = ResponseTypeDefault;
368 } else if (responseType == "text") { 365 } else if (responseType == "text") {
369 m_responseTypeCode = ResponseTypeText; 366 m_responseTypeCode = ResponseTypeText;
370 } else if (responseType == "json") { 367 } else if (responseType == "json") {
371 m_responseTypeCode = ResponseTypeJSON; 368 m_responseTypeCode = ResponseTypeJSON;
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
415 { 412 {
416 if (!m_upload) 413 if (!m_upload)
417 m_upload = XMLHttpRequestUpload::create(this); 414 m_upload = XMLHttpRequestUpload::create(this);
418 return m_upload.get(); 415 return m_upload.get();
419 } 416 }
420 417
421 void XMLHttpRequest::trackProgress(int length) 418 void XMLHttpRequest::trackProgress(int length)
422 { 419 {
423 m_receivedLength += length; 420 m_receivedLength += length;
424 421
425 if (m_async) 422 if (getFlag(IsAsync))
426 dispatchProgressEventFromSnapshot(EventTypeNames::progress); 423 dispatchProgressEventFromSnapshot(EventTypeNames::progress);
427 424
428 if (m_state != LOADING) { 425 if (m_state != LOADING) {
429 changeState(LOADING); 426 changeState(LOADING);
430 } else { 427 } else {
431 // Firefox calls readyStateChanged every time it receives data. Do 428 // Firefox calls readyStateChanged every time it receives data. Do
432 // the same to align with Firefox. 429 // the same to align with Firefox.
433 // 430 //
434 // FIXME: Make our implementation and the spec consistent. This 431 // FIXME: Make our implementation and the spec consistent. This
435 // behavior was needed when the progress event was not available. 432 // behavior was needed when the progress event was not available.
436 dispatchReadyStateChangeEvent(); 433 dispatchReadyStateChangeEvent();
437 } 434 }
438 } 435 }
439 436
440 void XMLHttpRequest::changeState(State newState) 437 void XMLHttpRequest::changeState(State newState)
441 { 438 {
442 if (m_state != newState) { 439 if (m_state != newState) {
443 m_state = newState; 440 m_state = newState;
444 dispatchReadyStateChangeEvent(); 441 dispatchReadyStateChangeEvent();
445 } 442 }
446 } 443 }
447 444
448 void XMLHttpRequest::dispatchReadyStateChangeEvent() 445 void XMLHttpRequest::dispatchReadyStateChangeEvent()
449 { 446 {
450 if (!executionContext()) 447 if (!executionContext())
451 return; 448 return;
452 449
453 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispat chXHRReadyStateChangeEvent(executionContext(), this); 450 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispat chXHRReadyStateChangeEvent(executionContext(), this);
454 451
455 if (m_async || (m_state <= OPENED || m_state == DONE)) { 452 if (getFlag(IsAsync) || (m_state <= OPENED || m_state == DONE)) {
456 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "XHRReadySt ateChange", "data", InspectorXhrReadyStateChangeEvent::data(executionContext(), this)); 453 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "XHRReadySt ateChange", "data", InspectorXhrReadyStateChangeEvent::data(executionContext(), this));
457 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack" ), "CallStack", "stack", InspectorCallStackEvent::currentCallStack()); 454 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack" ), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
458 ProgressEventAction flushAction = DoNotFlushProgressEvent; 455 ProgressEventAction flushAction = DoNotFlushProgressEvent;
459 if (m_state == DONE) { 456 if (m_state == DONE) {
460 if (m_error) 457 if (getFlag(HasError))
461 flushAction = FlushDeferredProgressEvent; 458 flushAction = FlushDeferredProgressEvent;
462 else 459 else
463 flushAction = FlushProgressEvent; 460 flushAction = FlushProgressEvent;
464 } 461 }
465 m_progressEventThrottle.dispatchReadyStateChangeEvent(XMLHttpRequestProg ressEvent::create(EventTypeNames::readystatechange), flushAction); 462 m_progressEventThrottle.dispatchReadyStateChangeEvent(XMLHttpRequestProg ressEvent::create(EventTypeNames::readystatechange), flushAction);
466 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "Up dateCounters", "data", InspectorUpdateCountersEvent::data()); 463 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "Up dateCounters", "data", InspectorUpdateCountersEvent::data());
467 } 464 }
468 465
469 InspectorInstrumentation::didDispatchXHRReadyStateChangeEvent(cookie); 466 InspectorInstrumentation::didDispatchXHRReadyStateChangeEvent(cookie);
470 if (m_state == DONE && !m_error) { 467 if (m_state == DONE && !getFlag(HasError)) {
471 { 468 {
472 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "XHRLoa d", "data", InspectorXhrLoadEvent::data(executionContext(), this)); 469 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "XHRLoa d", "data", InspectorXhrLoadEvent::data(executionContext(), this));
473 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.st ack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack()); 470 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.st ack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
474 InspectorInstrumentationCookie cookie = InspectorInstrumentation::wi llDispatchXHRLoadEvent(executionContext(), this); 471 InspectorInstrumentationCookie cookie = InspectorInstrumentation::wi llDispatchXHRLoadEvent(executionContext(), this);
475 dispatchProgressEventFromSnapshot(EventTypeNames::load); 472 dispatchProgressEventFromSnapshot(EventTypeNames::load);
476 InspectorInstrumentation::didDispatchXHRLoadEvent(cookie); 473 InspectorInstrumentation::didDispatchXHRLoadEvent(cookie);
477 } 474 }
478 dispatchProgressEventFromSnapshot(EventTypeNames::loadend); 475 dispatchProgressEventFromSnapshot(EventTypeNames::loadend);
479 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "Up dateCounters", "data", InspectorUpdateCountersEvent::data()); 476 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "Up dateCounters", "data", InspectorUpdateCountersEvent::data());
480 } 477 }
481 } 478 }
482 479
483 void XMLHttpRequest::setWithCredentials(bool value, ExceptionState& exceptionSta te) 480 void XMLHttpRequest::setWithCredentials(bool value, ExceptionState& exceptionSta te)
484 { 481 {
485 if (m_state > OPENED || m_loader) { 482 if (m_state > OPENED || m_loader) {
486 exceptionState.throwDOMException(InvalidStateError, "The value may only be set if the object's state is UNSENT or OPENED."); 483 exceptionState.throwDOMException(InvalidStateError, "The value may only be set if the object's state is UNSENT or OPENED.");
487 return; 484 return;
488 } 485 }
489 486
490 // FIXME: According to XMLHttpRequest Level 2 we should throw InvalidAccessE rror exception here. 487 // FIXME: According to XMLHttpRequest Level 2 we should throw InvalidAccessE rror exception here.
491 // However for time being only print warning message to warn web developers. 488 // However for time being only print warning message to warn web developers.
492 if (!m_async) 489 if (!getFlag(IsAsync))
493 UseCounter::countDeprecation(executionContext(), UseCounter::SyncXHRWith Credentials); 490 UseCounter::countDeprecation(executionContext(), UseCounter::SyncXHRWith Credentials);
494 491
495 m_includeCredentials = value; 492 setFlag(value, IsWithCredentials);
496 } 493 }
497 494
498 bool XMLHttpRequest::isAllowedHTTPMethod(const String& method) 495 bool XMLHttpRequest::isAllowedHTTPMethod(const String& method)
499 { 496 {
500 return !equalIgnoringCase(method, "TRACE") 497 return !equalIgnoringCase(method, "TRACE")
501 && !equalIgnoringCase(method, "TRACK") 498 && !equalIgnoringCase(method, "TRACK")
502 && !equalIgnoringCase(method, "CONNECT"); 499 && !equalIgnoringCase(method, "CONNECT");
503 } 500 }
504 501
505 AtomicString XMLHttpRequest::uppercaseKnownHTTPMethod(const AtomicString& method ) 502 AtomicString XMLHttpRequest::uppercaseKnownHTTPMethod(const AtomicString& method )
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
538 535
539 void XMLHttpRequest::open(const AtomicString& method, const KURL& url, bool asyn c, ExceptionState& exceptionState) 536 void XMLHttpRequest::open(const AtomicString& method, const KURL& url, bool asyn c, ExceptionState& exceptionState)
540 { 537 {
541 WTF_LOG(Network, "XMLHttpRequest %p open('%s', '%s', %d)", this, method.utf8 ().data(), url.elidedString().utf8().data(), async); 538 WTF_LOG(Network, "XMLHttpRequest %p open('%s', '%s', %d)", this, method.utf8 ().data(), url.elidedString().utf8().data(), async);
542 539
543 if (!internalAbort()) 540 if (!internalAbort())
544 return; 541 return;
545 542
546 State previousState = m_state; 543 State previousState = m_state;
547 m_state = UNSENT; 544 m_state = UNSENT;
548 m_error = false; 545 clearFlag(HasError);
549 m_uploadComplete = false; 546 clearFlag(IsUploadComplete);
550 547
551 // clear stuff from possible previous load 548 // clear stuff from possible previous load
552 clearResponse(); 549 clearResponse();
553 clearRequest(); 550 clearRequest();
554 551
555 ASSERT(m_state == UNSENT); 552 ASSERT(m_state == UNSENT);
556 553
557 if (!isValidHTTPToken(method)) { 554 if (!isValidHTTPToken(method)) {
558 exceptionState.throwDOMException(SyntaxError, "'" + method + "' is not a valid HTTP method."); 555 exceptionState.throwDOMException(SyntaxError, "'" + method + "' is not a valid HTTP method.");
559 return; 556 return;
(...skipping 27 matching lines...) Expand all
587 if (m_timeoutMilliseconds > 0) { 584 if (m_timeoutMilliseconds > 0) {
588 exceptionState.throwDOMException(InvalidAccessError, "Synchronous re quests must not set a timeout."); 585 exceptionState.throwDOMException(InvalidAccessError, "Synchronous re quests must not set a timeout.");
589 return; 586 return;
590 } 587 }
591 } 588 }
592 589
593 m_method = uppercaseKnownHTTPMethod(method); 590 m_method = uppercaseKnownHTTPMethod(method);
594 591
595 m_url = url; 592 m_url = url;
596 593
597 m_async = async; 594 setFlag(async, IsAsync);
598 595
599 ASSERT(!m_loader); 596 ASSERT(!m_loader);
600 597
601 // Check previous state to avoid dispatching readyState event 598 // Check previous state to avoid dispatching readyState event
602 // when calling open several times in a row. 599 // when calling open several times in a row.
603 if (previousState != OPENED) 600 if (previousState != OPENED)
604 changeState(OPENED); 601 changeState(OPENED);
605 else 602 else
606 m_state = OPENED; 603 m_state = OPENED;
607 } 604 }
(...skipping 18 matching lines...) Expand all
626 bool XMLHttpRequest::initSend(ExceptionState& exceptionState) 623 bool XMLHttpRequest::initSend(ExceptionState& exceptionState)
627 { 624 {
628 if (!executionContext()) 625 if (!executionContext())
629 return false; 626 return false;
630 627
631 if (m_state != OPENED || m_loader) { 628 if (m_state != OPENED || m_loader) {
632 exceptionState.throwDOMException(InvalidStateError, "The object's state must be OPENED."); 629 exceptionState.throwDOMException(InvalidStateError, "The object's state must be OPENED.");
633 return false; 630 return false;
634 } 631 }
635 632
636 m_error = false; 633 clearFlag(HasError);
637 return true; 634 return true;
638 } 635 }
639 636
640 void XMLHttpRequest::send(ExceptionState& exceptionState) 637 void XMLHttpRequest::send(ExceptionState& exceptionState)
641 { 638 {
642 send(String(), exceptionState); 639 send(String(), exceptionState);
643 } 640 }
644 641
645 bool XMLHttpRequest::areMethodAndURLValidForSend() 642 bool XMLHttpRequest::areMethodAndURLValidForSend()
646 { 643 {
(...skipping 164 matching lines...) Expand 10 before | Expand all | Expand 10 after
811 // Only GET request is supported for blob URL. 808 // Only GET request is supported for blob URL.
812 if (m_url.protocolIs("blob") && m_method != "GET") { 809 if (m_url.protocolIs("blob") && m_method != "GET") {
813 exceptionState.throwDOMException(NetworkError, "'GET' is the only method allowed for 'blob:' URLs."); 810 exceptionState.throwDOMException(NetworkError, "'GET' is the only method allowed for 'blob:' URLs.");
814 return; 811 return;
815 } 812 }
816 813
817 // The presence of upload event listeners forces us to use preflighting beca use POSTing to an URL that does not 814 // The presence of upload event listeners forces us to use preflighting beca use POSTing to an URL that does not
818 // permit cross origin requests should look exactly like POSTing to an URL t hat does not respond at all. 815 // permit cross origin requests should look exactly like POSTing to an URL t hat does not respond at all.
819 // Also, only async requests support upload progress events. 816 // Also, only async requests support upload progress events.
820 bool uploadEvents = false; 817 bool uploadEvents = false;
821 if (m_async) { 818 if (getFlag(IsAsync)) {
822 dispatchProgressEvent(EventTypeNames::loadstart, 0, 0); 819 dispatchProgressEvent(EventTypeNames::loadstart, 0, 0);
823 if (httpBody && m_upload) { 820 if (httpBody && m_upload) {
824 uploadEvents = m_upload->hasEventListeners(); 821 uploadEvents = m_upload->hasEventListeners();
825 m_upload->dispatchEvent(XMLHttpRequestProgressEvent::create(EventTyp eNames::loadstart)); 822 m_upload->dispatchEvent(XMLHttpRequestProgressEvent::create(EventTyp eNames::loadstart));
826 } 823 }
827 } 824 }
828 825
829 m_sameOriginRequest = securityOrigin()->canRequest(m_url); 826 setFlag(securityOrigin()->canRequest(m_url), IsSameOriginRequest);
830 827
831 // We also remember whether upload events should be allowed for this request in case the upload listeners are 828 // We also remember whether upload events should be allowed for this request in case the upload listeners are
832 // added after the request is started. 829 // added after the request is started.
833 m_uploadEventsAllowed = m_sameOriginRequest || uploadEvents || !isSimpleCros sOriginAccessRequest(m_method, m_requestHeaders); 830 setFlag(getFlag(IsSameOriginRequest) || uploadEvents || !isSimpleCrossOrigin AccessRequest(m_method, m_requestHeaders),
831 IsUploadEventsAllowed);
834 832
835 ASSERT(executionContext()); 833 ASSERT(executionContext());
836 ExecutionContext& executionContext = *this->executionContext(); 834 ExecutionContext& executionContext = *this->executionContext();
837 835
838 ResourceRequest request(m_url); 836 ResourceRequest request(m_url);
839 request.setHTTPMethod(m_method); 837 request.setHTTPMethod(m_method);
840 request.setTargetType(ResourceRequest::TargetIsXHR); 838 request.setTargetType(ResourceRequest::TargetIsXHR);
841 839
842 InspectorInstrumentation::willLoadXHR(&executionContext, this, this, m_metho d, m_url, m_async, httpBody ? httpBody->deepCopy() : nullptr, m_requestHeaders, m_includeCredentials); 840 InspectorInstrumentation::willLoadXHR(&executionContext, this, this, m_metho d, m_url, getFlag(IsAsync), httpBody ? httpBody->deepCopy() : nullptr, m_request Headers, getFlag(IsWithCredentials));
843 841
844 if (httpBody) { 842 if (httpBody) {
845 ASSERT(m_method != "GET"); 843 ASSERT(m_method != "GET");
846 ASSERT(m_method != "HEAD"); 844 ASSERT(m_method != "HEAD");
847 request.setHTTPBody(httpBody); 845 request.setHTTPBody(httpBody);
848 } 846 }
849 847
850 if (m_requestHeaders.size() > 0) 848 if (m_requestHeaders.size() > 0)
851 request.addHTTPHeaderFields(m_requestHeaders); 849 request.addHTTPHeaderFields(m_requestHeaders);
852 850
853 ThreadableLoaderOptions options; 851 ThreadableLoaderOptions options;
854 options.preflightPolicy = uploadEvents ? ForcePreflight : ConsiderPreflight; 852 options.preflightPolicy = uploadEvents ? ForcePreflight : ConsiderPreflight;
855 options.crossOriginRequestPolicy = UseAccessControl; 853 options.crossOriginRequestPolicy = UseAccessControl;
856 options.initiator = FetchInitiatorTypeNames::xmlhttprequest; 854 options.initiator = FetchInitiatorTypeNames::xmlhttprequest;
857 options.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypa ssMainWorld(&executionContext) ? DoNotEnforceContentSecurityPolicy : EnforceConn ectSrcDirective; 855 options.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypa ssMainWorld(&executionContext) ? DoNotEnforceContentSecurityPolicy : EnforceConn ectSrcDirective;
858 options.timeoutMilliseconds = m_timeoutMilliseconds; 856 options.timeoutMilliseconds = m_timeoutMilliseconds;
859 857
860 ResourceLoaderOptions resourceLoaderOptions; 858 ResourceLoaderOptions resourceLoaderOptions;
861 resourceLoaderOptions.allowCredentials = (m_sameOriginRequest || m_includeCr edentials) ? AllowStoredCredentials : DoNotAllowStoredCredentials; 859 resourceLoaderOptions.allowCredentials = (getFlag(IsSameOriginRequest) || ge tFlag(IsWithCredentials)) ? AllowStoredCredentials : DoNotAllowStoredCredentials ;
862 resourceLoaderOptions.credentialsRequested = m_includeCredentials ? ClientRe questedCredentials : ClientDidNotRequestCredentials; 860 resourceLoaderOptions.credentialsRequested = getFlag(IsWithCredentials) ? Cl ientRequestedCredentials : ClientDidNotRequestCredentials;
863 resourceLoaderOptions.securityOrigin = securityOrigin(); 861 resourceLoaderOptions.securityOrigin = securityOrigin();
864 // TODO(tsepez): Specify TreatAsActiveContent per http://crbug.com/305303. 862 // TODO(tsepez): Specify TreatAsActiveContent per http://crbug.com/305303.
865 resourceLoaderOptions.mixedContentBlockingTreatment = TreatAsPassiveContent; 863 resourceLoaderOptions.mixedContentBlockingTreatment = TreatAsPassiveContent;
866 864
867 // When responseType is set to "blob", we redirect the downloaded data to a 865 // When responseType is set to "blob", we redirect the downloaded data to a
868 // file-handle directly. 866 // file-handle directly.
869 if (responseTypeCode() == ResponseTypeBlob) { 867 if (responseTypeCode() == ResponseTypeBlob) {
870 request.setDownloadToFile(true); 868 request.setDownloadToFile(true);
871 resourceLoaderOptions.dataBufferingPolicy = DoNotBufferData; 869 resourceLoaderOptions.dataBufferingPolicy = DoNotBufferData;
872 } 870 }
873 871
874 m_exceptionCode = 0; 872 m_exceptionCode = 0;
875 m_error = false; 873 clearFlag(HasError);
876 874
877 if (m_async) { 875 if (getFlag(IsAsync)) {
878 if (m_upload) 876 if (m_upload)
879 request.setReportUploadProgress(true); 877 request.setReportUploadProgress(true);
880 878
881 // ThreadableLoader::create can return null here, for example if we're n o longer attached to a page. 879 // ThreadableLoader::create can return null here, for example if we're n o longer attached to a page.
882 // This is true while running onunload handlers. 880 // This is true while running onunload handlers.
883 // FIXME: Maybe we need to be able to send XMLHttpRequests from onunload , <http://bugs.webkit.org/show_bug.cgi?id=10904>. 881 // FIXME: Maybe we need to be able to send XMLHttpRequests from onunload , <http://bugs.webkit.org/show_bug.cgi?id=10904>.
884 // FIXME: Maybe create() can return null for other reasons too? 882 // FIXME: Maybe create() can return null for other reasons too?
885 ASSERT(!m_loader); 883 ASSERT(!m_loader);
886 m_loader = ThreadableLoader::create(executionContext, this, request, opt ions, resourceLoaderOptions); 884 m_loader = ThreadableLoader::create(executionContext, this, request, opt ions, resourceLoaderOptions);
887 if (m_loader) { 885 if (m_loader) {
888 // Neither this object nor the JavaScript wrapper should be deleted while 886 // Neither this object nor the JavaScript wrapper should be deleted while
889 // a request is in progress because we need to keep the listeners al ive, 887 // a request is in progress because we need to keep the listeners al ive,
890 // and they are referenced by the JavaScript wrapper. 888 // and they are referenced by the JavaScript wrapper.
891 setPendingActivity(this); 889 setPendingActivity(this);
892 } 890 }
893 } else { 891 } else {
894 // Use count for XHR synchronous requests. 892 // Use count for XHR synchronous requests.
895 UseCounter::count(&executionContext, UseCounter::XMLHttpRequestSynchrono us); 893 UseCounter::count(&executionContext, UseCounter::XMLHttpRequestSynchrono us);
896 ThreadableLoader::loadResourceSynchronously(executionContext, request, * this, options, resourceLoaderOptions); 894 ThreadableLoader::loadResourceSynchronously(executionContext, request, * this, options, resourceLoaderOptions);
897 } 895 }
898 896
899 if (!m_exceptionCode && m_error) 897 if (!m_exceptionCode && getFlag(HasError))
900 m_exceptionCode = NetworkError; 898 m_exceptionCode = NetworkError;
901 if (m_exceptionCode) 899 if (m_exceptionCode)
902 exceptionState.throwDOMException(m_exceptionCode, "Failed to load '" + m _url.elidedString() + "'."); 900 exceptionState.throwDOMException(m_exceptionCode, "Failed to load '" + m _url.elidedString() + "'.");
903 } 901 }
904 902
905 void XMLHttpRequest::abort() 903 void XMLHttpRequest::abort()
906 { 904 {
907 WTF_LOG(Network, "XMLHttpRequest %p abort()", this); 905 WTF_LOG(Network, "XMLHttpRequest %p abort()", this);
908 906
909 // internalAbort() calls dropProtection(), which may release the last refere nce. 907 // internalAbort() calls dropProtection(), which may release the last refere nce.
(...skipping 22 matching lines...) Expand all
932 930
933 void XMLHttpRequest::clearVariablesForLoading() 931 void XMLHttpRequest::clearVariablesForLoading()
934 { 932 {
935 m_decoder.clear(); 933 m_decoder.clear();
936 934
937 m_responseEncoding = String(); 935 m_responseEncoding = String();
938 } 936 }
939 937
940 bool XMLHttpRequest::internalAbort(DropProtection async) 938 bool XMLHttpRequest::internalAbort(DropProtection async)
941 { 939 {
942 m_error = true; 940 setFlag(HasError);
943 941
944 clearVariablesForLoading(); 942 clearVariablesForLoading();
945 943
946 InspectorInstrumentation::didFailXHRLoading(executionContext(), this, this); 944 InspectorInstrumentation::didFailXHRLoading(executionContext(), this, this);
947 945
948 if (m_responseStream && m_state != DONE) 946 if (m_responseStream && m_state != DONE)
949 m_responseStream->abort(); 947 m_responseStream->abort();
950 948
951 if (!m_loader) 949 if (!m_loader)
952 return true; 950 return true;
(...skipping 12 matching lines...) Expand all
965 RefPtr<ThreadableLoader> loader = m_loader.release(); 963 RefPtr<ThreadableLoader> loader = m_loader.release();
966 loader->cancel(); 964 loader->cancel();
967 965
968 // Save to a local variable since we're going to drop protection. 966 // Save to a local variable since we're going to drop protection.
969 bool newLoadStarted = m_loader; 967 bool newLoadStarted = m_loader;
970 968
971 // If abort() called internalAbort() and a nested open() ended up 969 // If abort() called internalAbort() and a nested open() ended up
972 // clearing the error flag, but didn't send(), make sure the error 970 // clearing the error flag, but didn't send(), make sure the error
973 // flag is still set. 971 // flag is still set.
974 if (!newLoadStarted) 972 if (!newLoadStarted)
975 m_error = true; 973 setFlag(HasError);
976 974
977 if (async == DropProtectionAsync) 975 if (async == DropProtectionAsync)
978 dropProtectionSoon(); 976 dropProtectionSoon();
979 else 977 else
980 dropProtection(); 978 dropProtection();
981 979
982 return !newLoadStarted; 980 return !newLoadStarted;
983 } 981 }
984 982
985 void XMLHttpRequest::clearResponse() 983 void XMLHttpRequest::clearResponse()
986 { 984 {
987 // FIXME: when we add the support for multi-part XHR, we will have to 985 // FIXME: when we add the support for multi-part XHR, we will have to
988 // be careful with this initialization. 986 // be careful with this initialization.
989 m_receivedLength = 0; 987 m_receivedLength = 0;
990 988
991 m_response = ResourceResponse(); 989 m_response = ResourceResponse();
992 990
993 m_responseText.clear(); 991 m_responseText.clear();
994 992
995 m_createdDocument = false; 993 clearFlag(IsDocumentCreated);
996 m_responseDocument = nullptr; 994 m_responseDocument = nullptr;
997 995
998 m_responseBlob = nullptr; 996 m_responseBlob = nullptr;
999 m_downloadedBlobLength = 0; 997 m_downloadedBlobLength = 0;
1000 998
1001 m_responseStream = nullptr; 999 m_responseStream = nullptr;
1002 1000
1003 // These variables may referred by the response accessors. So, we can clear 1001 // These variables may referred by the response accessors. So, we can clear
1004 // this only when we clear the response holder variables above. 1002 // this only when we clear the response holder variables above.
1005 m_binaryResponseBuilder.clear(); 1003 m_binaryResponseBuilder.clear();
1006 m_responseArrayBuffer.clear(); 1004 m_responseArrayBuffer.clear();
1007 } 1005 }
1008 1006
1009 void XMLHttpRequest::clearRequest() 1007 void XMLHttpRequest::clearRequest()
1010 { 1008 {
1011 m_requestHeaders.clear(); 1009 m_requestHeaders.clear();
1012 } 1010 }
1013 1011
1014 void XMLHttpRequest::handleDidFailGeneric() 1012 void XMLHttpRequest::handleDidFailGeneric()
1015 { 1013 {
1016 clearResponse(); 1014 clearResponse();
1017 clearRequest(); 1015 clearRequest();
1018 1016
1019 m_error = true; 1017 setFlag(HasError);
1020 } 1018 }
1021 1019
1022 void XMLHttpRequest::dispatchProgressEvent(const AtomicString& type, long long r eceivedLength, long long expectedLength) 1020 void XMLHttpRequest::dispatchProgressEvent(const AtomicString& type, long long r eceivedLength, long long expectedLength)
1023 { 1021 {
1024 bool lengthComputable = expectedLength > 0 && receivedLength <= expectedLeng th; 1022 bool lengthComputable = expectedLength > 0 && receivedLength <= expectedLeng th;
1025 unsigned long long loaded = receivedLength >= 0 ? static_cast<unsigned long long>(receivedLength) : 0; 1023 unsigned long long loaded = receivedLength >= 0 ? static_cast<unsigned long long>(receivedLength) : 0;
1026 unsigned long long total = lengthComputable ? static_cast<unsigned long long >(expectedLength) : 0; 1024 unsigned long long total = lengthComputable ? static_cast<unsigned long long >(expectedLength) : 0;
1027 1025
1028 m_progressEventThrottle.dispatchProgressEvent(type, lengthComputable, loaded , total); 1026 m_progressEventThrottle.dispatchProgressEvent(type, lengthComputable, loaded , total);
1029 } 1027 }
(...skipping 27 matching lines...) Expand all
1057 handleDidFailGeneric(); 1055 handleDidFailGeneric();
1058 handleRequestError(AbortError, EventTypeNames::abort, receivedLength, expect edLength); 1056 handleRequestError(AbortError, EventTypeNames::abort, receivedLength, expect edLength);
1059 } 1057 }
1060 1058
1061 void XMLHttpRequest::handleRequestError(ExceptionCode exceptionCode, const Atomi cString& type, long long receivedLength, long long expectedLength) 1059 void XMLHttpRequest::handleRequestError(ExceptionCode exceptionCode, const Atomi cString& type, long long receivedLength, long long expectedLength)
1062 { 1060 {
1063 WTF_LOG(Network, "XMLHttpRequest %p handleRequestError()", this); 1061 WTF_LOG(Network, "XMLHttpRequest %p handleRequestError()", this);
1064 1062
1065 // The request error steps for event 'type' and exception 'exceptionCode'. 1063 // The request error steps for event 'type' and exception 'exceptionCode'.
1066 1064
1067 if (!m_async && exceptionCode) { 1065 if (!getFlag(IsAsync) && exceptionCode) {
1068 m_state = DONE; 1066 m_state = DONE;
1069 m_exceptionCode = exceptionCode; 1067 m_exceptionCode = exceptionCode;
1070 return; 1068 return;
1071 } 1069 }
1072 // With m_error set, the state change steps are minimal: any pending 1070 // With HasError set, the state change steps are minimal: any pending
1073 // progress event is flushed + a readystatechange is dispatched. 1071 // progress event is flushed + a readystatechange is dispatched.
1074 // No new progress events dispatched; as required, that happens at 1072 // No new progress events dispatched; as required, that happens at
1075 // the end here. 1073 // the end here.
1076 ASSERT(m_error); 1074 ASSERT(getFlag(HasError));
1077 changeState(DONE); 1075 changeState(DONE);
1078 1076
1079 if (!m_uploadComplete) { 1077 if (!getFlag(IsUploadComplete)) {
1080 m_uploadComplete = true; 1078 setFlag(IsUploadComplete);
1081 if (m_upload && m_uploadEventsAllowed) 1079 if (m_upload && getFlag(IsUploadEventsAllowed))
1082 m_upload->handleRequestError(type); 1080 m_upload->handleRequestError(type);
1083 } 1081 }
1084 1082
1085 dispatchProgressEvent(EventTypeNames::progress, receivedLength, expectedLeng th); 1083 dispatchProgressEvent(EventTypeNames::progress, receivedLength, expectedLeng th);
1086 dispatchProgressEvent(type, receivedLength, expectedLength); 1084 dispatchProgressEvent(type, receivedLength, expectedLength);
1087 dispatchProgressEvent(EventTypeNames::loadend, receivedLength, expectedLengt h); 1085 dispatchProgressEvent(EventTypeNames::loadend, receivedLength, expectedLengt h);
1088 } 1086 }
1089 1087
1090 void XMLHttpRequest::dropProtectionSoon() 1088 void XMLHttpRequest::dropProtectionSoon()
1091 { 1089 {
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
1135 result.storedValue->value = result.storedValue->value + ", " + value; 1133 result.storedValue->value = result.storedValue->value + ", " + value;
1136 } 1134 }
1137 1135
1138 const AtomicString& XMLHttpRequest::getRequestHeader(const AtomicString& name) c onst 1136 const AtomicString& XMLHttpRequest::getRequestHeader(const AtomicString& name) c onst
1139 { 1137 {
1140 return m_requestHeaders.get(name); 1138 return m_requestHeaders.get(name);
1141 } 1139 }
1142 1140
1143 String XMLHttpRequest::getAllResponseHeaders() const 1141 String XMLHttpRequest::getAllResponseHeaders() const
1144 { 1142 {
1145 if (m_state < HEADERS_RECEIVED || m_error) 1143 if (m_state < HEADERS_RECEIVED || getFlag(HasError))
1146 return ""; 1144 return "";
1147 1145
1148 StringBuilder stringBuilder; 1146 StringBuilder stringBuilder;
1149 1147
1150 HTTPHeaderSet accessControlExposeHeaderSet; 1148 HTTPHeaderSet accessControlExposeHeaderSet;
1151 parseAccessControlExposeHeadersAllowList(m_response.httpHeaderField("Access- Control-Expose-Headers"), accessControlExposeHeaderSet); 1149 parseAccessControlExposeHeadersAllowList(m_response.httpHeaderField("Access- Control-Expose-Headers"), accessControlExposeHeaderSet);
1152 HTTPHeaderMap::const_iterator end = m_response.httpHeaderFields().end(); 1150 HTTPHeaderMap::const_iterator end = m_response.httpHeaderFields().end();
1153 for (HTTPHeaderMap::const_iterator it = m_response.httpHeaderFields().begin( ); it!= end; ++it) { 1151 for (HTTPHeaderMap::const_iterator it = m_response.httpHeaderFields().begin( ); it!= end; ++it) {
1154 // Hide Set-Cookie header fields from the XMLHttpRequest client for thes e reasons: 1152 // Hide Set-Cookie header fields from the XMLHttpRequest client for thes e reasons:
1155 // 1) If the client did have access to the fields, then it could rea d HTTP-only 1153 // 1) If the client did have access to the fields, then it could rea d HTTP-only
1156 // cookies; those cookies are supposed to be hidden from scripts. 1154 // cookies; those cookies are supposed to be hidden from scripts.
1157 // 2) There's no known harm in hiding Set-Cookie header fields entir ely; we don't 1155 // 2) There's no known harm in hiding Set-Cookie header fields entir ely; we don't
1158 // know any widely used technique that requires access to them. 1156 // know any widely used technique that requires access to them.
1159 // 3) Firefox has implemented this policy. 1157 // 3) Firefox has implemented this policy.
1160 if (isSetCookieHeader(it->key) && !securityOrigin()->canLoadLocalResourc es()) 1158 if (isSetCookieHeader(it->key) && !securityOrigin()->canLoadLocalResourc es())
1161 continue; 1159 continue;
1162 1160
1163 if (!m_sameOriginRequest && !isOnAccessControlResponseHeaderWhitelist(it ->key) && !accessControlExposeHeaderSet.contains(it->key)) 1161 if (!getFlag(IsSameOriginRequest) && !isOnAccessControlResponseHeaderWhi telist(it->key) && !accessControlExposeHeaderSet.contains(it->key))
1164 continue; 1162 continue;
1165 1163
1166 stringBuilder.append(it->key); 1164 stringBuilder.append(it->key);
1167 stringBuilder.append(':'); 1165 stringBuilder.append(':');
1168 stringBuilder.append(' '); 1166 stringBuilder.append(' ');
1169 stringBuilder.append(it->value); 1167 stringBuilder.append(it->value);
1170 stringBuilder.append('\r'); 1168 stringBuilder.append('\r');
1171 stringBuilder.append('\n'); 1169 stringBuilder.append('\n');
1172 } 1170 }
1173 1171
1174 return stringBuilder.toString(); 1172 return stringBuilder.toString();
1175 } 1173 }
1176 1174
1177 const AtomicString& XMLHttpRequest::getResponseHeader(const AtomicString& name) const 1175 const AtomicString& XMLHttpRequest::getResponseHeader(const AtomicString& name) const
1178 { 1176 {
1179 if (m_state < HEADERS_RECEIVED || m_error) 1177 if (m_state < HEADERS_RECEIVED || getFlag(HasError))
1180 return nullAtom; 1178 return nullAtom;
1181 1179
1182 // See comment in getAllResponseHeaders above. 1180 // See comment in getAllResponseHeaders above.
1183 if (isSetCookieHeader(name) && !securityOrigin()->canLoadLocalResources()) { 1181 if (isSetCookieHeader(name) && !securityOrigin()->canLoadLocalResources()) {
1184 logConsoleError(executionContext(), "Refused to get unsafe header \"" + name + "\""); 1182 logConsoleError(executionContext(), "Refused to get unsafe header \"" + name + "\"");
1185 return nullAtom; 1183 return nullAtom;
1186 } 1184 }
1187 1185
1188 HTTPHeaderSet accessControlExposeHeaderSet; 1186 HTTPHeaderSet accessControlExposeHeaderSet;
1189 parseAccessControlExposeHeadersAllowList(m_response.httpHeaderField("Access- Control-Expose-Headers"), accessControlExposeHeaderSet); 1187 parseAccessControlExposeHeadersAllowList(m_response.httpHeaderField("Access- Control-Expose-Headers"), accessControlExposeHeaderSet);
1190 1188
1191 if (!m_sameOriginRequest && !isOnAccessControlResponseHeaderWhitelist(name) && !accessControlExposeHeaderSet.contains(name)) { 1189 if (!getFlag(IsSameOriginRequest) && !isOnAccessControlResponseHeaderWhiteli st(name) && !accessControlExposeHeaderSet.contains(name)) {
1192 logConsoleError(executionContext(), "Refused to get unsafe header \"" + name + "\""); 1190 logConsoleError(executionContext(), "Refused to get unsafe header \"" + name + "\"");
1193 return nullAtom; 1191 return nullAtom;
1194 } 1192 }
1195 return m_response.httpHeaderField(name); 1193 return m_response.httpHeaderField(name);
1196 } 1194 }
1197 1195
1198 AtomicString XMLHttpRequest::responseMIMEType() const 1196 AtomicString XMLHttpRequest::responseMIMEType() const
1199 { 1197 {
1200 AtomicString mimeType = extractMIMETypeFromMediaType(m_mimeTypeOverride); 1198 AtomicString mimeType = extractMIMETypeFromMediaType(m_mimeTypeOverride);
1201 if (mimeType.isEmpty()) { 1199 if (mimeType.isEmpty()) {
1202 if (m_response.isHTTP()) 1200 if (m_response.isHTTP())
1203 mimeType = extractMIMETypeFromMediaType(m_response.httpHeaderField(" Content-Type")); 1201 mimeType = extractMIMETypeFromMediaType(m_response.httpHeaderField(" Content-Type"));
1204 else 1202 else
1205 mimeType = m_response.mimeType(); 1203 mimeType = m_response.mimeType();
1206 } 1204 }
1207 if (mimeType.isEmpty()) 1205 if (mimeType.isEmpty())
1208 mimeType = AtomicString("text/xml", AtomicString::ConstructFromLiteral); 1206 mimeType = AtomicString("text/xml", AtomicString::ConstructFromLiteral);
1209 1207
1210 return mimeType; 1208 return mimeType;
1211 } 1209 }
1212 1210
1213 bool XMLHttpRequest::responseIsXML() const 1211 bool XMLHttpRequest::responseIsXML() const
1214 { 1212 {
1215 return DOMImplementation::isXMLMIMEType(responseMIMEType()); 1213 return DOMImplementation::isXMLMIMEType(responseMIMEType());
1216 } 1214 }
1217 1215
1218 int XMLHttpRequest::status() const 1216 int XMLHttpRequest::status() const
1219 { 1217 {
1220 if (m_state == UNSENT || m_state == OPENED || m_error) 1218 if (m_state == UNSENT || m_state == OPENED || getFlag(HasError))
1221 return 0; 1219 return 0;
1222 1220
1223 if (m_response.httpStatusCode()) 1221 if (m_response.httpStatusCode())
1224 return m_response.httpStatusCode(); 1222 return m_response.httpStatusCode();
1225 1223
1226 return 0; 1224 return 0;
1227 } 1225 }
1228 1226
1229 String XMLHttpRequest::statusText() const 1227 String XMLHttpRequest::statusText() const
1230 { 1228 {
1231 if (m_state == UNSENT || m_state == OPENED || m_error) 1229 if (m_state == UNSENT || m_state == OPENED || getFlag(HasError))
1232 return String(); 1230 return String();
1233 1231
1234 if (!m_response.httpStatusText().isNull()) 1232 if (!m_response.httpStatusText().isNull())
1235 return m_response.httpStatusText(); 1233 return m_response.httpStatusText();
1236 1234
1237 return String(); 1235 return String();
1238 } 1236 }
1239 1237
1240 void XMLHttpRequest::didFail(const ResourceError& error) 1238 void XMLHttpRequest::didFail(const ResourceError& error)
1241 { 1239 {
1242 WTF_LOG(Network, "XMLHttpRequest %p didFail()", this); 1240 WTF_LOG(Network, "XMLHttpRequest %p didFail()", this);
1243 1241
1244 // If we are already in an error state, for instance we called abort(), bail out early. 1242 // If we are already in an error state, for instance we called abort(), bail out early.
1245 if (m_error) 1243 if (getFlag(HasError))
1246 return; 1244 return;
1247 1245
1248 if (error.isCancellation()) { 1246 if (error.isCancellation()) {
1249 handleDidCancel(); 1247 handleDidCancel();
1250 return; 1248 return;
1251 } 1249 }
1252 1250
1253 if (error.isTimeout()) { 1251 if (error.isTimeout()) {
1254 handleDidTimeout(); 1252 handleDidTimeout();
1255 return; 1253 return;
(...skipping 10 matching lines...) Expand all
1266 { 1264 {
1267 WTF_LOG(Network, "XMLHttpRequest %p didFailRedirectCheck()", this); 1265 WTF_LOG(Network, "XMLHttpRequest %p didFailRedirectCheck()", this);
1268 1266
1269 handleNetworkError(); 1267 handleNetworkError();
1270 } 1268 }
1271 1269
1272 void XMLHttpRequest::didFinishLoading(unsigned long identifier, double) 1270 void XMLHttpRequest::didFinishLoading(unsigned long identifier, double)
1273 { 1271 {
1274 WTF_LOG(Network, "XMLHttpRequest %p didFinishLoading(%lu)", this, identifier ); 1272 WTF_LOG(Network, "XMLHttpRequest %p didFinishLoading(%lu)", this, identifier );
1275 1273
1276 if (m_error) 1274 if (getFlag(HasError))
1277 return; 1275 return;
1278 1276
1279 if (m_state < HEADERS_RECEIVED) 1277 if (m_state < HEADERS_RECEIVED)
1280 changeState(HEADERS_RECEIVED); 1278 changeState(HEADERS_RECEIVED);
1281 1279
1282 if (m_decoder) 1280 if (m_decoder)
1283 m_responseText = m_responseText.concatenateWith(m_decoder->flush()); 1281 m_responseText = m_responseText.concatenateWith(m_decoder->flush());
1284 1282
1285 if (m_responseStream) 1283 if (m_responseStream)
1286 m_responseStream->finalize(); 1284 m_responseStream->finalize();
(...skipping 13 matching lines...) Expand all
1300 changeState(DONE); 1298 changeState(DONE);
1301 } 1299 }
1302 1300
1303 void XMLHttpRequest::didSendData(unsigned long long bytesSent, unsigned long lon g totalBytesToBeSent) 1301 void XMLHttpRequest::didSendData(unsigned long long bytesSent, unsigned long lon g totalBytesToBeSent)
1304 { 1302 {
1305 WTF_LOG(Network, "XMLHttpRequest %p didSendData(%llu, %llu)", this, bytesSen t, totalBytesToBeSent); 1303 WTF_LOG(Network, "XMLHttpRequest %p didSendData(%llu, %llu)", this, bytesSen t, totalBytesToBeSent);
1306 1304
1307 if (!m_upload) 1305 if (!m_upload)
1308 return; 1306 return;
1309 1307
1310 if (m_uploadEventsAllowed) 1308 if (getFlag(IsUploadEventsAllowed))
1311 m_upload->dispatchProgressEvent(bytesSent, totalBytesToBeSent); 1309 m_upload->dispatchProgressEvent(bytesSent, totalBytesToBeSent);
1312 1310
1313 if (bytesSent == totalBytesToBeSent && !m_uploadComplete) { 1311 if (bytesSent == totalBytesToBeSent && !getFlag(IsUploadComplete)) {
1314 m_uploadComplete = true; 1312 setFlag(IsUploadComplete);
1315 if (m_uploadEventsAllowed) 1313 if (getFlag(IsUploadEventsAllowed))
1316 m_upload->dispatchEventAndLoadEnd(EventTypeNames::load, true, bytesS ent, totalBytesToBeSent); 1314 m_upload->dispatchEventAndLoadEnd(EventTypeNames::load, true, bytesS ent, totalBytesToBeSent);
1317 } 1315 }
1318 } 1316 }
1319 1317
1320 void XMLHttpRequest::didReceiveResponse(unsigned long identifier, const Resource Response& response) 1318 void XMLHttpRequest::didReceiveResponse(unsigned long identifier, const Resource Response& response)
1321 { 1319 {
1322 WTF_LOG(Network, "XMLHttpRequest %p didReceiveResponse(%lu)", this, identifi er); 1320 WTF_LOG(Network, "XMLHttpRequest %p didReceiveResponse(%lu)", this, identifi er);
1323 1321
1324 m_response = response; 1322 m_response = response;
1325 if (!m_mimeTypeOverride.isEmpty()) { 1323 if (!m_mimeTypeOverride.isEmpty()) {
1326 m_response.setHTTPHeaderField("Content-Type", m_mimeTypeOverride); 1324 m_response.setHTTPHeaderField("Content-Type", m_mimeTypeOverride);
1327 m_responseEncoding = extractCharsetFromMediaType(m_mimeTypeOverride); 1325 m_responseEncoding = extractCharsetFromMediaType(m_mimeTypeOverride);
1328 } 1326 }
1329 1327
1330 if (m_responseEncoding.isEmpty()) 1328 if (m_responseEncoding.isEmpty())
1331 m_responseEncoding = response.textEncodingName(); 1329 m_responseEncoding = response.textEncodingName();
1332 } 1330 }
1333 1331
1334 void XMLHttpRequest::didReceiveData(const char* data, int len) 1332 void XMLHttpRequest::didReceiveData(const char* data, int len)
1335 { 1333 {
1336 ASSERT(m_responseTypeCode != ResponseTypeBlob); 1334 ASSERT(m_responseTypeCode != ResponseTypeBlob);
1337 1335
1338 if (m_error) 1336 if (getFlag(HasError))
1339 return; 1337 return;
1340 1338
1341 if (m_state < HEADERS_RECEIVED) 1339 if (m_state < HEADERS_RECEIVED)
1342 changeState(HEADERS_RECEIVED); 1340 changeState(HEADERS_RECEIVED);
1343 1341
1344 bool useDecoder = m_responseTypeCode == ResponseTypeDefault || m_responseTyp eCode == ResponseTypeText || m_responseTypeCode == ResponseTypeJSON || m_respons eTypeCode == ResponseTypeDocument; 1342 bool useDecoder = m_responseTypeCode == ResponseTypeDefault || m_responseTyp eCode == ResponseTypeText || m_responseTypeCode == ResponseTypeJSON || m_respons eTypeCode == ResponseTypeDocument;
1345 1343
1346 if (useDecoder && !m_decoder) { 1344 if (useDecoder && !m_decoder) {
1347 if (m_responseTypeCode == ResponseTypeJSON) { 1345 if (m_responseTypeCode == ResponseTypeJSON) {
1348 m_decoder = TextResourceDecoder::create("application/json", "UTF-8") ; 1346 m_decoder = TextResourceDecoder::create("application/json", "UTF-8") ;
(...skipping 25 matching lines...) Expand all
1374 // Buffer binary data. 1372 // Buffer binary data.
1375 if (!m_binaryResponseBuilder) 1373 if (!m_binaryResponseBuilder)
1376 m_binaryResponseBuilder = SharedBuffer::create(); 1374 m_binaryResponseBuilder = SharedBuffer::create();
1377 m_binaryResponseBuilder->append(data, len); 1375 m_binaryResponseBuilder->append(data, len);
1378 } else if (m_responseTypeCode == ResponseTypeStream) { 1376 } else if (m_responseTypeCode == ResponseTypeStream) {
1379 if (!m_responseStream) 1377 if (!m_responseStream)
1380 m_responseStream = Stream::create(executionContext(), responseMIMETy pe()); 1378 m_responseStream = Stream::create(executionContext(), responseMIMETy pe());
1381 m_responseStream->addData(data, len); 1379 m_responseStream->addData(data, len);
1382 } 1380 }
1383 1381
1384 if (m_error) 1382 if (getFlag(HasError))
1385 return; 1383 return;
1386 1384
1387 trackProgress(len); 1385 trackProgress(len);
1388 } 1386 }
1389 1387
1390 void XMLHttpRequest::didDownloadData(int dataLength) 1388 void XMLHttpRequest::didDownloadData(int dataLength)
1391 { 1389 {
1392 ASSERT(m_responseTypeCode == ResponseTypeBlob); 1390 ASSERT(m_responseTypeCode == ResponseTypeBlob);
1393 1391
1394 if (m_error) 1392 if (getFlag(HasError))
1395 return; 1393 return;
1396 1394
1397 if (m_state < HEADERS_RECEIVED) 1395 if (m_state < HEADERS_RECEIVED)
1398 changeState(HEADERS_RECEIVED); 1396 changeState(HEADERS_RECEIVED);
1399 1397
1400 if (!dataLength) 1398 if (!dataLength)
1401 return; 1399 return;
1402 1400
1403 // readystatechange event handler may do something to put this XHR in error 1401 // readystatechange event handler may do something to put this XHR in error
1404 // state. We need to check m_error again here. 1402 // state. We need to check HasError again here.
1405 if (m_error) 1403 if (getFlag(HasError))
1406 return; 1404 return;
1407 1405
1408 m_downloadedBlobLength += dataLength; 1406 m_downloadedBlobLength += dataLength;
1409 1407
1410 trackProgress(dataLength); 1408 trackProgress(dataLength);
1411 } 1409 }
1412 1410
1413 void XMLHttpRequest::handleDidTimeout() 1411 void XMLHttpRequest::handleDidTimeout()
1414 { 1412 {
1415 WTF_LOG(Network, "XMLHttpRequest %p handleDidTimeout()", this); 1413 WTF_LOG(Network, "XMLHttpRequest %p handleDidTimeout()", this);
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
1463 { 1461 {
1464 visitor->trace(m_responseBlob); 1462 visitor->trace(m_responseBlob);
1465 visitor->trace(m_responseStream); 1463 visitor->trace(m_responseStream);
1466 visitor->trace(m_responseDocument); 1464 visitor->trace(m_responseDocument);
1467 visitor->trace(m_progressEventThrottle); 1465 visitor->trace(m_progressEventThrottle);
1468 visitor->trace(m_upload); 1466 visitor->trace(m_upload);
1469 XMLHttpRequestEventTarget::trace(visitor); 1467 XMLHttpRequestEventTarget::trace(visitor);
1470 } 1468 }
1471 1469
1472 } // namespace WebCore 1470 } // namespace WebCore
OLDNEW
« Source/core/xml/XMLHttpRequest.h ('K') | « Source/core/xml/XMLHttpRequest.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698