URL.pm 14.2 KB
Newer Older
1 2
=head1 LICENSE

3
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Thomas Maurel's avatar
Thomas Maurel committed
4
Copyright [2016-2018] EMBL-European Bioinformatics Institute
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

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package EnsEMBL::Web::File::Utils::URL;

### Non-OO library for common functions required for handling remote files 
### Note that we have to use two different Perl modules here, owing to 
### limitations on support for FTP and proxied HTTPS

### File access methods have two modes: "nice" mode is most suitable for
### web interfaces, and returns a hashref containing either the raw content
### or a user-friendly error message (no exceptions are thrown). "Non-nice" 
### or raw mode returns 0/1 for failure/success or the expected raw data, 
### and optionally throws exceptions.

### IMPORTANT: You must pass a reference to the Hub to all methods, so that they
### can access site-wide parameters such as proxies

use strict;
Tiago Grego's avatar
Tiago Grego committed
36
use warnings;
37 38 39 40 41 42 43 44

use HTTP::Tiny;
use LWP::UserAgent;

use EnsEMBL::Web::File::Utils qw(get_compression uncompress);
use Bio::EnsEMBL::Utils::Exception qw(throw);

use Exporter qw(import);
Ridwan Amode's avatar
Ridwan Amode committed
45
our @EXPORT_OK = qw(chase_redirects file_exists read_file write_file delete_file get_filesize fetch_file);
46 47 48 49 50 51 52 53
our %EXPORT_TAGS = (all     => [@EXPORT_OK]);

use constant 'MAX_HIGHLIGHT_FILESIZE' => 1048576;  # (bytes) = 1Mb

sub chase_redirects {
### Deal with files "hidden" behind a URL-shortening service such as tinyurl
### @param File - EnsEMBL::Web::File object or path to file (String)
### @param args Hashref
54 55
###                     hub (optional) EnsEMBL::Web::Hub or
###                     proxy (optional) String
56 57 58 59 60 61
###                     max_follow (optional) Integer - maximum number of redirects to follow
### @return url (String) or Hashref containing errors (ArrayRef)
  my ($file, $args) = @_;
  my $url = ref($file) ? $file->read_location : $file;

  $args->{'max_follow'} = 10 unless defined $args->{'max_follow'};
62
  my $proxy = _proxy($args);
63 64 65 66 67

  if ($url =~ /^ftp/) {
    my $ua = LWP::UserAgent->new( max_redirect => $args->{'max_follow'} );
    $ua->timeout(10);
    $ua->env_proxy;
68
    $ua->proxy([qw(http https ftp)], $proxy) || ();
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
    my $response = $ua->head($url);
    if ($response->is_success) {
      return $response->request->uri->as_string;
    }
    else {
      my $error = _get_lwp_useragent_error($response);
      if ($error =~ /405/) {
        ## Try a GET request, if the server is misconfigured
        $response = $ua->get($url);
        if ($response->is_success) {
          return $response->request->uri->as_string;
        }
        else {
          return {'error' => [_get_lwp_useragent_error($response)]};
        }
      }
      else {
        return {'error' => [$error]};
      }
    }
  }
  else {
    my %args = (
              'timeout'       => 10,
              'max_redirect'  => $args->{'max_follow'},
              );
95 96 97
    if ($proxy) {
      $args{'http_proxy'}   = $proxy;
      $args{'https_proxy'}  = $proxy;
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
    }
    my $http = HTTP::Tiny->new(%args);

    my $response = $http->request('HEAD', $url);
    if ($response->{'success'}) {
      return $response->{'url'};
    }
    else {
      my $error = _get_http_tiny_error($response);
      if ($error =~ /405/) {
        ## Try a GET request, if the server is misconfigured
        $response = $http->request('GET', $url);
        if ($response->{'success'}) {
          return $response->{'url'};
        }
        else {
          return {'error' => [_get_http_tiny_error($response)]};
        }
      }
      else {
        return {'error' => [$error]};
      }
    }
  }
}

sub file_exists {
### Check if a file of this name exists
### @param File - EnsEMBL::Web::File object or path to file (String)
### @param Args Hashref 
128 129
###         hub (optional) EnsEMBL::Web::Hub or
###         proxy (optional) String
130 131 132 133 134
###         nice (optional) Boolean - see introduction
###         no_exception (optional) Boolean
### @return Hashref (nice mode) or Boolean 
  my ($file, $args) = @_;
  my $url = ref($file) ? $file->absolute_read_path : $file;
135
  my $proxy = _proxy($args);
136 137 138 139 140 141 142

  my ($success, $error);

  if ($url =~ /^ftp/) {
    my $ua = LWP::UserAgent->new();
    $ua->timeout(10);
    $ua->env_proxy;
143
    $ua->proxy([qw(http https ftp)], $proxy) || ();
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    my $response = $ua->head($url);
    unless ($response->is_success) {
      $error = _get_lwp_useragent_error($response);
      if ($error =~ /405/) {
        ## Try a GET request, if the server is misconfigured
        $error = undef;
        $response = $ua->get($url);
        unless ($response->is_success) {
          $error = _get_lwp_useragent_error($response);
        }  
      }
    }
  }
  else {
    my %params = ('timeout'       => 10);
159 160 161
    if ($proxy) {
      $params{'http_proxy'}   = $proxy;
      $params{'https_proxy'}  = $proxy;
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
    }
    my $http = HTTP::Tiny->new(%params);

    my $response = $http->request('GET', $url);
    unless ($response->{'success'}) {
      $error = _get_http_tiny_error($response);
      if ($error =~ /405/) {
        ## Try a GET request, if the server is misconfigured
        $error = undef;
        $response = $http->request('GET', $url);
        unless ($response->{'success'}) {
          $error = _get_http_tiny_error($response);
        }  
      }
    }
  }

  if ($args->{'nice'}) {
    return $error ? {'error' => [$error]} : {'success' => 1};
  }
  else {
    if ($error) {
      throw("File $url could not be found: $error") unless $args->{'no_exception'};
      return 0;
    }
    else {
      return 1;
    }
  }
}

sub read_file {
### Get entire content of file
### @param File - EnsEMBL::Web::File object or path to file (String)
### @param Args Hashref 
197 198
###         hub (optional) EnsEMBL::Web::Hub or
###         proxy (optional) String
199 200
###         nice (optional) Boolean - see introduction
###         compression String (optional) - compression type
Anne Lyle's avatar
Anne Lyle committed
201
###         method String (optional) - defaults to 'get'
202
###         size_limit (optional) - max size for the file to be read
203 204 205
### @return Hashref (in nice mode) or String - contents of file
  my ($file, $args) = @_;
  my $url = ref($file) ? $file->absolute_read_path : $file;
206
  my $proxy = _proxy($args);
207 208

  my ($content, $error);
Anne Lyle's avatar
Anne Lyle committed
209
  my $method = $args->{'method'} || 'get';
210

211

212 213 214 215
  if ($url =~ /^ftp/) {
    my $ua = LWP::UserAgent->new();
    $ua->timeout(10);
    $ua->env_proxy;
216
    $ua->proxy([qw(http https ftp)], $proxy) || ();
Anne Lyle's avatar
Anne Lyle committed
217
    my $response = $ua->$method($url, %{$args->{'headers'}});
218 219 220 221 222 223 224 225 226 227
    if ($response->is_success) {
      $content = $response->content;
    }
    else {
      $error = _get_lwp_useragent_error($response);
      warn "!!! ERROR FETCHING FILE $url: $error";
    }
  }
  else {
    my %params = ('timeout'       => 10);
228 229 230
    if ($proxy) {
      $params{'http_proxy'}   = $proxy;
      $params{'https_proxy'}  = $proxy;
231
    }
Anne Lyle's avatar
Anne Lyle committed
232

233 234
    my $http = HTTP::Tiny->new(%params);

Anne Lyle's avatar
Anne Lyle committed
235 236 237 238 239 240 241 242 243 244
    ## HTTP::Tiny separates content from other headers
    my $options = {};
    if ($args->{'headers'} && $args->{'headers'}{'Content'}) {
      $options->{'content'} = $args->{'headers'}{'Content'};
      delete $args->{'headers'}{'Content'};
    }
    if ($args->{'headers'} && keys %{$args->{'headers'}}) {
      $options->{'headers'} = $args->{'headers'};
    }

245 246 247 248 249 250 251 252 253
    # max size limit provided ?
    my $_content = '';
    if ($args->{'size_limit'}) {
      $options->{'data_callback'} = sub {
        $_content .= $_[0];
        die "File size exceeds maximum allowed size\n" if length $_content > $args->{'size_limit'};
      }
    }

Anne Lyle's avatar
Anne Lyle committed
254
    my $response = $http->request(uc($method),$url,$options);
255
    if ($response->{'success'}) {
256
      $content = $args->{'size_limit'} ? $_content : $response->{'content'};
257 258
    }
    else {
Anne Lyle's avatar
Anne Lyle committed
259
      $error = _get_http_tiny_error($response) . " ($url)";
260 261 262 263 264 265 266 267 268 269 270 271 272 273
      warn "!!! ERROR FETCHING FILE $url: $error";
    }
  }

  if ($error) {
    if ($args->{'nice'}) {
      return {'error' => [$error]};
    }
    else {
      throw('URLException', "File $url could not be read: $error") unless $args->{'no_exception'};
      return 0;
    }
  }
  else {
274
    my $compression = $args->{'compression'} || get_compression($url);
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
    if ($compression) {
      uncompress(\$content, $compression);
    }
    if ($args->{'nice'}) {
      return {'content' => $content};
    }
    else {
      return $content;
    }
  }
}

sub write_file {
### Returns an error if caller tries to write to remote server!
### @param File - EnsEMBL::Web::File object or path to file (String)
### @param Args Hashref 
###         nice (optional) Boolean - see introduction
### @return Zero (nice mode) or Hashref containing error
  my ($file, $args) = @_;
  my $url = ref($file) ? $file->write_url : $file;
  warn "!!! Oops - tried to write to a remote server!";
  if ($args->{'nice'}) {
    return {'error' => ["Cannot write to remote file $url. Function not supported"]};
  }
  else {
    throw("Writing to remote files not permitted!") unless $args->{'no_exception'};
    return 0;
  }
}

sub delete_file {
### Returns an error if caller tries to delete file from remote server!
### @param File - EnsEMBL::Web::File object or path to file (String)
### @param Args Hashref 
###         nice (optional) Boolean - see introduction
### @return Zero (nice mode) or Hashref containing error (ArrayRef)
  my ($file, $args) = @_;
  my $url = ref($file) ? $file->write_url : $file;
  warn "!!! Oops - tried to delete file from a remote server!";
  if ($args->{'nice'}) {
    return {'error' => ["Cannot delete remote file $url. Function not supported"]};
  }
  else {
    throw("Deleting remote files not permitted!") unless $args->{'no_exception'};
    return 0;
  }
}

Ridwan Amode's avatar
Ridwan Amode committed
323 324 325 326 327 328
sub fetch_file {
### Download file (URL based) to local file system
### @param file_url - File URL
### @param Args (optional) Hashref
###                     nice Boolean - see introduction
###                     destination_path - path where to store file (if not specified will store it in /tmp/)
Ridwan Amode's avatar
Ridwan Amode committed
329
### @return location of downloaded file or Hashref containing error
Ridwan Amode's avatar
Ridwan Amode committed
330 331 332 333 334 335 336 337 338 339
### CAUTION: Fetching large file will cause the page to hang as it waits for the whole file to finish download and then proceed
  my ($file_url, $args) = @_;

  $file_url     =~ m!([^/]+)$!;
  my $filename  = $1;
  my $proxy     = _proxy($args);
  my $ua        = LWP::UserAgent->new();

  $ua->timeout(10);
  $ua->env_proxy;
340
  $ua->proxy([qw(http https ftp)], $proxy) || ();
Ridwan Amode's avatar
Ridwan Amode committed
341

Ridwan Amode's avatar
Ridwan Amode committed
342 343 344
  my $dest     = $args->{'destination_path'} ? $args->{'destination_path'}."$filename" : "/tmp/$filename";
  my $response = $ua->mirror($file_url, $dest);
  return $dest if ($response->{_msg} eq 'OK');
Ridwan Amode's avatar
Ridwan Amode committed
345 346 347 348 349 350 351 352 353

  if($args->{'nice'}) {
     return {'error' => "Cannot download file ($file_url). HTTP request error code ".$response->{_rc}};
  } else {
    throw("Cannot download file ($file_url). HTTP request error code ".$response->{_rc}) unless $args->{'no_exception'};
    return 0;
  }
}

354 355 356 357 358
sub get_headers {
### Get one or all headers from a remote file 
### @param url - URL of file
### @param Args Hashref 
###         header (optional) String - name of header
359 360
###         hub (optional) EnsEMBL::Web::Hub or
###         proxy (optional) String
361 362 363 364 365 366
###         nice (optional) Boolean - see introduction
###         compression String (optional) - compression type
### @return Hashref containing results (single header or hashref of headers) or errors (ArrayRef)
  my ($file, $args) = @_;
  my $url = ref($file) ? $file->absolute_read_path : $file;
  my ($all_headers, $result, $error);
367
  my $proxy = _proxy($args);
368 369 370 371 372 373 374

  if ($url =~ /^ftp/) {
    ## TODO - support FTP properly!
    return {'Content-Type' => 1};
  }
  else {
    my %params = ('timeout'       => 10);
375 376 377
    if ($proxy) {
      $params{'http_proxy'}   = $proxy;
      $params{'https_proxy'}  = $proxy;
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
    }
    my $http = HTTP::Tiny->new(%params);

    my $response = $http->request('HEAD', $url);
    if ($response->{'success'}) {
      $all_headers = $response->{'headers'};
    }
    else {
      $error = _get_http_tiny_error($response);
    }
  }

  $result = $args->{'header'} ? $all_headers->{$args->{'header'}} : $all_headers;

  if ($args->{'nice'}) {
    if ($error) {
      if ($error =~ /405/) {
        ## Some servers don't accept header requests, which is annoying but not fatal
        $error = 'denied';
      }
      return {'error' => [$error]};
    }
    else {
      return {'headers' => $result};
    }
  }
  else {
    if ($error) {
      throw("Could not get headers.") unless $args->{'no_exception'};
      return 0;
    }
    else {
      return $result;
    }
  }
}

sub get_filesize {
### Get size of remote file 
### @param url - URL of file
### @param Args Hashref 
419 420
###         hub (optional) EnsEMBL::Web::Hub or
###         proxy (optional) String
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
###         nice (optional) Boolean - see introduction
###         compression String (optional) - compression type
### @return Hashref containing results (Integer - file size in bytes) or errors (ArrayRef)
  my ($file, $args) = @_;
  $args->{'header'} = 'Content-Length';
  return get_headers($file, $args);
}

sub _get_lwp_useragent_error {
### Convert error responses from LWP::UserAgent into a user-friendly string
### @param response - HTTP::Response object
### @return String
  my $response = shift;

  return 'timeout'              unless $response->code;
  return $response->status_line if     $response->code >= 400;
  return;
}

sub _get_http_tiny_error {
### Convert error responses from HTTP::Tiny into a user-friendly string
### @param response HashRef 
### @return String
  my $response = shift;

  return 'timeout' unless $response->{'status'};
447 448 449 450
  if($response->{'status'} == 599) {
    # HTTP::Tiny errors are reported via code 599.
    return "Internal: $response->{'content'}";
  } elsif($response->{'status'} >= 400) {
451 452 453 454 455
    return $response->{'status'}.': '.$response->{'reason'};
  }
  return;
}

456 457 458 459 460
sub _proxy {
  my $args = shift;

  my $proxy = $args->{'proxy'};
  if (!$proxy && $args->{'hub'}) {
461
    $proxy = $args->{'hub'}->web_proxy;
462 463 464
  }
  return $proxy;
}
465 466 467

1;