summaryrefslogtreecommitdiffstats
path: root/content/browser/in_process_webkit/indexed_db_dispatcher_host.cc
blob: 49339864e5205f38d08651d84930de218509be0c (plain)
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/in_process_webkit/indexed_db_dispatcher_host.h"

#include <vector>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/process.h"
#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "content/browser/in_process_webkit/indexed_db_callbacks.h"
#include "content/browser/in_process_webkit/indexed_db_context_impl.h"
#include "content/browser/in_process_webkit/indexed_db_database_callbacks.h"
#include "content/browser/renderer_host/render_message_filter.h"
#include "content/common/indexed_db/indexed_db_messages.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/result_codes.h"
#include "googleurl/src/gurl.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebData.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebVector.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDOMStringList.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebIDBCursor.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebIDBDatabase.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebIDBDatabaseCallbacks.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebIDBDatabaseError.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebIDBDatabaseException.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebIDBFactory.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebIDBMetadata.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h"
#include "webkit/base/file_path_string_conversions.h"
#include "webkit/database/database_util.h"

using webkit_database::DatabaseUtil;
using WebKit::WebDOMStringList;
using WebKit::WebData;
using WebKit::WebExceptionCode;
using WebKit::WebIDBCallbacks;
using WebKit::WebIDBCursor;
using WebKit::WebIDBDatabase;
using WebKit::WebIDBDatabaseError;
using WebKit::WebIDBIndex;
using WebKit::WebIDBKey;
using WebKit::WebIDBMetadata;
using WebKit::WebIDBObjectStore;
using WebKit::WebSecurityOrigin;
using WebKit::WebSerializedScriptValue;
using WebKit::WebVector;

namespace content {
namespace {

template <class T>
void DeleteOnWebKitThread(T* obj) {
  if (!BrowserThread::DeleteSoon(BrowserThread::WEBKIT_DEPRECATED,
                                 FROM_HERE, obj))
    delete obj;
}
}

IndexedDBDispatcherHost::IndexedDBDispatcherHost(
    int ipc_process_id, IndexedDBContextImpl* indexed_db_context)
    : indexed_db_context_(indexed_db_context),
      ALLOW_THIS_IN_INITIALIZER_LIST(database_dispatcher_host_(
          new DatabaseDispatcherHost(this))),
      ALLOW_THIS_IN_INITIALIZER_LIST(cursor_dispatcher_host_(
          new CursorDispatcherHost(this))),
      ipc_process_id_(ipc_process_id) {
  DCHECK(indexed_db_context_.get());
}

IndexedDBDispatcherHost::~IndexedDBDispatcherHost() {
}

void IndexedDBDispatcherHost::OnChannelClosing() {
  BrowserMessageFilter::OnChannelClosing();

  bool success = BrowserThread::PostTask(
      BrowserThread::WEBKIT_DEPRECATED, FROM_HERE,
      base::Bind(&IndexedDBDispatcherHost::ResetDispatcherHosts, this));

  if (!success)
    ResetDispatcherHosts();
}

void IndexedDBDispatcherHost::ResetDispatcherHosts() {
  // It is important that the various *_dispatcher_host_ members are reset
  // on the WebKit thread, since there might be incoming messages on that
  // thread, and we must not reset the dispatcher hosts until after those
  // messages are processed.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED) ||
         CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess));

  database_dispatcher_host_.reset();
  cursor_dispatcher_host_.reset();
}

void IndexedDBDispatcherHost::OverrideThreadForMessage(
    const IPC::Message& message,
    BrowserThread::ID* thread) {
  if (IPC_MESSAGE_CLASS(message) == IndexedDBMsgStart)
    *thread = BrowserThread::WEBKIT_DEPRECATED;
}

bool IndexedDBDispatcherHost::OnMessageReceived(const IPC::Message& message,
                                                bool* message_was_ok) {
  if (IPC_MESSAGE_CLASS(message) != IndexedDBMsgStart)
    return false;

  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));

  bool handled =
      database_dispatcher_host_->OnMessageReceived(message, message_was_ok) ||
      cursor_dispatcher_host_->OnMessageReceived(message, message_was_ok);

  if (!handled) {
    handled = true;
    IPC_BEGIN_MESSAGE_MAP_EX(IndexedDBDispatcherHost, message, *message_was_ok)
      IPC_MESSAGE_HANDLER(IndexedDBHostMsg_FactoryGetDatabaseNames,
                          OnIDBFactoryGetDatabaseNames)
      IPC_MESSAGE_HANDLER(IndexedDBHostMsg_FactoryOpen, OnIDBFactoryOpen)
      IPC_MESSAGE_HANDLER(IndexedDBHostMsg_FactoryDeleteDatabase,
                          OnIDBFactoryDeleteDatabase)
      IPC_MESSAGE_UNHANDLED(handled = false)
    IPC_END_MESSAGE_MAP()
  }
  return handled;
}

int32 IndexedDBDispatcherHost::Add(WebIDBCursor* idb_cursor) {
  if (!cursor_dispatcher_host_.get()) {
    delete idb_cursor;
    return 0;
  }
  return cursor_dispatcher_host_->map_.Add(idb_cursor);
}

int32 IndexedDBDispatcherHost::Add(WebIDBDatabase* idb_database,
                                   int32 ipc_thread_id,
                                   const GURL& origin_url) {
  if (!database_dispatcher_host_.get()) {
    delete idb_database;
    return 0;
  }
  int32 ipc_database_id = database_dispatcher_host_->map_.Add(idb_database);
  Context()->ConnectionOpened(origin_url, idb_database);
  database_dispatcher_host_->database_url_map_[ipc_database_id] = origin_url;
  return ipc_database_id;
}

void IndexedDBDispatcherHost::RegisterTransactionId(
    int64 host_transaction_id,
    const GURL& url)
{
  if (!database_dispatcher_host_)
    return;
  database_dispatcher_host_->transaction_url_map_[host_transaction_id] = url;
}

int64 IndexedDBDispatcherHost::HostTransactionId(int64 transaction_id) {
  // Inject the renderer process id into the transaction id, to
  // uniquely identify this transaction, and effectively bind it to
  // the renderer that initiated it. The lower 32 bits of
  // transaction_id are guaranteed to be unique within that renderer.
  base::ProcessId pid = base::GetProcId(peer_handle());
  DCHECK(!(transaction_id >> 32)) << "Transaction ids can only be 32 bits";
  COMPILE_ASSERT(sizeof(base::ProcessId) <= sizeof(int32),
                 Process_ID_must_fit_in_32_bits);

  return transaction_id | (static_cast<uint64>(pid) << 32);
}

int64 IndexedDBDispatcherHost::RendererTransactionId(
    int64 host_transaction_id) {
  DCHECK(host_transaction_id >> 32 == base::GetProcId(peer_handle())) <<
      "Invalid renderer target for transaction id";
  return host_transaction_id & 0xffffffff;
}

WebIDBCursor* IndexedDBDispatcherHost::GetCursorFromId(int32 ipc_cursor_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  return cursor_dispatcher_host_->map_.Lookup(ipc_cursor_id);
}

IndexedDBDatabaseMetadata IndexedDBDispatcherHost::ConvertMetadata(
    const WebIDBMetadata& web_metadata)
{
  IndexedDBDatabaseMetadata metadata;
  metadata.id = web_metadata.id;
  metadata.name = web_metadata.name;
  metadata.version = web_metadata.version;
  metadata.int_version = web_metadata.intVersion;
  metadata.max_object_store_id = web_metadata.maxObjectStoreId;

  for (size_t i = 0; i < web_metadata.objectStores.size(); ++i) {
    const WebIDBMetadata::ObjectStore& web_store_metadata =
        web_metadata.objectStores[i];
    IndexedDBObjectStoreMetadata idb_store_metadata;
    idb_store_metadata.id = web_store_metadata.id;
    idb_store_metadata.name = web_store_metadata.name;
    idb_store_metadata.keyPath = IndexedDBKeyPath(web_store_metadata.keyPath);
    idb_store_metadata.autoIncrement = web_store_metadata.autoIncrement;
    idb_store_metadata.max_index_id = web_store_metadata.maxIndexId;

    for (size_t j = 0; j < web_store_metadata.indexes.size(); ++j) {
      const WebIDBMetadata::Index& web_index_metadata =
          web_store_metadata.indexes[j];
      IndexedDBIndexMetadata idb_index_metadata;
      idb_index_metadata.id = web_index_metadata.id;
      idb_index_metadata.name = web_index_metadata.name;
      idb_index_metadata.keyPath = IndexedDBKeyPath(web_index_metadata.keyPath);
      idb_index_metadata.unique = web_index_metadata.unique;
      idb_index_metadata.multiEntry = web_index_metadata.multiEntry;
      idb_store_metadata.indexes.push_back(idb_index_metadata);
    }
    metadata.object_stores.push_back(idb_store_metadata);
  }
  return metadata;
}

void IndexedDBDispatcherHost::OnIDBFactoryGetDatabaseNames(
    const IndexedDBHostMsg_FactoryGetDatabaseNames_Params& params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  base::FilePath indexed_db_path = indexed_db_context_->data_path();

  WebSecurityOrigin origin(
      WebSecurityOrigin::createFromDatabaseIdentifier(params.origin));

  Context()->GetIDBFactory()->getDatabaseNames(
      new IndexedDBCallbacks<WebDOMStringList>(this, params.ipc_thread_id,
      params.ipc_response_id), origin, NULL,
      webkit_base::FilePathToWebString(indexed_db_path));
}

void IndexedDBDispatcherHost::OnIDBFactoryOpen(
    const IndexedDBHostMsg_FactoryOpen_Params& params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  base::FilePath indexed_db_path = indexed_db_context_->data_path();

  GURL origin_url = DatabaseUtil::GetOriginFromIdentifier(params.origin);
  WebSecurityOrigin origin(
      WebSecurityOrigin::createFromDatabaseIdentifier(params.origin));

  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));

  int64 host_transaction_id = HostTransactionId(params.transaction_id);

  // TODO(dgrogan): Don't let a non-existing database be opened (and therefore
  // created) if this origin is already over quota.
  Context()->GetIDBFactory()->open(
      params.name,
      params.version,
      host_transaction_id,
      new IndexedDBCallbacksDatabase(this, params.ipc_thread_id,
                                     params.ipc_response_id,
                                     host_transaction_id,
                                     origin_url),
      new IndexedDBDatabaseCallbacks(this, params.ipc_thread_id,
                                     params.ipc_database_response_id),
      origin, NULL, webkit_base::FilePathToWebString(indexed_db_path));
}

void IndexedDBDispatcherHost::OnIDBFactoryDeleteDatabase(
    const IndexedDBHostMsg_FactoryDeleteDatabase_Params& params) {
  base::FilePath indexed_db_path = indexed_db_context_->data_path();

  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  Context()->GetIDBFactory()->deleteDatabase(
      params.name,
      new IndexedDBCallbacks<WebSerializedScriptValue>(this,
                                                       params.ipc_thread_id,
                                                       params.ipc_response_id),
      WebSecurityOrigin::createFromDatabaseIdentifier(params.origin), NULL,
      webkit_base::FilePathToWebString(indexed_db_path));
}

void IndexedDBDispatcherHost::FinishTransaction(
    int64 host_transaction_id, bool committed) {
  if (committed)
    Context()->TransactionComplete(
        database_dispatcher_host_->transaction_url_map_[host_transaction_id]);
  database_dispatcher_host_->transaction_url_map_.erase(host_transaction_id);
  database_dispatcher_host_->transaction_size_map_.erase(host_transaction_id);
}

//////////////////////////////////////////////////////////////////////
// Helper templates.
//

template <typename ObjectType>
ObjectType* IndexedDBDispatcherHost::GetOrTerminateProcess(
    IDMap<ObjectType, IDMapOwnPointer>* map, int32 ipc_return_object_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  ObjectType* return_object = map->Lookup(ipc_return_object_id);
  if (!return_object) {
    NOTREACHED() << "Uh oh, couldn't find object with id "
                 << ipc_return_object_id;
    RecordAction(UserMetricsAction("BadMessageTerminate_IDBMF"));
    BadMessageReceived();
  }
  return return_object;
}

template <typename ObjectType>
void IndexedDBDispatcherHost::DestroyObject(
    IDMap<ObjectType, IDMapOwnPointer>* map, int32 ipc_object_id) {
  GetOrTerminateProcess(map, ipc_object_id);
  map->Remove(ipc_object_id);
}


//////////////////////////////////////////////////////////////////////
// IndexedDBDispatcherHost::DatabaseDispatcherHost
//

IndexedDBDispatcherHost::DatabaseDispatcherHost::DatabaseDispatcherHost(
    IndexedDBDispatcherHost* parent)
    : parent_(parent) {
  map_.set_check_on_null_data(true);
}

IndexedDBDispatcherHost::DatabaseDispatcherHost::~DatabaseDispatcherHost() {
  for (WebIDBObjectIDToURLMap::iterator iter = database_url_map_.begin();
       iter != database_url_map_.end(); iter++) {
    WebIDBDatabase* database = map_.Lookup(iter->first);
    if (database) {
      database->close();
      parent_->Context()->ConnectionClosed(iter->second, database);
    }
  }
}

bool IndexedDBDispatcherHost::DatabaseDispatcherHost::OnMessageReceived(
    const IPC::Message& message, bool* msg_is_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(IndexedDBDispatcherHost::DatabaseDispatcherHost,
                           message, *msg_is_ok)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseCreateObjectStore,
                        OnCreateObjectStore)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseDeleteObjectStore,
                        OnDeleteObjectStore)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseCreateTransaction,
                        OnCreateTransaction)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseClose, OnClose)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseDestroyed, OnDestroyed)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseGet, OnGet)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabasePutOld, OnPutOld)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabasePut, OnPut)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseSetIndexKeys,
                        OnSetIndexKeys)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseSetIndexesReady,
                        OnSetIndexesReady)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseOpenCursor, OnOpenCursor)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseCount, OnCount)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseDeleteRange, OnDeleteRange)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseClear, OnClear)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseCreateIndex,
                        OnCreateIndex)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseDeleteIndex,
                        OnDeleteIndex)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseAbort,
                        OnAbort)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseCommit,
                        OnCommit)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::Send(
    IPC::Message* message) {
  parent_->Send(message);
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnCreateObjectStore(
    const IndexedDBHostMsg_DatabaseCreateObjectStore_Params& params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, params.ipc_database_id);
  if (!database)
    return;

  int64 host_transaction_id = parent_->HostTransactionId(params.transaction_id);
  database->createObjectStore(
      host_transaction_id,
      params.object_store_id,
      params.name, params.key_path, params.auto_increment);
  if (parent_->Context()->IsOverQuota(
      database_url_map_[params.ipc_database_id])) {
    database->abort(host_transaction_id);
  }
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnDeleteObjectStore(
    int32 ipc_database_id,
    int64 transaction_id,
    int64 object_store_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, ipc_database_id);
  if (!database)
    return;

  database->deleteObjectStore(parent_->HostTransactionId(transaction_id),
                              object_store_id);
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnCreateTransaction(
    const IndexedDBHostMsg_DatabaseCreateTransaction_Params& params) {
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, params.ipc_database_id);
  if (!database)
      return;

  WebVector<long long> object_stores(params.object_store_ids.size());
  for (size_t i = 0; i < params.object_store_ids.size(); ++i)
      object_stores[i] = params.object_store_ids[i];

  int64 host_transaction_id = parent_->HostTransactionId(params.transaction_id);

  database->createTransaction(
      host_transaction_id,
      new IndexedDBDatabaseCallbacks(parent_, params.ipc_thread_id,
                                     params.ipc_database_response_id),
      object_stores, params.mode);
  parent_->RegisterTransactionId(host_transaction_id,
                                 database_url_map_[params.ipc_database_id]);
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnClose(
    int32 ipc_database_id) {
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, ipc_database_id);
  if (!database)
    return;
  database->close();
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnDestroyed(
    int32 ipc_object_id) {
  WebIDBDatabase* database = map_.Lookup(ipc_object_id);
  parent_->Context()->ConnectionClosed(database_url_map_[ipc_object_id],
                                       database);
  database_url_map_.erase(ipc_object_id);
  parent_->DestroyObject(&map_, ipc_object_id);
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnGet(
    const IndexedDBHostMsg_DatabaseGet_Params& params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, params.ipc_database_id);
  if (!database)
    return;

  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebSerializedScriptValue>(
          parent_, params.ipc_thread_id,
          params.ipc_response_id));
  database->get(parent_->HostTransactionId(params.transaction_id),
                params.object_store_id,
                params.index_id,
                params.key_range, params.key_only, callbacks.release());
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnPutOld(
    const IndexedDBHostMsg_DatabasePutOld_Params& params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));

  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, params.ipc_database_id);
  if (!database)
    return;
  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebIDBKey>(parent_, params.ipc_thread_id,
                                        params.ipc_response_id));
  if (params.index_ids.size() != params.index_keys.size()) {
    callbacks->onError(WebIDBDatabaseError(
        WebKit::WebIDBDatabaseExceptionUnknownError,
        "Malformed IPC message: index_ids.size() != index_keys.size()"));
    return;
  }

  WebVector<unsigned char> value(params.value);
  int64 host_transaction_id = parent_->HostTransactionId(params.transaction_id);
  database->put(host_transaction_id,
                params.object_store_id,
                &value, params.key,
                params.put_mode, callbacks.release(),
                params.index_ids,
                params.index_keys);
  TransactionIDToSizeMap* map =
      &parent_->database_dispatcher_host_->transaction_size_map_;
  // Size can't be big enough to overflow because it represents the
  // actual bytes passed through IPC.
  (*map)[host_transaction_id] += params.value.size();
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnPut(
    const IndexedDBHostMsg_DatabasePut_Params& params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));

  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, params.ipc_database_id);
  if (!database)
    return;
  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebIDBKey>(parent_, params.ipc_thread_id,
                                        params.ipc_response_id));
  // Be careful with empty vectors.
  WebData value;
  if (params.value.size())
      value.assign(&params.value.front(), params.value.size());
  int64 host_transaction_id = parent_->HostTransactionId(params.transaction_id);
  database->put(host_transaction_id,
                params.object_store_id,
                value, params.key,
                params.put_mode, callbacks.release(),
                params.index_ids,
                params.index_keys);
  TransactionIDToSizeMap* map =
      &parent_->database_dispatcher_host_->transaction_size_map_;
  // Size can't be big enough to overflow because it represents the
  // actual bytes passed through IPC.
  (*map)[host_transaction_id] += params.value.size();
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnSetIndexKeys(
    const IndexedDBHostMsg_DatabaseSetIndexKeys_Params& params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, params.ipc_database_id);
  if (!database)
    return;

  int64 host_transaction_id = parent_->HostTransactionId(params.transaction_id);
  if (params.index_ids.size() != params.index_keys.size()) {
    database->abort(host_transaction_id, WebIDBDatabaseError(
        WebKit::WebIDBDatabaseExceptionUnknownError,
        "Malformed IPC message: index_ids.size() != index_keys.size()"));
    return;
  }

  database->setIndexKeys(host_transaction_id,
                         params.object_store_id,
                         params.primary_key, params.index_ids,
                         params.index_keys);
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnSetIndexesReady(
    int32 ipc_database_id,
    int64 transaction_id,
    int64 object_store_id,
    const std::vector<int64>& index_ids) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, ipc_database_id);
  if (!database)
    return;

  database->setIndexesReady(parent_->HostTransactionId(transaction_id),
                            object_store_id,
                            WebVector<long long>(index_ids));
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnOpenCursor(
    const IndexedDBHostMsg_DatabaseOpenCursor_Params& params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, params.ipc_database_id);
  if (!database)
    return;

  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebIDBCursor>(parent_, params.ipc_thread_id,
                                           params.ipc_response_id, -1));
  database->openCursor(
      parent_->HostTransactionId(params.transaction_id),
      params.object_store_id, params.index_id,
      params.key_range, params.direction, params.key_only, params.task_type,
      callbacks.release());
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnCount(
    const IndexedDBHostMsg_DatabaseCount_Params& params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, params.ipc_database_id);
  if (!database)
    return;

  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebSerializedScriptValue>(
          parent_, params.ipc_thread_id,
          params.ipc_response_id));
  database->count(
      parent_->HostTransactionId(params.transaction_id),
      params.object_store_id, params.index_id,
      params.key_range, callbacks.release());
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnDeleteRange(
    const IndexedDBHostMsg_DatabaseDeleteRange_Params& params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, params.ipc_database_id);
  if (!database)
    return;

  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebSerializedScriptValue>(
          parent_, params.ipc_thread_id,
          params.ipc_response_id));
  database->deleteRange(parent_->HostTransactionId(params.transaction_id),
                        params.object_store_id,
                        params.key_range, callbacks.release());
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnClear(
    int32 ipc_thread_id,
    int32 ipc_response_id,
    int32 ipc_database_id,
    int64 transaction_id,
    int64 object_store_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, ipc_database_id);
  if (!database)
    return;

  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebSerializedScriptValue>(
          parent_, ipc_thread_id,
          ipc_response_id));

  database->clear(parent_->HostTransactionId(transaction_id),
                  object_store_id, callbacks.release());
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnAbort(
    int32 ipc_database_id,
    int64 transaction_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, ipc_database_id);
  if (!database)
    return;

  database->abort(parent_->HostTransactionId(transaction_id));
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnCommit(
    int32 ipc_database_id,
    int64 transaction_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, ipc_database_id);
  if (!database)
    return;

  int64 host_transaction_id = parent_->HostTransactionId(transaction_id);
  if (parent_->Context()->WouldBeOverQuota(
          transaction_url_map_[host_transaction_id],
          transaction_size_map_[host_transaction_id])) {
    database->abort(host_transaction_id, WebIDBDatabaseError(
        WebKit::WebIDBDatabaseExceptionQuotaError));
    return;
  }

  database->commit(host_transaction_id);
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnCreateIndex(
    const IndexedDBHostMsg_DatabaseCreateIndex_Params& params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, params.ipc_database_id);
  if (!database)
    return;

  int64 host_transaction_id = parent_->HostTransactionId(params.transaction_id);
  database->createIndex(
      host_transaction_id,
      params.object_store_id,
      params.index_id,
      params.name,
      params.key_path,
      params.unique,
      params.multi_entry);
  if (parent_->Context()->IsOverQuota(
      database_url_map_[params.ipc_database_id])) {
    database->abort(host_transaction_id);
  }
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnDeleteIndex(
    int32 ipc_database_id,
    int64 transaction_id,
    int64 object_store_id,
    int64 index_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, ipc_database_id);
  if (!database)
    return;

  database->deleteIndex(parent_->HostTransactionId(transaction_id),
                        object_store_id, index_id);
}

//////////////////////////////////////////////////////////////////////
// IndexedDBDispatcherHost::CursorDispatcherHost
//

IndexedDBDispatcherHost::CursorDispatcherHost::CursorDispatcherHost(
    IndexedDBDispatcherHost* parent)
    : parent_(parent) {
  map_.set_check_on_null_data(true);
}

IndexedDBDispatcherHost::CursorDispatcherHost::~CursorDispatcherHost() {
}

bool IndexedDBDispatcherHost::CursorDispatcherHost::OnMessageReceived(
    const IPC::Message& message, bool* msg_is_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(IndexedDBDispatcherHost::CursorDispatcherHost,
                           message, *msg_is_ok)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorAdvance, OnAdvance)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorContinue, OnContinue)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorPrefetch, OnPrefetch)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorPrefetchReset, OnPrefetchReset)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorDelete, OnDelete)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorDestroyed, OnDestroyed)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}


void IndexedDBDispatcherHost::CursorDispatcherHost::Send(
    IPC::Message* message) {
  parent_->Send(message);
}


void IndexedDBDispatcherHost::CursorDispatcherHost::OnAdvance(
    int32 ipc_cursor_id,
    int32 ipc_thread_id,
    int32 ipc_response_id,
    unsigned long count) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBCursor* idb_cursor = parent_->GetOrTerminateProcess(
      &map_, ipc_cursor_id);
  if (!idb_cursor)
    return;

  WebKit::WebExceptionCode ec = 0;
  idb_cursor->advance(count,
                      new IndexedDBCallbacks<WebIDBCursor>(parent_,
                                                           ipc_thread_id,
                                                           ipc_response_id,
                                                           ipc_cursor_id),
                      ec);
  DCHECK(!ec);
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnContinue(
    int32 ipc_cursor_id,
    int32 ipc_thread_id,
    int32 ipc_response_id,
    const IndexedDBKey& key) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_,
                                                            ipc_cursor_id);
  if (!idb_cursor)
    return;

  WebKit::WebExceptionCode ec = 0;
  idb_cursor->continueFunction(
      key, new IndexedDBCallbacks<WebIDBCursor>(parent_, ipc_thread_id,
                                                ipc_response_id,
                                                ipc_cursor_id), ec);
  DCHECK(!ec);
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnPrefetch(
    int32 ipc_cursor_id,
    int32 ipc_thread_id,
    int32 ipc_response_id,
    int n) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_,
                                                            ipc_cursor_id);
  if (!idb_cursor)
    return;

  WebKit::WebExceptionCode ec = 0;
  idb_cursor->prefetchContinue(
      n, new IndexedDBCallbacks<WebIDBCursor>(parent_, ipc_thread_id,
                                              ipc_response_id,
                                              ipc_cursor_id), ec);
  DCHECK(!ec);
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnPrefetchReset(
    int32 ipc_cursor_id, int used_prefetches, int unused_prefetches) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_,
                                                            ipc_cursor_id);
  if (!idb_cursor)
    return;

  idb_cursor->prefetchReset(used_prefetches, unused_prefetches);
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnDelete(
    int32 ipc_cursor_id,
    int32 ipc_thread_id,
    int32 ipc_response_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_,
                                                            ipc_cursor_id);
  if (!idb_cursor)
    return;

  WebKit::WebExceptionCode ec = 0;
  idb_cursor->deleteFunction(
      new IndexedDBCallbacks<WebSerializedScriptValue>(parent_, ipc_thread_id,
                                                       ipc_response_id), ec);
  DCHECK(!ec);
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnDestroyed(
    int32 ipc_object_id) {
  parent_->DestroyObject(&map_, ipc_object_id);
}

}  // namespace content