-
Notifications
You must be signed in to change notification settings - Fork 16
/
rifec.pl
executable file
·1719 lines (1400 loc) · 51 KB
/
rifec.pl
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
#! /usr/bin/perl
#
# RIFEC.pl: Receive Images From Eye-Fi Cards
# Copyright (C) 2011 Kristoffer Gleditsch, https://github.com/kristofg
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
# There are two global objects, ::Config and ::Log, each accessed
# through a global variable. At the bottom of the script, there is a
# plain sub implementing the listen/fork loop on the socket. For each
# incoming connection, it instantiates a ::Handler object. All
# incoming requests on the same connection is sent there. The
# ::Session and ::File objects are helper objects used internally by
# the ::Handler.
require 5.014;
use strict;
use warnings;
use filetest 'access';
my $log;
my $config;
# Config parsing and handling (accessed through the $config object)
package RIFEC::Config {
use Carp qw(confess);
use Config::IniFiles;
use Cwd qw();
use Data::Dumper;
use Params::Validate;
use POSIX qw();
our $card_section_re = qr/\A card \s+ (.*?)\z/xi;
our $filetype_section_re = qr/\A filetype \s+ (.*?)\z/xi;
our $from_section_re = qr/\A from \s+ (.*?) \s+ filetype \s+ (.*?)\z/xi;
sub new {
validate_pos(@_, 1, 0);
my ($class, $file) = @_;
my $self = {};
bless($self, $class);
$self->{'_file'} = $file if @_ > 1;
$self->{'_cfg'} = $self->_build_config();
$self->{'_counter'} = 0;
return $self;
}
sub _file {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'_file'};
}
sub _cfg {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'_cfg'};
}
sub counter {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'_counter'};
}
sub bump_counter {
validate_pos(@_, 1);
my ($self) = @_;
return ++$self->{'_counter'};
}
sub normalize_mac {
validate_pos(@_, 1, 1);
my ($self, $in) = @_;
my $ret = lc $in;
$ret =~ s/[-: ]//gx;
confess "'$in' doesn't look like a MAC address"
unless $ret =~ m|\A [a-z0-9]{12} \z|xi;
return $ret;
}
sub _read_inifile {
validate_pos(@_, 1);
my ($self) = @_;
# Fall back to default if undef or empty:
$self->{'file'} = "rifec.config" unless $self->_file;
# Absolute-ize, so that error messages output a full path:
$self->{'file'} = Cwd::abs_path($self->_file);
confess sprintf("Config file '%s' does not exist", $self->_file)
unless -e $self->_file;
confess sprintf("Config file '%s' is not readable", $self->_file)
unless -r $self->_file;
confess sprintf("Config file '%s' is empty", $self->_file)
unless -s $self->_file;
my %cfg;
tie(%cfg, 'Config::IniFiles', (-file => $self->_file,
-nocase => 1,
-allowempty => 0));
confess "Unable to read config file: ", Dumper(@Config::IniFiles::errors)
unless %cfg;
return \%cfg;
}
sub _validate_inifile {
validate_pos(@_, 1, { type => Params::Validate::HASHREF });
my ($self, $ini) = @_;
my %paramspec_of = (
$card_section_re => {
'macaddress' => 1,
'uploadkey' => 1,
'folder' => 0,
'subfolder' => 0,
},
$from_section_re => {
'folder' => 0,
'subfolder' => 0,
},
$filetype_section_re => {
'folder' => 0,
'subfolder' => 0,
},
qr/\A main \z/xi => {
'logfile' => 1,
'loglevel' => 1,
'port' => 1,
'sockettimeout' => 1,
'subfoldertimesource' => 0,
'tarcommand' => 0,
'folder' => 0,
'subfolder' => 0,
},
);
foreach my $key (keys %$ini) {
# Find the paramspec for this type of section:
my @match = grep { $key =~ $_ } keys %paramspec_of;
# Every section should match one and only one paramspec:
if (scalar(@match) != 1) {
confess sprintf("Unrecognized or malformed config section name '%s'",
$key);
}
my @inifields = %{$ini->{$key}};
validate(@inifields, $paramspec_of{$match[0]});
}
}
sub _build_config {
validate_pos(@_, 1);
my ($self) = @_;
my $filecfg = $self->_read_inifile();
$self->_validate_inifile($filecfg);
my $c = {};
# Main section:
foreach my $s (keys %{ $filecfg->{'main'} }) {
$c->{'main'}->{$s} = $filecfg->{'main'}->{$s};
}
# top-level filetype sections:
foreach my $ft_section (grep { $_ =~ $filetype_section_re } keys %$filecfg) {
$ft_section =~ $filetype_section_re
|| confess "Unexpected regexp mismatch";
my $type = $1;
foreach my $f (keys %{ $filecfg->{$ft_section} }) {
$c->{'filetypes'}->{$type}->{$f} = $filecfg->{$ft_section}->{$f};
}
}
# card sections:
foreach my $card_section (grep { $_ =~ $card_section_re } keys %$filecfg) {
$card_section =~ $card_section_re
|| confess "Unexpected regexp mismatch";
my $cardname = $1;
foreach my $s (keys %{ $filecfg->{$card_section}}) {
my $value = $filecfg->{$card_section}->{$s};
if ($s eq 'macaddress') {
$value = $self->normalize_mac($value);
}
$c->{'cards'}->{$cardname}->{$s} = $value;
}
# We are messing around with card names here, but the
# actual config lookups will be by MAC:
my $mac = $c->{'cards'}->{$cardname}->{'macaddress'};
$c->{'macs'}->{$mac} = $c->{'cards'}->{$cardname};
# Add the name to the hash, so the people who've only got
# the MAC can get at it:
$c->{'cards'}->{$cardname}->{'name'} = $cardname;
}
# from X filetype Y sections:
foreach my $from_section (grep { $_ =~ $from_section_re } keys %$filecfg) {
$from_section =~ $from_section_re
|| confess "Unexptected regexp mismatch";
my $card = $1;
my $type = $2;
confess sprintf("section '%s' doesn't match any card names!",
$from_section)
unless exists $c->{'cards'}->{$card};
foreach my $s (keys %{ $filecfg->{$from_section} }) {
$c->{'cards'}->{$card}->{'filetypes'}->{$type}->{$s} =
$filecfg->{$from_section}->{$s};
}
}
#print STDERR "Config hash dump: ", Dumper($c), "\n";
return $c;
}
sub say_hello {
validate_pos(@_, 1);
my ($self) = @_;
$log->info("Config file '%s', %d card(s) configured:",
Cwd::abs_path($self->_file),
scalar keys %{ $self->_cfg->{'cards'} });
foreach my $card (keys %{ $self->_cfg->{'cards'} }) {
$log->info(" Card '%s' (%s)",
$card,
$self->_cfg->{'cards'}->{$card}->{'macaddress'});
}
}
sub doiknow {
validate_pos(@_, 1, 1);
my ($self, $mac) = @_;
$mac = $self->normalize_mac($mac);
confess sprintf("Sorry, I don't know the card with MAC '%s'", $mac)
unless exists $self->_cfg->{'macs'}->{$mac};
return 1;
}
sub check_writeable_dir {
validate_pos(@_, 1, 1);
my ($self, $dir) = @_;
confess sprintf("Destination directory '%s' not found", $dir)
unless -e $dir;
confess sprintf("Destination directory '%s' not a directory", $dir)
unless -d $dir;
confess sprintf("Destination directory '%s' not writeable", $dir)
unless -w $dir;
}
# Actual config accessors.
sub logfile {
validate_pos(@_, 1);
my ($self) = @_;
return $self->_cfg->{'main'}->{'logfile'};
}
sub loglevel {
validate_pos(@_, 1);
my ($self) = @_;
return $self->_cfg->{'main'}->{'loglevel'};
}
sub port {
validate_pos(@_, 1);
my ($self) = @_;
return $self->_cfg->{'main'}->{'port'} || 59278;
}
sub sockettimeout {
validate_pos(@_, 1);
my ($self) = @_;
return $self->_cfg->{'main'}->{'sockettimeout'} || 600;
}
sub tarcommand {
validate_pos(@_, 1);
my ($self) = @_;
my $tc = $self->_cfg->{'main'}->{'tarcommand'} || "/bin/tar";
# Verify that the tar command looks sane:
my $help = "Please tell me where tar is by adding 'TarCommand=/path/to/tar' to the main section of your config file";
confess "'$tc' not found: $help"
unless -e $tc;
confess "'$tc' is not executable: $help"
unless -x $tc;
return $tc;
}
sub subfoldertimesource {
validate_pos(@_, 1);
my ($self) = @_;
return $self->_cfg->{'main'}->{'subfoldertimesource'} || "local";
}
# Per-card settings:
sub _mac_setting {
validate_pos(@_, 1, 1, 1);
my ($self, $mac, $setting) = @_;
$self->doiknow($mac);
$mac = $self->normalize_mac($mac);
confess sprintf("Error looking up setting '%s' for card '%s'",
$setting, $mac)
unless exists $self->_cfg->{'macs'}->{$mac}->{$setting};
return $self->_cfg->{'macs'}->{$mac}->{$setting};
}
sub cardname {
validate_pos(@_, 1, 1);
my ($self, $mac) = @_;
return $self->_mac_setting($mac, 'name');
}
sub uploadkey {
validate_pos(@_, 1, 1);
my ($self, $mac) = @_;
return $self->_mac_setting($mac, 'uploadkey');
}
sub _foldersetting {
validate_pos(@_, 1, 1, 1, 1);
my ($self, $setting, $mac, $filename) = @_;
$self->doiknow($mac);
$mac = $self->normalize_mac($mac);
my $cfg = $self->_cfg;
if (defined($filename) && $filename) {
$filename =~ / \. ([^ \.]*?) \z/xi
|| confess "Unable to extract file type from name '$filename'";
my $type = lc $1;
if (exists $cfg->{'macs'}->{$mac}->{'filetypes'}->{$type} &&
exists $cfg->{'macs'}->{$mac}->{'filetypes'}->{$type}->{$setting})
{
return $cfg->{'macs'}->{$mac}->{'filetypes'}->{$type}->{$setting};
}
if (exists $cfg->{'filetypes'}->{$type} &&
exists $cfg->{'filetypes'}->{$type}->{$setting})
{
return $cfg->{'filetypes'}->{$type}->{$setting};
}
}
if (exists $cfg->{'macs'}->{$mac}->{$setting}) {
return $cfg->{'macs'}->{$mac}->{$setting};
}
if (exists $cfg->{'main'}->{$setting}) {
return $cfg->{'main'}->{$setting}
}
return;
}
sub folder {
validate_pos(@_, 1, 1, 0);
my ($self, $mac, $filename) = @_;
my $f = $self->_foldersetting('folder', $mac, $filename || '');
confess sprintf("Error looking up folder for card '%s' file '%s'",
$self->_cfg->{'macs'}->{$mac}->{'name'},
$filename || '')
unless defined($f) && $f;
$self->check_writeable_dir($f);
return $f;
}
sub subfolder {
validate_pos(@_, 1, 1, 0);
my ($self, $mac, $filename) = @_;
return $self->_foldersetting('subfolder', $mac, $filename || '');
}
1;
}
# Logging, accessed through the $log object:
package RIFEC::Log {
use Carp qw(confess);
use Data::Dumper;
use HTTP::Date qw();
use IO::File;
use Params::Validate;
sub new {
validate_pos(@_, 1, 0);
my ($class, $file) = @_;
my $self = {};
bless($self, $class);
$self->{'_fh'} = \*STDOUT;
$self->open();
return $self;
}
sub _fh {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'_fh'};
}
sub DESTROY {
my ($self) = @_;
if (defined $self->_fh) {
$self->_fh->close()
or confess "Unable to close log filehandle while exiting: $!";
}
}
sub loglevel {
return {
'off' => 100,
'warning' => 4,
'info' => 3,
'debug' => 2,
'trace' => 1,
};
};
sub open {
validate_pos(@_, 1);
my ($self) = @_;
if (my $lf = $config->logfile()) {
$self->_fh->close()
or confess "Unable to close logfile while exiting: $!";
my $fh = IO::File->new($lf, O_WRONLY|O_APPEND|O_CREAT)
or confess "Unable to open logfile '$lf' for writing: $!";
$self->{'_fh'} = $fh;
}
}
sub _get_preamble {
validate_pos(@_, 1, 1);
my ($self, $ll) = @_;
return sprintf("%s %7u %7s ",
HTTP::Date::time2isoz(),
$$,
uc $ll);
}
sub _print_if {
validate_pos(@_, 1, 1, (0) x (@_ - 2));
my ($self, $loglevel, @str) = @_;
# Sanity check.
foreach my $ll ($loglevel, $config->loglevel) {
confess sprintf("Invalid loglevel '%s'", $ll)
unless $self->loglevel->{lc $ll};
}
if ($self->loglevel->{lc $loglevel} >= $self->loglevel->{lc $config->loglevel})
{
my $out = $self->_get_preamble($loglevel);
# figure out if it's a (s)printf or not:
if (scalar(@str) == 1) {
$out .= $str[0];
}
elsif (scalar(@str) > 1) {
$out .= sprintf shift(@str), @str;
}
else {
confess "If you log, please send content too.";
}
# \n-terminate if needed
$out .= ($out =~ / \n \z/x) ? "" : "\n";
print { $self->_fh } $out;
$self->_fh->flush();
}
}
sub trace {
my ($self, @str) = @_;
$self->_print_if('trace', @str);
}
sub debug {
my ($self, @str) = @_;
$self->_print_if('debug', @str);
}
sub info {
my ($self, @str) = @_;
$self->_print_if('info', @str);
}
sub warning {
my ($self, @str) = @_;
$self->_print_if('warning', @str);
}
1;
}
package RIFEC::Session {
use Carp qw(confess);
use Data::Dumper;
use Digest::MD5 qw(md5_hex);
use IO::File;
use Params::Validate;
sub new {
my $class = shift;
my %p = validate(@_, { 'card' => 1,
'transfermode' => 1,
'transfermodetimestamp' => 1,
'card_nonce' => 1, });
my $self = {};
bless($self, $class);
foreach my $key (keys %p) {
$self->{$key} = $p{$key};
}
$self->{'server_nonce'} = $self->_generate_s_nonce();
$self->{'is_authenticated'} = undef;
$self->_check_params();
return $self;
}
sub card {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'card'};
}
sub transfermode {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'transfermode'};
}
sub transfermodetimestamp {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'transfermodetimestamp'};
}
sub card_nonce {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'card_nonce'};
}
sub server_nonce {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'server_nonce'};
}
sub authenticated {
validate_pos(@_, 1, 0);
my ($self, $set) = @_;
$self->{'is_authenticated'} = $set if @_ > 1;
return $self->{'is_authenticated'};
}
# We used to use the Crypt::Random library for this, but it is not
# available through the package manager of all Linux
# distributions, and was just a wrapper around reading the data
# from /dev/urandom anyway.
sub getrandom {
validate_pos(@_, 1, 1);
my ($self, $bytes) = @_;
my $random_file = "/dev/urandom";
my $output;
my $has_read = 0;
my $fh = IO::File->new($random_file, O_RDONLY)
or confess "Unable to open '$random_file' for reading random data: $!";
while ($has_read < $bytes) {
my $o;
my $read_status = $fh->read($o, $bytes - $has_read);
if (!defined $read_status) {
confess "Error while reading random data from '$random_file': $!";
}
elsif ($read_status == 0) {
confess "Reached EOF while reading random data from '$random_file'";
}
$output .= $o;
$has_read += $read_status;
}
$fh->close()
or confess "Unable to close '$random_file': $!";
return $output;
}
sub _generate_s_nonce {
my ($self) = @_;
my $octets = $self->getrandom(16);
return unpack("H*", $octets);
}
sub _check_params {
my ($self) = @_;
# Only accept cards that have a config section
$config->doiknow($self->card);
# Only accept transfer modes that we recognize. My card sends
# 546 (0x222), and from basic testing twiddling switches in
# the config GUI, it looks like this number is a bitmask:
#
# 0 1 0 0 0 1 0 0 0 1 0 = 546
# 1 = 2 : Transfer photos to computer
# 1 = 32 : Transfer videos to computer
# 1 = 512 : Transfer RAW files to computer
#
# I'll go with that theory for now: Either way this approach
# means all the modes I have seen will work, and the ones I
# haven't won't.
my $known_txmodes = 1<<1 | 1<<5 | 1<<9;
if ($self->transfermode & ~$known_txmodes) {
confess sprintf("Unsupported transfermode '%s' from card '%s' (%s)," .
" See TROUBLESHOOTING.txt for info about what this means",
$self->transfermode,
$config->cardname($self->card),
$self->card);
}
}
sub server_credential {
my ($self) = @_;
return md5_hex(pack("H*", $self->card),
pack("H*", $self->card_nonce),
pack("H*", $config->uploadkey($self->card)));
}
sub card_credential {
my ($self) = @_;
return md5_hex(pack("H*", $self->card),
pack("H*", $config->uploadkey($self->card)),
pack("H*", $self->server_nonce));
}
}
package RIFEC::File {
use Carp qw(confess);
use Data::Dumper;
use Digest::MD5 qw();
use File::Spec;
use File::Temp qw();
use IO::File;
use Params::Validate;
use POSIX qw();
# If your camera produces files containing other characters than I
# have thought of here, you may have to change this regexp. (All
# places checking the file name should use this, so it should be
# sufficient to update this one place).
our $filename_regexp = qr|\A [ a-z0-9._-]* \z|xi;
sub new {
my $class = shift;
my %p = validate(@_, { 'session' => { isa => 'RIFEC::Session' },
'tarfilename' => 1,
'size' => 1,
'encryption' => 0,
'filesignature' => 1, });
my $self = {};
bless($self, $class);
foreach my $key (keys %p) {
$self->{$key} = $p{$key};
}
return $self;
}
# RO parameters:
sub session {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'session'};
}
sub tarfilename {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'tarfilename'};
}
sub size {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'size'};
}
sub encryption {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'encryption'};
}
sub filesignature {
validate_pos(@_, 1);
my ($self) = @_;
return $self->{'filesignature'};
}
# RW parameters:
sub integritydigest {
validate_pos(@_, 1, 0);
my ($self, $set) = @_;
$self->{'integritydigest'} = $set if @_ > 1;
return $self->{'integritydigest'};
}
sub calculated_digest {
validate_pos(@_, 1, 0);
my ($self, $set) = @_;
$self->{'calculated_digest'} = $set if @_ > 1;
return $self->{'calculated_digest'};
}
sub tarfile {
validate_pos(@_, 1, 0);
my ($self, $set) = @_;
$self->{'tarfile'} = $set if @_ > 1;
return $self->{'tarfile'};
}
sub stored_file {
validate_pos(@_, 1, 0);
my ($self, $set) = @_;
$self->{'stored_file'} = $set if @_ > 1;
return $self->{'stored_file'};
}
# See http://forums.eye.fi/viewtopic.php?f=4&t=270#p3874
sub _calculate_tcp_checksum {
my ($self, $block) = @_;
my $val = 0;
map { $val += $_ } unpack "S*", $block;
while (my $rest = $val >> 16) {
$val = ($val & 0xFFFF) + $rest;
}
return pack("S", ~$val);
}
# Calculating this while receiving the file, ie. in
# Handler::read_socket, would be much faster. However, by doing
# it afterwards we get a sanity check that read_part/read_socket
# didn't mess up our data in transit. Belt and braces.
sub _calculate_integritydigest {
my ($self) = @_;
my $file = $self->tarfile;
$log->debug("Calculating integrity digest of '%s'", $file);
my $blocksize = 512;
# Make sure it is 512-block aligned (it should be)
my $length = (stat($file))[7];
confess "Tar file not 512-byte aligned!"
if $length % $blocksize;
my $md5 = Digest::MD5->new();
my $fh = IO::File->new($file, O_RDONLY)
or confess "Unable to open '$file': $!";
my $i = 0;
while ($i < $length) {
my $block;
my $read_status = $fh->read($block, $blocksize);
confess "Error while reading from '$file': $!"
unless defined $read_status;
confess "Reached EOF while reading from '$file'"
if $read_status == 0;
confess "Unexpected read length [$read_status] from '$file'"
unless $read_status == $blocksize;
$md5->add( $self->_calculate_tcp_checksum($block) );
$i += $blocksize;
}
$fh->close()
or confess "Unable to close '$file': $!";
$md5->add(pack("H*", $config->uploadkey($self->session->card)));
my $md5sum = $md5->hexdigest();
$log->debug("...done: %s", uc $md5sum);
$self->calculated_digest(uc $md5sum);
return uc $md5sum;
}
sub receiver_filehandle {
validate_pos(@_, 1, 1);
my ($self, $inner_filename) = @_;
my $folder = $config->folder($self->session->card);
$config->check_writeable_dir($folder);
my $tfh = File::Temp->new(
TEMPLATE => sprintf(".rifec-receiving-%d--%s--XXXXXXXX",
$$,
$inner_filename),
DIR => $folder,
UNLINK => 0);
my $tfn = $tfh->filename;
$self->tarfile($tfn); # Remember where we put it
$log->debug("Receiver file: '%s' ('%s')", $tfn, $self->tarfilename);
return $tfh;
}
sub check {
validate_pos(@_, 1);
my ($self) = @_;
# First that the size matches what the card said:
my $stat_size = (stat($self->tarfile))[7];
if ($stat_size == $self->size)
{
$log->debug("File '%s' is %d bytes long, as expected",
$self->tarfile,
$self->size);
}
else {
$log->warning("File '%s' is %d bytes long, should have been %d",
$self->tarfile,
$stat_size,
$self->size);
return;
}
# Then check the integrity digest field:
$self->_calculate_integritydigest();
if (uc($self->calculated_digest()) eq uc($self->integritydigest()))
{
$log->debug("Integritydigest OK: [%s]", uc $self->integritydigest());
}
else {
$log->warning("Integritydigests does not match!");
$log->warning(" Calculated: [%s]\n Received: [%s]",
uc $self->calculated_digest(),
uc $self->integritydigest());
return;
}
return 1;
}
sub _subfolder {
validate_pos(@_, 1, 1, 1);
my ($self, $tmpimage, $imagefilename) = @_;
my $card = $self->session->card;
my $topfolder = $config->folder($card, $imagefilename);
my $subfolder;
my $subtemplate = $config->subfolder($card, $imagefilename);
# We can create sub folders, but the top folders should be there:
$config->check_writeable_dir($topfolder);
if (!$subtemplate || $subtemplate =~ /\A \s* \z/mxi) {
$log->debug("Card '%s' file '%s': Root folder '%s', empty/blank subfolder",
$config->cardname($card),
$imagefilename,
$topfolder);
return $topfolder;
}
if ($config->subfoldertimesource() ne 'local') {
confess "Sorry, other time sources than 'local' is not implemented yet";
}
$subfolder = POSIX::strftime($subtemplate, localtime());
my $destination = File::Spec->catfile($topfolder, $subfolder);
$log->debug("Destination subdirectory: '%s' -> '%s', full path: '%s'",
$subtemplate,
$subfolder,
$destination);
# Next, create it. Note that the subfolder may be
# $topfolder/X/Y/Z, not just $topfolder/X, so mkdir one level
# at a time:
my @path_elements = File::Spec->splitdir($subfolder);
my $makedir = $topfolder;
foreach my $pe (@path_elements) {
$makedir = File::Spec->catfile($makedir, $pe);
if (! -e $makedir) {
$log->trace("mkdir '$makedir'");
mkdir $makedir
or confess "Unable to mkdir '$makedir': $!";
}
}
# Final sanity check:
$config->check_writeable_dir($destination);
return $destination;
}
# We never want to overwrite existing files, but we don't want the
# card to be stuck with files because we're not able to write them
# to disk either. So we receive it, but add .1 (or .2, or .n+1)
# to the filename. The user will have to sort out duplicates
# afterwards.
#
# (We *assume* that if the link() fails, it is because the
# filename already exists.)
sub _link_file {
validate_pos(@_, 1, 1, 1);
my ($self, $tempfile, $destination_name) = @_;
my $tries = 0;
my $max = 100;
my $dst = $destination_name;
my $done = undef;
while (!$done && $tries < $max) {
if (link $tempfile, $dst) {
$done = $dst;
$log->debug("'%s' created OK (linked from '%s')", $dst, $tempfile);
}
else {
my $prev_dst = $dst;
$dst = sprintf("%s.%d", $destination_name, ++$tries);
$log->warning("'%s' already exists, trying '%s'", $prev_dst, $dst);
}
}
confess sprintf("Unable to write '%s': Destination files already there!",
$dst)
unless $done;
return $dst;
}
sub _extract_tarfile {
validate_pos(@_, 1);
my ($self) = @_;
my $tar_cmd = $config->tarcommand;
my $tar_file = $self->tarfile;
my @files = `$tar_cmd -tf $tar_file`;
# Remove leading and trailing whitespace from each element: