Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / native_client_sdk / src / libraries / nacl_io / httpfs / http_fs_node.cc
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "nacl_io/httpfs/http_fs_node.h"
6
7 #include <assert.h>
8 #include <errno.h>
9 #include <stdio.h>
10 #include <string.h>
11
12 #include <ppapi/c/pp_errors.h>
13
14 #include "nacl_io/httpfs/http_fs.h"
15 #include "nacl_io/kernel_handle.h"
16 #include "nacl_io/osinttypes.h"
17
18 #if defined(WIN32)
19 #define snprintf _snprintf
20 #endif
21
22 namespace nacl_io {
23
24 namespace {
25
26 // If we're attempting to read a partial request, but the server returns a full
27 // request, we need to read all of the data up to the start of our partial
28 // request into a dummy buffer. This is the maximum size of that buffer.
29 const int MAX_READ_BUFFER_SIZE = 64 * 1024;
30 const int32_t STATUSCODE_OK = 200;
31 const int32_t STATUSCODE_PARTIAL_CONTENT = 206;
32 const int32_t STATUSCODE_FORBIDDEN = 403;
33 const int32_t STATUSCODE_NOT_FOUND = 404;
34 const int32_t STATUSCODE_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
35
36 StringMap_t ParseHeaders(const char* headers, int32_t headers_length) {
37   enum State {
38     FINDING_KEY,
39     SKIPPING_WHITESPACE,
40     FINDING_VALUE,
41   };
42
43   StringMap_t result;
44   std::string key;
45   std::string value;
46
47   State state = FINDING_KEY;
48   const char* start = headers;
49   for (int i = 0; i < headers_length; ++i) {
50     switch (state) {
51       case FINDING_KEY:
52         if (headers[i] == ':') {
53           // Found key.
54           key.assign(start, &headers[i] - start);
55           key = NormalizeHeaderKey(key);
56           state = SKIPPING_WHITESPACE;
57         }
58         break;
59
60       case SKIPPING_WHITESPACE:
61         if (headers[i] == ' ') {
62           // Found whitespace, keep going...
63           break;
64         }
65
66         // Found a non-whitespace, mark this as the start of the value.
67         start = &headers[i];
68         state = FINDING_VALUE;
69       // Fallthrough to start processing value without incrementing i.
70
71       case FINDING_VALUE:
72         if (headers[i] == '\n') {
73           // Found value.
74           value.assign(start, &headers[i] - start);
75           result[key] = value;
76           start = &headers[i + 1];
77           state = FINDING_KEY;
78         }
79         break;
80     }
81   }
82
83   return result;
84 }
85
86 bool ParseContentLength(const StringMap_t& headers, off_t* content_length) {
87   StringMap_t::const_iterator iter = headers.find("Content-Length");
88   if (iter == headers.end())
89     return false;
90
91   *content_length = strtoull(iter->second.c_str(), NULL, 10);
92   return true;
93 }
94
95 bool ParseContentRange(const StringMap_t& headers,
96                        off_t* read_start,
97                        off_t* read_end,
98                        off_t* entity_length) {
99   StringMap_t::const_iterator iter = headers.find("Content-Range");
100   if (iter == headers.end())
101     return false;
102
103   // The key should look like "bytes ##-##/##" or "bytes ##-##/*". The last
104   // value is the entity length, which can potentially be * (i.e. unknown).
105   off_t read_start_int;
106   off_t read_end_int;
107   off_t entity_length_int;
108   int result = sscanf(iter->second.c_str(),
109                       "bytes %" SCNi64 "-%" SCNi64 "/%" SCNi64,
110                       &read_start_int,
111                       &read_end_int,
112                       &entity_length_int);
113
114   // The Content-Range header specifies an inclusive range: e.g. the first ten
115   // bytes is "bytes 0-9/*". Convert it to a half-open range by incrementing
116   // read_end.
117   if (result == 2) {
118     if (read_start)
119       *read_start = read_start_int;
120     if (read_end)
121       *read_end = read_end_int + 1;
122     if (entity_length)
123       *entity_length = 0;
124     return true;
125   } else if (result == 3) {
126     if (read_start)
127       *read_start = read_start_int;
128     if (read_end)
129       *read_end = read_end_int + 1;
130     if (entity_length)
131       *entity_length = entity_length_int;
132     return true;
133   }
134
135   return false;
136 }
137
138 // Maps an HTTP |status_code| onto the appropriate errno code.
139 int HTTPStatusCodeToErrno(int status_code) {
140   switch (status_code) {
141     case STATUSCODE_OK:
142     case STATUSCODE_PARTIAL_CONTENT:
143       return 0;
144     case STATUSCODE_FORBIDDEN:
145       return EACCES;
146     case STATUSCODE_NOT_FOUND:
147       return ENOENT;
148   }
149   if (status_code >= 400 && status_code < 500)
150     return EINVAL;
151   return EIO;
152 }
153
154 }  // namespace
155
156 void HttpFsNode::SetCachedSize(off_t size) {
157   has_cached_size_ = true;
158   stat_.st_size = size;
159 }
160
161 Error HttpFsNode::FSync() {
162   return EACCES;
163 }
164
165 Error HttpFsNode::GetDents(size_t offs,
166                            struct dirent* pdir,
167                            size_t count,
168                            int* out_bytes) {
169   *out_bytes = 0;
170   return EACCES;
171 }
172
173 Error HttpFsNode::GetStat(struct stat* stat) {
174   AUTO_LOCK(node_lock_);
175   return GetStat_Locked(stat);
176 }
177
178 Error HttpFsNode::Read(const HandleAttr& attr,
179                        void* buf,
180                        size_t count,
181                        int* out_bytes) {
182   *out_bytes = 0;
183
184   AUTO_LOCK(node_lock_);
185   if (cache_content_) {
186     if (cached_data_.empty()) {
187       Error error = DownloadToCache();
188       if (error)
189         return error;
190     }
191
192     return ReadPartialFromCache(attr, buf, count, out_bytes);
193   }
194
195   return DownloadPartial(attr, buf, count, out_bytes);
196 }
197
198 Error HttpFsNode::FTruncate(off_t size) {
199   return EACCES;
200 }
201
202 Error HttpFsNode::Write(const HandleAttr& attr,
203                         const void* buf,
204                         size_t count,
205                         int* out_bytes) {
206   // TODO(binji): support POST?
207   *out_bytes = 0;
208   return EACCES;
209 }
210
211 Error HttpFsNode::GetSize(off_t* out_size) {
212   *out_size = 0;
213
214   // TODO(binji): This value should be cached properly; i.e. obey the caching
215   // headers returned by the server.
216   AUTO_LOCK(node_lock_);
217   struct stat statbuf;
218   Error error = GetStat_Locked(&statbuf);
219   if (error)
220     return error;
221
222   *out_size = stat_.st_size;
223   return 0;
224 }
225
226 HttpFsNode::HttpFsNode(Filesystem* filesystem,
227                        const std::string& url,
228                        bool cache_content)
229     : Node(filesystem),
230       url_(url),
231       buffer_(NULL),
232       buffer_len_(0),
233       cache_content_(cache_content),
234       has_cached_size_(false) {
235 }
236
237 void HttpFsNode::SetMode(int mode) {
238   stat_.st_mode = mode;
239 }
240
241 Error HttpFsNode::GetStat_Locked(struct stat* stat) {
242   // Assume we need to 'HEAD' if we do not know the size, otherwise, assume
243   // that the information is constant.  We can add a timeout if needed.
244   HttpFs* filesystem = static_cast<HttpFs*>(filesystem_);
245   if (!has_cached_size_ || !filesystem->cache_stat_) {
246     StringMap_t headers;
247     ScopedResource loader(filesystem_->ppapi());
248     ScopedResource request(filesystem_->ppapi());
249     ScopedResource response(filesystem_->ppapi());
250     int32_t statuscode;
251     StringMap_t response_headers;
252     const char* method = "HEAD";
253
254     if (filesystem->is_blob_url_) {
255       // Blob URLs do not support HEAD requests, but do give the content length
256       // in their response headers. We issue a single-byte GET request to
257       // retrieve the content length.
258       method = "GET";
259       headers["Range"] = "bytes=0-0";
260     }
261
262     Error error = OpenUrl(method,
263                           &headers,
264                           &loader,
265                           &request,
266                           &response,
267                           &statuscode,
268                           &response_headers);
269     if (error)
270       return error;
271
272     off_t entity_length;
273     if (ParseContentRange(response_headers, NULL, NULL, &entity_length)) {
274       SetCachedSize(static_cast<off_t>(entity_length));
275     } else if (ParseContentLength(response_headers, &entity_length)) {
276       SetCachedSize(static_cast<off_t>(entity_length));
277     } else if (cache_content_) {
278       // The server didn't give a content length; download the data to memory
279       // via DownloadToCache, which will also set stat_.st_size;
280       error = DownloadToCache();
281       if (error)
282         return error;
283     } else {
284       // The user doesn't want to cache content, but we didn't get a
285       // "Content-Length" header. Read the entire entity, and throw it away.
286       // Don't use DownloadToCache, as that will still allocate enough memory
287       // for the entire entity.
288       off_t bytes_read;
289       error = DownloadToTemp(&bytes_read);
290       if (error)
291         return error;
292
293       SetCachedSize(bytes_read);
294     }
295
296     stat_.st_atime = 0;  // TODO(binji): Use "Last-Modified".
297     stat_.st_mtime = 0;
298     stat_.st_ctime = 0;
299
300     stat_.st_mode |= S_IFREG;
301   }
302
303   // Fill the stat structure if provided
304   if (stat)
305     *stat = stat_;
306
307   return 0;
308 }
309
310 Error HttpFsNode::OpenUrl(const char* method,
311                           StringMap_t* request_headers,
312                           ScopedResource* out_loader,
313                           ScopedResource* out_request,
314                           ScopedResource* out_response,
315                           int32_t* out_statuscode,
316                           StringMap_t* out_response_headers) {
317   // Clear all out parameters.
318   *out_statuscode = 0;
319   out_response_headers->clear();
320
321   // Assume lock_ is already held.
322   PepperInterface* ppapi = filesystem_->ppapi();
323
324   HttpFs* mount_http = static_cast<HttpFs*>(filesystem_);
325   out_request->Reset(
326       mount_http->MakeUrlRequestInfo(url_, method, request_headers));
327   if (!out_request->pp_resource())
328     return EINVAL;
329
330   URLLoaderInterface* loader_interface = ppapi->GetURLLoaderInterface();
331   URLResponseInfoInterface* response_interface =
332       ppapi->GetURLResponseInfoInterface();
333   VarInterface* var_interface = ppapi->GetVarInterface();
334
335   out_loader->Reset(loader_interface->Create(ppapi->GetInstance()));
336   if (!out_loader->pp_resource())
337     return EINVAL;
338
339   int32_t result = loader_interface->Open(out_loader->pp_resource(),
340                                           out_request->pp_resource(),
341                                           PP_BlockUntilComplete());
342   if (result != PP_OK)
343     return PPErrorToErrno(result);
344
345   out_response->Reset(
346       loader_interface->GetResponseInfo(out_loader->pp_resource()));
347   if (!out_response->pp_resource())
348     return EINVAL;
349
350   // Get response statuscode.
351   PP_Var statuscode = response_interface->GetProperty(
352       out_response->pp_resource(), PP_URLRESPONSEPROPERTY_STATUSCODE);
353
354   if (statuscode.type != PP_VARTYPE_INT32)
355     return EINVAL;
356
357   *out_statuscode = statuscode.value.as_int;
358
359   // Only accept OK or Partial Content.
360   Error error = HTTPStatusCodeToErrno(*out_statuscode);
361   if (error)
362     return error;
363
364   // Get response headers.
365   PP_Var response_headers_var = response_interface->GetProperty(
366       out_response->pp_resource(), PP_URLRESPONSEPROPERTY_HEADERS);
367
368   uint32_t response_headers_length;
369   const char* response_headers_str =
370       var_interface->VarToUtf8(response_headers_var, &response_headers_length);
371
372   *out_response_headers =
373       ParseHeaders(response_headers_str, response_headers_length);
374
375   var_interface->Release(response_headers_var);
376
377   return 0;
378 }
379
380 Error HttpFsNode::DownloadToCache() {
381   StringMap_t headers;
382   ScopedResource loader(filesystem_->ppapi());
383   ScopedResource request(filesystem_->ppapi());
384   ScopedResource response(filesystem_->ppapi());
385   int32_t statuscode;
386   StringMap_t response_headers;
387   Error error = OpenUrl("GET",
388                         &headers,
389                         &loader,
390                         &request,
391                         &response,
392                         &statuscode,
393                         &response_headers);
394   if (error)
395     return error;
396
397   off_t content_length = 0;
398   if (ParseContentLength(response_headers, &content_length)) {
399     cached_data_.resize(content_length);
400     int real_size;
401     error = ReadResponseToBuffer(
402         loader, cached_data_.data(), content_length, &real_size);
403     if (error)
404       return error;
405
406     SetCachedSize(real_size);
407     cached_data_.resize(real_size);
408     return 0;
409   }
410
411   int bytes_read;
412   error = ReadEntireResponseToCache(loader, &bytes_read);
413   if (error)
414     return error;
415
416   SetCachedSize(bytes_read);
417   return 0;
418 }
419
420 Error HttpFsNode::ReadPartialFromCache(const HandleAttr& attr,
421                                        void* buf,
422                                        int count,
423                                        int* out_bytes) {
424   *out_bytes = 0;
425   off_t size = cached_data_.size();
426
427   if (attr.offs + count > size)
428     count = size - attr.offs;
429
430   if (count <= 0)
431     return 0;
432
433   memcpy(buf, &cached_data_.data()[attr.offs], count);
434   *out_bytes = count;
435   return 0;
436 }
437
438 Error HttpFsNode::DownloadPartial(const HandleAttr& attr,
439                                   void* buf,
440                                   off_t count,
441                                   int* out_bytes) {
442   *out_bytes = 0;
443
444   StringMap_t headers;
445
446   char buffer[100];
447   // Range request is inclusive: 0-99 returns 100 bytes.
448   snprintf(&buffer[0],
449            sizeof(buffer),
450            "bytes=%" PRIi64 "-%" PRIi64,
451            attr.offs,
452            attr.offs + count - 1);
453   headers["Range"] = buffer;
454
455   ScopedResource loader(filesystem_->ppapi());
456   ScopedResource request(filesystem_->ppapi());
457   ScopedResource response(filesystem_->ppapi());
458   int32_t statuscode;
459   StringMap_t response_headers;
460   Error error = OpenUrl("GET",
461                         &headers,
462                         &loader,
463                         &request,
464                         &response,
465                         &statuscode,
466                         &response_headers);
467   if (error) {
468     if (statuscode == STATUSCODE_REQUESTED_RANGE_NOT_SATISFIABLE) {
469       // We're likely trying to read past the end. Return 0 bytes.
470       *out_bytes = 0;
471       return 0;
472     }
473
474     return error;
475   }
476
477   off_t read_start = 0;
478   if (statuscode == STATUSCODE_OK) {
479     // No partial result, read everything starting from the part we care about.
480     off_t content_length;
481     if (ParseContentLength(response_headers, &content_length)) {
482       if (attr.offs >= content_length)
483         return EINVAL;
484
485       // Clamp count, if trying to read past the end of the file.
486       if (attr.offs + count > content_length) {
487         count = content_length - attr.offs;
488       }
489     }
490   } else if (statuscode == STATUSCODE_PARTIAL_CONTENT) {
491     // Determine from the headers where we are reading.
492     off_t read_end;
493     off_t entity_length;
494     if (ParseContentRange(
495             response_headers, &read_start, &read_end, &entity_length)) {
496       if (read_start > attr.offs || read_start > read_end) {
497         // If this error occurs, the server is returning bogus values.
498         return EINVAL;
499       }
500
501       // Clamp count, if trying to read past the end of the file.
502       count = std::min(read_end - read_start, count);
503     } else {
504       // Partial Content without Content-Range. Assume that the server gave us
505       // exactly what we asked for. This can happen even when the server
506       // returns 200 -- the cache may return 206 in this case, but not modify
507       // the headers.
508       read_start = attr.offs;
509     }
510   }
511
512   if (read_start < attr.offs) {
513     // We aren't yet at the location where we want to start reading. Read into
514     // our dummy buffer until then.
515     int bytes_to_read = attr.offs - read_start;
516     int bytes_read;
517     error = ReadResponseToTemp(loader, bytes_to_read, &bytes_read);
518     if (error)
519       return error;
520
521     // Tried to read past the end of the entity.
522     if (bytes_read < bytes_to_read) {
523       *out_bytes = 0;
524       return 0;
525     }
526   }
527
528   return ReadResponseToBuffer(loader, buf, count, out_bytes);
529 }
530
531 Error HttpFsNode::DownloadToTemp(off_t* out_bytes) {
532   StringMap_t headers;
533   ScopedResource loader(filesystem_->ppapi());
534   ScopedResource request(filesystem_->ppapi());
535   ScopedResource response(filesystem_->ppapi());
536   int32_t statuscode;
537   StringMap_t response_headers;
538   Error error = OpenUrl("GET",
539                         &headers,
540                         &loader,
541                         &request,
542                         &response,
543                         &statuscode,
544                         &response_headers);
545   if (error)
546     return error;
547
548   off_t content_length = 0;
549   if (ParseContentLength(response_headers, &content_length)) {
550     *out_bytes = content_length;
551     return 0;
552   }
553
554   return ReadEntireResponseToTemp(loader, out_bytes);
555 }
556
557 Error HttpFsNode::ReadEntireResponseToTemp(const ScopedResource& loader,
558                                            off_t* out_bytes) {
559   *out_bytes = 0;
560
561   const int kBytesToRead = MAX_READ_BUFFER_SIZE;
562   buffer_ = (char*)realloc(buffer_, kBytesToRead);
563   assert(buffer_);
564   if (!buffer_) {
565     buffer_len_ = 0;
566     return ENOMEM;
567   }
568   buffer_len_ = kBytesToRead;
569
570   while (true) {
571     int bytes_read;
572     Error error =
573         ReadResponseToBuffer(loader, buffer_, kBytesToRead, &bytes_read);
574     if (error)
575       return error;
576
577     *out_bytes += bytes_read;
578
579     if (bytes_read < kBytesToRead)
580       return 0;
581   }
582 }
583
584 Error HttpFsNode::ReadEntireResponseToCache(const ScopedResource& loader,
585                                             int* out_bytes) {
586   *out_bytes = 0;
587   const int kBytesToRead = MAX_READ_BUFFER_SIZE;
588
589   while (true) {
590     // Always recalculate the buf pointer because it may have moved when
591     // cached_data_ was resized.
592     cached_data_.resize(*out_bytes + kBytesToRead);
593     void* buf = cached_data_.data() + *out_bytes;
594
595     int bytes_read;
596     Error error = ReadResponseToBuffer(loader, buf, kBytesToRead, &bytes_read);
597     if (error)
598       return error;
599
600     *out_bytes += bytes_read;
601
602     if (bytes_read < kBytesToRead) {
603       // Shrink the cached data buffer to the correct size.
604       cached_data_.resize(*out_bytes);
605       return 0;
606     }
607   }
608 }
609
610 Error HttpFsNode::ReadResponseToTemp(const ScopedResource& loader,
611                                      int count,
612                                      int* out_bytes) {
613   *out_bytes = 0;
614
615   if (buffer_len_ < count) {
616     int new_len = std::min(count, MAX_READ_BUFFER_SIZE);
617     buffer_ = (char*)realloc(buffer_, new_len);
618     assert(buffer_);
619     if (!buffer_) {
620       buffer_len_ = 0;
621       return ENOMEM;
622     }
623     buffer_len_ = new_len;
624   }
625
626   int bytes_left = count;
627   while (bytes_left > 0) {
628     int bytes_to_read = std::min(bytes_left, buffer_len_);
629     int bytes_read;
630     Error error = ReadResponseToBuffer(
631         loader, buffer_, bytes_to_read, &bytes_read);
632     if (error)
633       return error;
634
635     if (bytes_read == 0)
636       return 0;
637
638     bytes_left -= bytes_read;
639     *out_bytes += bytes_read;
640   }
641
642   return 0;
643 }
644
645 Error HttpFsNode::ReadResponseToBuffer(const ScopedResource& loader,
646                                        void* buf,
647                                        int count,
648                                        int* out_bytes) {
649   *out_bytes = 0;
650
651   PepperInterface* ppapi = filesystem_->ppapi();
652   URLLoaderInterface* loader_interface = ppapi->GetURLLoaderInterface();
653
654   char* out_buffer = static_cast<char*>(buf);
655   int bytes_to_read = count;
656   while (bytes_to_read > 0) {
657     int bytes_read =
658         loader_interface->ReadResponseBody(loader.pp_resource(),
659                                            out_buffer,
660                                            bytes_to_read,
661                                            PP_BlockUntilComplete());
662
663     if (bytes_read == 0) {
664       // This is not an error -- it may just be that we were trying to read
665       // more data than exists.
666       *out_bytes = count - bytes_to_read;
667       return 0;
668     }
669
670     if (bytes_read < 0)
671       return PPErrorToErrno(bytes_read);
672
673     assert(bytes_read <= bytes_to_read);
674     bytes_to_read -= bytes_read;
675     out_buffer += bytes_read;
676   }
677
678   *out_bytes = count;
679   return 0;
680 }
681
682 }  // namespace nacl_io