File: HTTP.pm

package info (click to toggle)
rex 1.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,688 kB
  • ctags: 2,045
  • sloc: perl: 29,512; xml: 264; makefile: 7
file content (108 lines) | stat: -rw-r--r-- 1,820 bytes parent folder | download
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
#
# (c) Jan Gehring <jan.gehring@gmail.com>
#
# vim: set ts=2 sw=2 tw=0:
# vim: set expandtab:

package Rex::Interface::File::HTTP;

use strict;
use warnings;

our $VERSION = '1.4.1'; # VERSION

use Data::Dumper;

BEGIN {
  use Rex::Require;
  MIME::Base64->use;
}

use Rex::Commands;
use Rex::Interface::Fs;
use Rex::Interface::File::Base;
use base qw(Rex::Interface::File::Base);

sub new {
  my $that  = shift;
  my $proto = ref($that) || $that;
  my $self  = $proto->SUPER::new(@_);

  bless( $self, $proto );

  return $self;
}

sub open {
  my ( $self, $mode, $file ) = @_;

  $self->{__file}        = $file;
  $self->{__current_pos} = 0;

  if ( $mode eq ">>" ) {
    my $fs = Rex::Interface::Fs->create;
    eval {
      my %stat = $fs->stat($file);
      $self->{__current_pos} = $stat{size};
    };
  }

  Rex::Logger::debug("Opening $file with mode: $mode");
  my $resp = connection->post( "/file/open", { path => $file, mode => $mode } );
  return $resp->{ok};
}

sub read {
  my ( $self, $len ) = @_;

  my $resp = connection->post(
    "/file/read",
    {
      path  => $self->{__file},
      start => $self->{__current_pos},
      len   => $len,
    }
  );

  if ( $resp->{ok} ) {
    my $buf = decode_base64( $resp->{buf} );
    $self->{__current_pos} += length($buf);
    return $buf;
  }

  return;
}

sub write {
  my ( $self, $buf ) = @_;

  my $resp = connection->post(
    "/file/write_fh",
    {
      path  => $self->{__file},
      start => $self->{__current_pos},
      buf   => encode_base64($buf),
    }
  );

  if ( $resp->{ok} ) {
    $self->{__current_pos} += length($buf);
    return length($buf);
  }

  return;
}

sub seek {
  my ( $self, $pos ) = @_;
  $self->{__current_pos} = $pos;
}

sub close {
  my ($self) = @_;

  delete $self->{__current_pos};
  delete $self->{__file};
}

1;