summaryrefslogtreecommitdiffstats
path: root/webkit/glue/plugins/plugin_host.cc
blob: 599816ffa4e37ba6ae9c0daced3ec9823274759f (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
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
// Copyright (c) 2006-2008 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.

// Pepper API support should be turned on for this module.
#define PEPPER_APIS_ENABLED

#include "webkit/glue/plugins/plugin_host.h"

#include "base/file_util.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "net/base/net_util.h"
#include "third_party/WebKit/WebKit/chromium/public/WebBindings.h"
#include "webkit/default_plugin/default_plugin_shared.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webplugininfo.h"
#include "webkit/glue/webplugin_delegate.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/pepper/pepper.h"
#include "webkit/glue/plugins/plugin_instance.h"
#include "webkit/glue/plugins/plugin_lib.h"
#include "webkit/glue/plugins/plugin_list.h"
#include "webkit/glue/plugins/plugin_stream_url.h"
#include "third_party/npapi/bindings/npruntime.h"

using WebKit::WebBindings;

namespace NPAPI
{
scoped_refptr<PluginHost> PluginHost::singleton_;

PluginHost::PluginHost() {
  InitializeHostFuncs();
}

PluginHost::~PluginHost() {
}

PluginHost *PluginHost::Singleton() {
  if (singleton_.get() == NULL) {
    singleton_ = new PluginHost();
  }

  DCHECK(singleton_.get() != NULL);
  return singleton_;
}

void PluginHost::InitializeHostFuncs() {
  memset(&host_funcs_, 0, sizeof(host_funcs_));
  host_funcs_.size = sizeof(host_funcs_);
  host_funcs_.version = (NP_VERSION_MAJOR << 8) | (NP_VERSION_MINOR);

  // The "basic" functions
  host_funcs_.geturl = &NPN_GetURL;
  host_funcs_.posturl = &NPN_PostURL;
  host_funcs_.requestread = &NPN_RequestRead;
  host_funcs_.newstream = &NPN_NewStream;
  host_funcs_.write = &NPN_Write;
  host_funcs_.destroystream = &NPN_DestroyStream;
  host_funcs_.status = &NPN_Status;
  host_funcs_.uagent = &NPN_UserAgent;
  host_funcs_.memalloc = &NPN_MemAlloc;
  host_funcs_.memfree = &NPN_MemFree;
  host_funcs_.memflush = &NPN_MemFlush;
  host_funcs_.reloadplugins = &NPN_ReloadPlugins;

  // We don't implement java yet
  host_funcs_.getJavaEnv = &NPN_GetJavaEnv;
  host_funcs_.getJavaPeer = &NPN_GetJavaPeer;

  // Advanced functions we implement
  host_funcs_.geturlnotify = &NPN_GetURLNotify;
  host_funcs_.posturlnotify = &NPN_PostURLNotify;
  host_funcs_.getvalue = &NPN_GetValue;
  host_funcs_.setvalue = &NPN_SetValue;
  host_funcs_.invalidaterect = &NPN_InvalidateRect;
  host_funcs_.invalidateregion = &NPN_InvalidateRegion;
  host_funcs_.forceredraw = &NPN_ForceRedraw;

  // These come from the Javascript Engine
  host_funcs_.getstringidentifier = WebBindings::getStringIdentifier;
  host_funcs_.getstringidentifiers = WebBindings::getStringIdentifiers;
  host_funcs_.getintidentifier = WebBindings::getIntIdentifier;
  host_funcs_.identifierisstring = WebBindings::identifierIsString;
  host_funcs_.utf8fromidentifier = WebBindings::utf8FromIdentifier;
  host_funcs_.intfromidentifier = WebBindings::intFromIdentifier;
  host_funcs_.createobject = WebBindings::createObject;
  host_funcs_.retainobject = WebBindings::retainObject;
  host_funcs_.releaseobject = WebBindings::releaseObject;
  host_funcs_.invoke = WebBindings::invoke;
  host_funcs_.invokeDefault = WebBindings::invokeDefault;
  host_funcs_.evaluate = WebBindings::evaluate;
  host_funcs_.getproperty = WebBindings::getProperty;
  host_funcs_.setproperty = WebBindings::setProperty;
  host_funcs_.removeproperty = WebBindings::removeProperty;
  host_funcs_.hasproperty = WebBindings::hasProperty;
  host_funcs_.hasmethod = WebBindings::hasMethod;
  host_funcs_.releasevariantvalue = WebBindings::releaseVariantValue;
  host_funcs_.setexception = WebBindings::setException;
  host_funcs_.pushpopupsenabledstate = NPN_PushPopupsEnabledState;
  host_funcs_.poppopupsenabledstate = NPN_PopPopupsEnabledState;
  host_funcs_.enumerate = WebBindings::enumerate;
  host_funcs_.pluginthreadasynccall = NPN_PluginThreadAsyncCall;
  host_funcs_.construct = WebBindings::construct;
  host_funcs_.getvalueforurl = NPN_GetValueForURL;
  host_funcs_.setvalueforurl = NPN_SetValueForURL;
  host_funcs_.getauthenticationinfo = NPN_GetAuthenticationInfo;
  host_funcs_.scheduletimer = NPN_ScheduleTimer;
  host_funcs_.unscheduletimer = NPN_UnscheduleTimer;
}

void PluginHost::PatchNPNetscapeFuncs(NPNetscapeFuncs* overrides) {
  // When running in the plugin process, we need to patch the NPN functions
  // that the plugin calls to interact with NPObjects that we give.  Otherwise
  // the plugin will call the v8 NPN functions, which won't work since we have
  // an NPObjectProxy and not a real v8 implementation.
  if (overrides->invoke)
    host_funcs_.invoke = overrides->invoke;

  if (overrides->invokeDefault)
    host_funcs_.invokeDefault = overrides->invokeDefault;

  if (overrides->evaluate)
    host_funcs_.evaluate = overrides->evaluate;

  if (overrides->getproperty)
    host_funcs_.getproperty = overrides->getproperty;

  if (overrides->setproperty)
    host_funcs_.setproperty = overrides->setproperty;

  if (overrides->removeproperty)
    host_funcs_.removeproperty = overrides->removeproperty;

  if (overrides->hasproperty)
    host_funcs_.hasproperty = overrides->hasproperty;

  if (overrides->hasmethod)
    host_funcs_.hasmethod = overrides->hasmethod;

  if (overrides->setexception)
    host_funcs_.setexception = overrides->setexception;

  if (overrides->enumerate)
    host_funcs_.enumerate = overrides->enumerate;
}

bool PluginHost::SetPostData(const char *buf,
                             uint32 length,
                             std::vector<std::string>* names,
                             std::vector<std::string>* values,
                             std::vector<char>* body) {
  // Use a state table to do the parsing.  Whitespace must be
  // trimmed after the fact if desired.  In our case, we actually
  // don't care about the whitespace, because we're just going to
  // pass this back into another POST.  This function strips out the
  // "Content-length" header and does not append it to the request.

  //
  // This parser takes action only on state changes.
  //
  // Transition table:
  //                  :       \n  NULL    Other
  // 0 GetHeader      1       2   4       0
  // 1 GetValue       1       0   3       1
  // 2 GetData        2       2   3       2
  // 3 DONE
  // 4 ERR
  //
  enum { INPUT_COLON=0, INPUT_NEWLINE, INPUT_NULL, INPUT_OTHER };
  enum { GETNAME, GETVALUE, GETDATA, DONE, ERR };
  int statemachine[3][4] = { { GETVALUE, GETDATA, GETDATA, GETNAME },
                             { GETVALUE, GETNAME, DONE, GETVALUE },
                             { GETDATA,  GETDATA, DONE, GETDATA } };
  std::string name, value;
  char *ptr = (char*)buf;
  char *start = ptr;
  int state = GETNAME;  // initial state
  bool done = false;
  bool err = false;
  do {
    int input;

    // Translate the current character into an input
    // for the state table.
    switch (*ptr) {
      case ':' :
        input = INPUT_COLON;
        break;
      case '\n':
        input = INPUT_NEWLINE;
        break;
      case 0   :
        input = INPUT_NULL;
        break;
      default  :
        input = INPUT_OTHER;
        break;
    }

    int newstate = statemachine[state][input];

    // Take action based on the new state.
    if (state != newstate) {
      switch (newstate) {
      case GETNAME:
        // Got a value.
        value = std::string(start, ptr - start);
        TrimWhitespace(value, TRIM_ALL, &value);
        // If the name field is empty, we'll skip this header
        // but we won't error out.
        if (!name.empty() && name != "content-length") {
          names->push_back(name);
          values->push_back(value);
        }
        start = ptr + 1;
        break;
      case GETVALUE:
        // Got a header.
        name = StringToLowerASCII(std::string(start, ptr - start));
        TrimWhitespace(name, TRIM_ALL, &name);
        start = ptr + 1;
        break;
      case GETDATA:
      {
        // Finished headers, now get body
        if (*ptr)
          start = ptr + 1;
        size_t previous_size = body->size();
        size_t new_body_size = length - static_cast<int>(start - buf);
        body->resize(previous_size + new_body_size);
        if (!body->empty())
          memcpy(&body->front() + previous_size, start, new_body_size);
        done = true;
        break;
      }
      case ERR:
        // error
        err = true;
        done = true;
        break;
      }
    }
    state = newstate;
    ptr++;
  } while (!done);

  return !err;
}

} // namespace NPAPI

extern "C" {

// FindInstance()
// Finds a PluginInstance from an NPP.
// The caller must take a reference if needed.
NPAPI::PluginInstance* FindInstance(NPP id) {
  if (id == NULL) {
    NOTREACHED();
    return NULL;
  }

  return (NPAPI::PluginInstance *)id->ndata;
}

// Allocates memory from the host's memory space.
void* NPN_MemAlloc(uint32 size) {
  scoped_refptr<NPAPI::PluginHost> host = NPAPI::PluginHost::Singleton();
  if (host != NULL) {
    // Note: We must use the same allocator/deallocator
    // that is used by the javascript library, as some of the
    // JS APIs will pass memory to the plugin which the plugin
    // will attempt to free.
    return malloc(size);
  }
  return NULL;
}

// Deallocates memory from the host's memory space
void NPN_MemFree(void* ptr) {
  scoped_refptr<NPAPI::PluginHost> host = NPAPI::PluginHost::Singleton();
  if (host != NULL) {
    if (ptr != NULL && ptr != (void*)-1) {
      free(ptr);
    }
  }
}

// Requests that the host free a specified amount of memory.
uint32 NPN_MemFlush(uint32 size) {
  // This is not relevant on Windows; MAC specific
  return size;
}

// This is for dynamic discovery of new plugins.
// Should force a re-scan of the plugins directory to load new ones.
void  NPN_ReloadPlugins(NPBool reloadPages) {
  // TODO: implement me
  DLOG(INFO) << "NPN_ReloadPlugin is not implemented yet.";
}

// Requests a range of bytes for a seekable stream.
NPError  NPN_RequestRead(NPStream* stream, NPByteRange* range_list) {
  if (!stream || !range_list) {
    return NPERR_GENERIC_ERROR;
  }

  scoped_refptr<NPAPI::PluginInstance> plugin =
      reinterpret_cast<NPAPI::PluginInstance*>(stream->ndata);
  if (!plugin.get()) {
    return NPERR_GENERIC_ERROR;
  }

  plugin->RequestRead(stream, range_list);
  return NPERR_NO_ERROR;
}

static bool IsJavaScriptUrl(const std::string& url) {
  return StartsWithASCII(url, "javascript:", false);
}

// Generic form of GetURL for common code between
// GetURL() and GetURLNotify().
static NPError GetURLNotify(NPP id,
                            const char* url,
                            const char* target,
                            bool notify,
                            void* notify_data) {
  if (!url)
    return NPERR_INVALID_URL;

  bool is_javascript_url = IsJavaScriptUrl(url);

  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  if (plugin.get()) {
    plugin->webplugin()->HandleURLRequest(
        "GET", is_javascript_url, target, 0, 0, false,
        notify, url, reinterpret_cast<intptr_t>(notify_data),
        plugin->popups_allowed());
  } else {
    NOTREACHED();
    return NPERR_GENERIC_ERROR;
  }
  return NPERR_NO_ERROR;
}

// Requests creation of a new stream with the contents of the
// specified URL; gets notification of the result.
NPError NPN_GetURLNotify(NPP id,
                         const char* url,
                         const char* target,
                         void* notify_data) {
  // This is identical to NPN_GetURL, but after finishing, the
  // browser will call NPP_URLNotify to inform the plugin that
  // it has completed.

  // According to the NPAPI documentation, if target == _self
  // or a parent to _self, the browser should return NPERR_INVALID_PARAM,
  // because it can't notify the plugin once deleted.  This is
  // absolutely false; firefox doesn't do this, and Flash relies on
  // being able to use this.

  // Also according to the NPAPI documentation, we should return
  // NPERR_INVALID_URL if the url requested is not valid.  However,
  // this would require that we synchronously start fetching the
  // URL.  That just isn't practical.  As such, there really is
  // no way to return this error.  From looking at the Firefox
  // implementation, it doesn't look like Firefox does this either.

  return GetURLNotify(id, url, target, true, notify_data);
}

NPError  NPN_GetURL(NPP id, const char* url, const char* target) {
  // Notes:
  //    Request from the Plugin to fetch content either for the plugin
  //    or to be placed into a browser window.
  //
  // If target == null, the browser fetches content and streams to plugin.
  //    otherwise, the browser loads content into an existing browser frame.
  // If the target is the window/frame containing the plugin, the plugin
  //    may be destroyed.
  // If the target is _blank, a mailto: or news: url open content in a new
  //    browser window
  // If the target is _self, no other instance of the plugin is created.  The
  //    plugin continues to operate in its own window

  return GetURLNotify(id, url, target, false, 0);
}

// Generic form of PostURL for common code between
// PostURL() and PostURLNotify().
static NPError PostURLNotify(NPP id,
                             const char* url,
                             const char* target,
                             uint32 len,
                             const char* buf,
                             NPBool file,
                             bool notify,
                             void* notify_data) {
  if (!url)
    return NPERR_INVALID_URL;

  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  if (!plugin.get()) {
    NOTREACHED();
    return NPERR_GENERIC_ERROR;
  }

  std::string post_file_contents;

  if (file) {
    // Post data to be uploaded from a file. This can be handled in two
    // ways.
    // 1. Read entire file and send the contents as if it was a post data
    //    specified in the argument
    // 2. Send just the file details and read them in the browser at the
    //    time of sending the request.
    // Approach 2 is more efficient but complicated. Approach 1 has a major
    // drawback of sending potentially large data over two IPC hops.  In a way
    // 'large data over IPC' problem exists as it is in case of plugin giving
    // the data directly instead of in a file.
    // Currently we are going with the approach 1 to get the feature working.
    // We can optimize this later with approach 2.

    // TODO(joshia): Design a scheme to send a file descriptor instead of
    // entire file contents across.

    // Security alert:
    // ---------------
    // Here we are blindly uploading whatever file requested by a plugin.
    // This is risky as someone could exploit a plugin to send private
    // data in arbitrary locations.
    // A malicious (non-sandboxed) plugin has unfeterred access to OS
    // resources and can do this anyway without using browser's HTTP stack.
    // FWIW, Firefox and Safari don't perform any security checks.

    if (!buf)
      return NPERR_FILE_NOT_FOUND;

    std::string file_path_ascii(buf);
    std::wstring file_path;
    static const char kFileUrlPrefix[] = "file:";
    if (StartsWithASCII(file_path_ascii, kFileUrlPrefix, false)) {
      GURL file_url(file_path_ascii);
      DCHECK(file_url.SchemeIsFile());
      FilePath path;
      net::FileURLToFilePath(file_url, &path);
      file_path = path.ToWStringHack();
    } else {
      file_path = base::SysNativeMBToWide(file_path_ascii);
    }

    file_util::FileInfo post_file_info = {0};
    if (!file_util::GetFileInfo(file_path.c_str(), &post_file_info) ||
        post_file_info.is_directory)
      return NPERR_FILE_NOT_FOUND;

    if (!file_util::ReadFileToString(file_path, &post_file_contents))
      return NPERR_FILE_NOT_FOUND;

    buf = post_file_contents.c_str();
    len = post_file_contents.size();
  }

  bool is_javascript_url = IsJavaScriptUrl(url);

  // The post data sent by a plugin contains both headers
  // and post data.  Example:
  //      Content-type: text/html
  //      Content-length: 200
  //
  //      <200 bytes of content here>
  //
  // Unfortunately, our stream needs these broken apart,
  // so we need to parse the data and set headers and data
  // separately.
  plugin->webplugin()->HandleURLRequest(
      "POST", is_javascript_url, target, len, buf, false, notify, url,
      reinterpret_cast<intptr_t>(notify_data), plugin->popups_allowed());
  return NPERR_NO_ERROR;
}

NPError  NPN_PostURLNotify(NPP id,
                           const char* url,
                           const char* target,
                           uint32 len,
                           const char* buf,
                           NPBool file,
                           void* notify_data) {
  return PostURLNotify(id, url, target, len, buf, file, true, notify_data);
}

NPError  NPN_PostURL(NPP id,
                     const char* url,
                     const char* target,
                     uint32 len,
                     const char* buf,
                     NPBool file) {
  // POSTs data to an URL, either from a temp file or a buffer.
  // If file is true, buf contains a temp file (which host will delete after
  //   completing), and len contains the length of the filename.
  // If file is false, buf contains the data to send, and len contains the
  //   length of the buffer
  //
  // If target is null,
  //   server response is returned to the plugin
  // If target is _current, _self, or _top,
  //   server response is written to the plugin window and plugin is unloaded.
  // If target is _new or _blank,
  //   server response is written to a new browser window
  // If target is an existing frame,
  //   server response goes to that frame.
  //
  // For protocols other than FTP
  //   file uploads must be line-end converted from \r\n to \n
  //
  // Note:  you cannot specify headers (even a blank line) in a memory buffer,
  //        use NPN_PostURLNotify

  return PostURLNotify(id, url, target, len, buf, file, false, 0);
}

NPError NPN_NewStream(NPP id,
                      NPMIMEType type,
                      const char* target,
                      NPStream** stream) {
  // Requests creation of a new data stream produced by the plugin,
  // consumed by the browser.
  //
  // Browser should put this stream into a window target.
  //
  // TODO: implement me
  DLOG(INFO) << "NPN_NewStream is not implemented yet.";
  return NPERR_GENERIC_ERROR;
}

int32 NPN_Write(NPP id, NPStream* stream, int32 len, void* buffer) {
  // Writes data to an existing Plugin-created stream.

  // TODO: implement me
  DLOG(INFO) << "NPN_Write is not implemented yet.";
  return NPERR_GENERIC_ERROR;
}

NPError NPN_DestroyStream(NPP id, NPStream* stream, NPReason reason) {
  // Destroys a stream (could be created by plugin or browser).
  //
  // Reasons:
  //    NPRES_DONE          - normal completion
  //    NPRES_USER_BREAK    - user terminated
  //    NPRES_NETWORK_ERROR - network error (all errors fit here?)
  //
  //

  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  if (plugin.get() == NULL) {
    NOTREACHED();
    return NPERR_GENERIC_ERROR;
  }

  return plugin->NPP_DestroyStream(stream, reason);
}

const char* NPN_UserAgent(NPP id) {
#if defined(OS_WIN)
  // Flash passes in a null id during the NP_initialize call.  We need to
  // default to the Mozilla user agent if we don't have an NPP instance or
  // else Flash won't request windowless mode.
  if (id) {
    scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
    if (plugin.get() && !plugin->use_mozilla_user_agent())
      return webkit_glue::GetUserAgent(GURL()).c_str();
  }

  return "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9a1) Gecko/20061103 Firefox/2.0a1";
#else
  // TODO(port): For now we always use our real useragent on Mac and Linux.
  // We might eventually need to spoof for some plugins.
  return webkit_glue::GetUserAgent(GURL()).c_str();
#endif
}

void NPN_Status(NPP id, const char* message) {
  // Displays a message on the status line of the browser window.

  // TODO: implement me
  DLOG(INFO) << "NPN_Status is not implemented yet.";
}

void NPN_InvalidateRect(NPP id, NPRect *invalidRect) {
  // Invalidates specified drawing area prior to repainting or refreshing a
  // windowless plugin

  // Before a windowless plugin can refresh part of its drawing area, it must
  // first invalidate it.  This function causes the NPP_HandleEvent method to
  // pass an update event or a paint message to the plug-in.  After calling
  // this method, the plug-in recieves a paint message asynchronously.

  // The browser redraws invalid areas of the document and any windowless
  // plug-ins at regularly timed intervals. To force a paint message, the
  // plug-in can call NPN_ForceRedraw after calling this method.

  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  DCHECK(plugin.get() != NULL);
  if (plugin.get() && plugin->webplugin()) {
    if (invalidRect) {
#if defined(OS_WIN)
      if (!plugin->windowless()) {
        RECT rect = {0};
        rect.left = invalidRect->left;
        rect.right = invalidRect->right;
        rect.top = invalidRect->top;
        rect.bottom = invalidRect->bottom;
        ::InvalidateRect(plugin->window_handle(), &rect, FALSE);
        return;
      }
#endif
      gfx::Rect rect(invalidRect->left,
                     invalidRect->top,
                     invalidRect->right - invalidRect->left,
                     invalidRect->bottom - invalidRect->top);
      plugin->webplugin()->InvalidateRect(rect);
    } else {
      plugin->webplugin()->Invalidate();
    }
  }
}

void NPN_InvalidateRegion(NPP id, NPRegion invalidRegion) {
  // Invalidates a specified drawing region prior to repainting
  // or refreshing a window-less plugin.
  //
  // Similar to NPN_InvalidateRect.

  // TODO: this is overkill--add platform-specific region handling (at the
  // very least, fetch the region's bounding box and pass it to InvalidateRect).
  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  DCHECK(plugin.get() != NULL);
  if (plugin.get() && plugin->webplugin()) {
    plugin->webplugin()->Invalidate();
  }
}

void NPN_ForceRedraw(NPP id) {
  // Forces repaint for a windowless plug-in.
  //
  // Once a value has been invalidated with NPN_InvalidateRect/
  // NPN_InvalidateRegion, ForceRedraw can be used to force a paint message.
  //
  // The plugin will receive a WM_PAINT message, the lParam of the WM_PAINT
  // message holds a pointer to an NPRect that is the bounding box of the
  // update area.
  // Since the plugin and browser share the same HDC, before drawing, the
  // plugin is responsible fro saving the current HDC settings, setting up
  // its own environment, drawing, and restoring the HDC to the previous
  // settings.  The HDC settings must be restored whenever control returns
  // back to the browser, either before returning from NPP_HandleEvent or
  // before calling a drawing-related netscape method.

  NOTIMPLEMENTED();
}

#if defined(PEPPER_APIS_ENABLED)
static NPError InitializeRenderContext(NPP id,
                                       NPRenderType type,
                                       NPRenderContext* context) {
  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  if (plugin) {
    webkit_glue::WebPluginDelegate* delegate = plugin->webplugin()->delegate();
    // Set up the renderer for the specified type.
    return delegate->InitializeRenderContext(type, context);
  }
  return NPERR_GENERIC_ERROR;
}

static NPError FlushRenderContext(NPP id,
                                  NPRenderContext* context,
                                  NPFlushRenderContextCallbackPtr callback,
                                  void* user_data) {
  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  if (plugin) {
    webkit_glue::WebPluginDelegate* delegate = plugin->webplugin()->delegate();
    // Do the flush.
    NPError err = delegate->FlushRenderContext(context);

    // Invoke the callback to inform the caller the work was done.
    if (callback != NULL)
      (*callback)(context, err, user_data);

    // Return any errors.
    return err;
  }
  return NPERR_GENERIC_ERROR;
}

static NPError DestroyRenderContext(NPP id,
                                    NPRenderContext* context) {
  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  if (plugin) {
    webkit_glue::WebPluginDelegate* delegate = plugin->webplugin()->delegate();
    return delegate->DestroyRenderContext(context);
  }
  return NPERR_GENERIC_ERROR;
}

static NPError OpenFileInSandbox(NPP id, const char* file_name, void** handle) {
  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  if (!plugin)
    return NPERR_GENERIC_ERROR;
  webkit_glue::WebPluginDelegate* delegate = plugin->webplugin()->delegate();
  return delegate->OpenFileInSandbox(file_name, handle);
}
#endif  // defined(PEPPER_APIS_ENABLED)

NPError NPN_GetValue(NPP id, NPNVariable variable, void *value) {
  // Allows the plugin to query the browser for information
  //
  // Variables:
  //    NPNVxDisplay (unix only)
  //    NPNVxtAppContext (unix only)
  //    NPNVnetscapeWindow (win only) - Gets the native window on which the
  //              plug-in drawing occurs, returns HWND
  //    NPNVjavascriptEnabledBool:  tells whether Javascript is enabled
  //    NPNVasdEnabledBool:  tells whether SmartUpdate is enabled
  //    NPNVOfflineBool: tells whether offline-mode is enabled

  NPError rv = NPERR_GENERIC_ERROR;

  switch (variable) {
  case NPNVWindowNPObject:
  {
    scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
    NPObject *np_object = plugin->webplugin()->GetWindowScriptNPObject();
    // Return value is expected to be retained, as
    // described here:
    // <http://www.mozilla.org/projects/plugins/npruntime.html#browseraccess>
    if (np_object) {
      WebBindings::retainObject(np_object);
      void **v = (void **)value;
      *v = np_object;
      rv = NPERR_NO_ERROR;
    } else {
      NOTREACHED();
    }
    break;
  }
  case NPNVPluginElementNPObject:
  {
    scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
    NPObject *np_object = plugin->webplugin()->GetPluginElement();
    // Return value is expected to be retained, as
    // described here:
    // <http://www.mozilla.org/projects/plugins/npruntime.html#browseraccess>
    if (np_object) {
      WebBindings::retainObject(np_object);
      void **v = (void **)value;
      *v = np_object;
      rv = NPERR_NO_ERROR;
    } else {
      NOTREACHED();
    }
    break;
  }
  case NPNVnetscapeWindow:
  {
#if defined(OS_WIN) || defined(OS_LINUX)
    scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
    gfx::PluginWindowHandle handle = plugin->window_handle();
    *((void**)value) = (void*)handle;
    rv = NPERR_NO_ERROR;
#else
    NOTIMPLEMENTED();
#endif
    break;
  }
  case NPNVjavascriptEnabledBool:
  {
    // yes, JS is enabled.
    *((void**)value) = (void*)1;
    rv = NPERR_NO_ERROR;
    break;
  }
#if defined(OS_LINUX)
  case NPNVToolkit:
    // Tell them we are GTK2.  (The alternative is GTK 1.2.)
    *reinterpret_cast<int*>(value) = NPNVGtk2;
    rv = NPERR_NO_ERROR;
    break;

  case NPNVSupportsXEmbedBool:
    // Yes, we support XEmbed.
    *reinterpret_cast<NPBool*>(value) = TRUE;
    rv = NPERR_NO_ERROR;
    break;
#endif
  case NPNVSupportsWindowless:
  {
    NPBool* supports_windowless = reinterpret_cast<NPBool*>(value);
    *supports_windowless = TRUE;
    rv = NPERR_NO_ERROR;
    break;
  }
  case NPNVprivateModeBool:
  {
    NPBool* private_mode = reinterpret_cast<NPBool*>(value);
    scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
    *private_mode = plugin->webplugin()->IsOffTheRecord();
    rv = NPERR_NO_ERROR;
    break;
  }
  case default_plugin::kMissingPluginStatusStart +
       default_plugin::MISSING_PLUGIN_AVAILABLE:
  // fall through
  case default_plugin::kMissingPluginStatusStart +
       default_plugin::MISSING_PLUGIN_USER_STARTED_DOWNLOAD:
  {
    // This is a hack for the default plugin to send notification to renderer.
    // Even though we check if the plugin is the default plugin, we still need
    // to worry about future standard change that may conflict with the
    // variable definition, in order to avoid duplicate case clauses in this
    // big switch statement.
    scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
    if (plugin->plugin_lib()->plugin_info().path.value() ==
          kDefaultPluginLibraryName) {
      plugin->webplugin()->OnMissingPluginStatus(
          variable - default_plugin::kMissingPluginStatusStart);
    }
    break;
  }
#if defined(OS_MACOSX)
  case NPNVpluginDrawingModel:
  {
    // return the drawing model that was negotiated when we initialized.
    scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
    *reinterpret_cast<int*>(value) = plugin->drawing_model();
    rv = NPERR_NO_ERROR;
    break;
  }
  case NPNVsupportsQuickDrawBool:
  {
    // we do not admit to supporting the QuickDraw drawing model.
    NPBool* supports_qd = reinterpret_cast<NPBool*>(value);
    *supports_qd = FALSE;
    rv = NPERR_NO_ERROR;
    break;
  }
  case NPNVsupportsCoreGraphicsBool:
  case NPNVsupportsCarbonBool:
  case NPNVsupportsCocoaBool:
  {
    // we do support these drawing and event models.
    NPBool* supports_model = reinterpret_cast<NPBool*>(value);
    *supports_model = TRUE;
    rv = NPERR_NO_ERROR;
    break;
  }
  case NPNVsupportsOpenGLBool:
  case NPNVsupportsCoreAnimationBool:
  {
    // we do not support these drawing and event models.
    NPBool* supports_model = reinterpret_cast<NPBool*>(value);
    *supports_model = FALSE;
    rv = NPERR_NO_ERROR;
    break;
  }
#endif
#if defined(PEPPER_APIS_ENABLED)
  case NPNVPepperExtensions:
  {
    static const NPPepperExtensions kExtensions = {
      InitializeRenderContext,
      FlushRenderContext,
      DestroyRenderContext,
      OpenFileInSandbox,
    };
    // Return a pointer to the canonical function table.
    NPPepperExtensions* extensions =
        const_cast<NPPepperExtensions*>(&kExtensions);
    NPPepperExtensions** exts = reinterpret_cast<NPPepperExtensions**>(value);
    *exts = extensions;
    rv = NPERR_NO_ERROR;
    break;
  }
#endif  // defined(PEPPER_APIS_ENABLED)
  default:
  {
    // TODO: implement me
    DLOG(INFO) << "NPN_GetValue(" << variable << ") is not implemented yet.";
    break;
  }
  }
  return rv;
}

NPError  NPN_SetValue(NPP id, NPPVariable variable, void *value) {
  // Allows the plugin to set various modes

  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  switch(variable)
  {
  case NPPVpluginWindowBool:
  {
    // Sets windowless mode for display of the plugin
    // Note: the documentation at http://developer.mozilla.org/en/docs/NPN_SetValue
    // is wrong.  When value is NULL, the mode is set to true.  This is the same
    // way Mozilla works.
    plugin->set_windowless(value == 0);
    return NPERR_NO_ERROR;
  }
  case NPPVpluginTransparentBool:
  {
    // Sets transparent mode for display of the plugin
    //
    // Transparent plugins require the browser to paint the background
    // before having the plugin paint.  By default, windowless plugins
    // are transparent.  Making a windowless plugin opaque means that
    // the plugin does not require the browser to paint the background.
    //
    bool mode = (value != 0);
    plugin->set_transparent(mode);
    return NPERR_NO_ERROR;
  }
  case NPPVjavascriptPushCallerBool:
    // Specifies whether you are pushing or popping the JSContext off
    // the stack
    // TODO: implement me
    DLOG(INFO) << "NPN_SetValue(NPPVJavascriptPushCallerBool) is not implemented.";
    return NPERR_GENERIC_ERROR;
  case NPPVpluginKeepLibraryInMemory:
    // Tells browser that plugin library should live longer than usual.
    // TODO: implement me
    DLOG(INFO) << "NPN_SetValue(NPPVpluginKeepLibraryInMemory) is not implemented.";
    return NPERR_GENERIC_ERROR;
#if defined(OS_MACOSX)
  case NPPVpluginDrawingModel:
  {
    // we only admit to supporting the CoreGraphics drawing model.  The logic
    // here is that our QuickDraw plugin support is so rudimentary that we
    // only want to use it as a fallback to keep plugins from crashing: if
    // a plugin knows enough to ask, we want them to use CoreGraphics.
    int model = reinterpret_cast<int>(value);
    if (model == NPDrawingModelCoreGraphics) {
      plugin->set_drawing_model(model);
      return NPERR_NO_ERROR;
    }
    return NPERR_GENERIC_ERROR;
  }
  case NPPVpluginEventModel:
  {
    // we support Carbon and Cocoa event models
    int model = reinterpret_cast<int>(value);
    switch (model) {
      case NPNVsupportsCarbonBool:
      case NPNVsupportsCocoaBool:
        plugin->set_event_model(model);
        return NPERR_NO_ERROR;
        break;
    }
    return NPERR_GENERIC_ERROR;
  }
#endif
  default:
    // TODO: implement me
    DLOG(INFO) << "NPN_SetValue(" << variable << ") is not implemented.";
    break;
  }

  NOTREACHED();
  return NPERR_GENERIC_ERROR;
}

void *NPN_GetJavaEnv() {
  // TODO: implement me
  DLOG(INFO) << "NPN_GetJavaEnv is not implemented.";
  return NULL;
}

void *NPN_GetJavaPeer(NPP) {
  // TODO: implement me
  DLOG(INFO) << "NPN_GetJavaPeer is not implemented.";
  return NULL;
}

void NPN_PushPopupsEnabledState(NPP id, NPBool enabled) {
  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  if (plugin) {
    plugin->PushPopupsEnabledState(enabled);
  }
}

void NPN_PopPopupsEnabledState(NPP id) {
  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  if (plugin) {
    plugin->PopPopupsEnabledState();
  }
}

void NPN_PluginThreadAsyncCall(NPP id,
                               void (*func)(void *),
                               void *userData) {
  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  if (plugin) {
    plugin->PluginThreadAsyncCall(func, userData);
  }
}

NPError NPN_GetValueForURL(NPP id,
                           NPNURLVariable variable,
                           const char *url,
                           char **value,
                           uint32_t *len) {
  if (!id)
    return NPERR_INVALID_PARAM;

  if (!url || !*url || !len)
    return NPERR_INVALID_URL;

  *len = 0;
  std::string result;

  switch (variable) {
    case NPNURLVProxy: {
      result = "DIRECT";
      if (!webkit_glue::FindProxyForUrl(GURL((std::string(url))), &result))
        return NPERR_GENERIC_ERROR;

      break;
    }
    case NPNURLVCookie: {
      scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
      if (!plugin)
        return NPERR_GENERIC_ERROR;

      webkit_glue::WebPlugin* webplugin = plugin->webplugin();
      if (!webplugin)
        return NPERR_GENERIC_ERROR;

      // Bypass third-party cookie blocking by using the url as the policy_url.
      GURL cookies_url((std::string(url)));
      result = webplugin->GetCookies(cookies_url, cookies_url);
      break;
    }
    default:
      return NPERR_GENERIC_ERROR;
  }

  // Allocate this using the NPAPI allocator. The plugin will call
  // NPN_Free to free this.
  *value = static_cast<char*>(NPN_MemAlloc(result.length() + 1));
  strncpy(*value, result.c_str(), result.length() + 1);
  *len = result.length();

  return NPERR_NO_ERROR;
}

NPError NPN_SetValueForURL(NPP id,
                           NPNURLVariable variable,
                           const char *url,
                           const char *value,
                           uint32_t len) {
  if (!id)
    return NPERR_INVALID_PARAM;

  if (!url || !*url)
    return NPERR_INVALID_URL;

  switch (variable) {
    case NPNURLVCookie: {
      scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
      if (!plugin)
        return NPERR_GENERIC_ERROR;

      webkit_glue::WebPlugin* webplugin = plugin->webplugin();
      if (!webplugin)
        return NPERR_GENERIC_ERROR;

      std::string cookie(value, len);
      GURL cookies_url((std::string(url)));
      webplugin->SetCookie(cookies_url, cookies_url, cookie);
      return NPERR_NO_ERROR;
    }
    case NPNURLVProxy:
      // We don't support setting proxy values, fall through...
      break;
    default:
      // Fall through and return an error...
      break;
  }

  return NPERR_GENERIC_ERROR;
}

NPError NPN_GetAuthenticationInfo(NPP id,
                                  const char *protocol,
                                  const char *host,
                                  int32_t port,
                                  const char *scheme,
                                  const char *realm,
                                  char **username,
                                  uint32_t *ulen,
                                  char **password,
                                  uint32_t *plen) {
  if (!id || !protocol || !host || !scheme || !realm || !username ||
      !ulen || !password || !plen)
    return NPERR_INVALID_PARAM;

  // TODO: implement me (bug 23928)
  return NPERR_GENERIC_ERROR;
}

uint32 NPN_ScheduleTimer(NPP id,
                         uint32 interval,
                         NPBool repeat,
                         void (*func)(NPP id, uint32 timer_id)) {
  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  if (!plugin)
    return 0;

  return plugin->ScheduleTimer(interval, repeat, func);
}

void NPN_UnscheduleTimer(NPP id, uint32 timer_id) {
  scoped_refptr<NPAPI::PluginInstance> plugin = FindInstance(id);
  if (plugin)
    plugin->UnscheduleTimer(timer_id);
}
} // extern "C"