877672b11477a482e4453efcdd31c8d8e6ad1c78
[feisty_meow.git] / octopi / library / tentacles / file_transfer_tentacle.cpp
1 /*****************************************************************************\
2 *                                                                             *
3 *  Name   : file_transfer_tentacle                                            *
4 *  Author : Chris Koeritz                                                     *
5 *                                                                             *
6 *******************************************************************************
7 * Copyright (c) 2005-$now By Author.  This program is free software; you can  *
8 * redistribute it and/or modify it under the terms of the GNU General Public  *
9 * License as published by the Free Software Foundation; either version 2 of   *
10 * the License or (at your option) any later version.  This is online at:      *
11 *     http://www.fsf.org/copyleft/gpl.html                                    *
12 * Please send any updates to: fred@gruntose.com                               *
13 \*****************************************************************************/
14
15 #include "file_transfer_tentacle.h"
16
17 #include <basis/mutex.h>
18 #include <filesystem/directory_tree.h>
19 #include <filesystem/filename.h>
20 #include <filesystem/filename_list.h>
21 #include <filesystem/heavy_file_ops.h>
22 #include <loggers/program_wide_logger.h>
23 #include <octopus/entity_defs.h>
24 #include <octopus/unhandled_request.h>
25 #include <processes/ethread.h>
26 #include <textual/parser_bits.h>
27
28 using namespace basis;
29 using namespace filesystem;
30 using namespace loggers;
31 using namespace octopi;
32 using namespace processes;
33 using namespace structures;
34 using namespace textual;
35 using namespace timely;
36
37 namespace octopi {
38
39 #undef AUTO_LOCK
40 #define AUTO_LOCK auto_synchronizer loc(*_lock);
41   // protects our lists.
42
43 const int FTT_CLEANING_INTERVAL = 30 * SECOND_ms;
44   // this is how frequently we clean up the list to remove outdated transfers.
45
46 const int TRANSFER_TIMEOUT = 10 * MINUTE_ms;
47   // if it hasn't been touched in this long, it's out of there.
48
49 #define DEBUG_FILE_TRANSFER_TENTACLE
50   // uncomment for noisier version.
51
52 #undef LOG
53 #define LOG(s) CLASS_EMERGENCY_LOG(program_wide_logger::get(), s)
54
55 //////////////
56
57 class file_transfer_record 
58 {
59 public:
60   // valid for both transfers and correspondences.
61   astring _src_root;  // where the info is on the data provider.
62   time_stamp _last_active;  // when this was last used.
63
64   // valid for file transfers only.
65   octopus_entity _ent;  // the entity requesting this service.
66   astring _dest_root;  // where the info is on the data sink.
67   filename_list *_diffs;  // the differences to be transferred.
68   file_transfer_header _last_sent;  // the last chunk that was sent.
69   bool _done;  // true if the transfer is finished.
70   string_array _includes;  // the set to include.
71
72   // valid for correspondence records only.
73   directory_tree *_local_dir;  // our local information about the transfer.
74   astring _source_mapping;  // valid for a correspondence record.
75   int _refresh_interval;  // the rate of refreshing the source tree.
76
77   file_transfer_record() : _diffs(NIL), _last_sent(file_time()),
78       _done(false), _local_dir(NIL)
79   {}
80
81   ~file_transfer_record() {
82     WHACK(_local_dir);
83     WHACK(_diffs);
84   }
85
86   astring text_form() const {
87     astring to_return;
88     to_return += astring("src=") + _src_root + astring(" last act=")
89         + _last_active.text_form();
90     if (_ent.blank()) to_return += astring(" ent=") + _ent.text_form();
91     if (_dest_root.t()) {
92       to_return += astring(" dest=") + _dest_root;
93       to_return += astring(" last_sent=") + _last_sent.text_form();
94     }
95     return to_return;
96   }
97 };
98
99 //////////////
100
101 // this implementation assumes that the same entity will never simultaneously
102 // transfer the same source to the same destination.  that assumption holds
103 // up fine for different clients, since they should have different entities.
104 // when there is a collision on the entity/src/dest, then the default action
105 // is to assume that the transfer is just being started over.
106
107 class file_transfer_status : public amorph<file_transfer_record>
108 {
109 public:
110   // find a transfer record by the key fields.
111   file_transfer_record *find(const octopus_entity &ent, const astring &src,
112       const astring &dest) {
113     for (int i = 0; i < elements(); i++) {
114       const file_transfer_record *rec = get(i);
115       if (rec && (rec->_ent == ent) && (rec->_src_root == src)
116           && (rec->_dest_root == dest) ) {
117         return borrow(i);
118       }
119     }
120     return NIL;
121   }
122
123   virtual ~file_transfer_status() {}
124
125   DEFINE_CLASS_NAME("file_transfer_status");
126
127   // find a file correspondence record by the mapping name.
128   file_transfer_record *find_mapping(const astring &source_mapping) {
129     for (int i = 0; i < elements(); i++) {
130       const file_transfer_record *rec = get(i);
131       if (rec && (rec->_source_mapping == source_mapping) )
132         return borrow(i);
133     }
134     return NIL;
135   }
136
137   // turns a source mapping into the location that it corresponds to.
138   astring translate(const astring &source_path) const {
139     FUNCDEF("translate");
140     string_array pieces;
141     filename(source_path).separate(pieces);
142     astring source_mapping = pieces[0];
143     pieces.zap(0, 0);  // remove source part.
144
145     for (int i = 0; i < elements(); i++) {
146       const file_transfer_record *rec = get(i);
147       if (rec && (rec->_source_mapping == source_mapping) ) {
148         return rec->_src_root;
149       }
150     }
151     return astring::empty_string();
152   }
153
154   // removes a file transfer record by the key fields.
155   bool whack(const octopus_entity &ent, const astring &src,
156       const astring &dest) {
157     for (int i = 0; i < elements(); i++) {
158       const file_transfer_record *rec = get(i);
159       if (rec && (rec->_ent == ent) && (rec->_src_root == src)
160           && (rec->_dest_root == dest) ) {
161         zap(i, i);
162         return true;
163       }
164     }
165     return false;
166   }
167
168   // clean all records for the entity "ent".
169   void whack_all(const octopus_entity &ent) {
170     for (int i = elements() - 1; i >= 0; i--) {
171       const file_transfer_record *rec = get(i);
172       if (rec && (rec->_ent == ent) )
173         zap(i, i);
174     }
175   }
176
177   // removes a file transfer correspondence.
178   bool whack_mapping(const astring &source_mapping) {
179     for (int i = elements() - 1; i >= 0; i--) {
180       const file_transfer_record *rec = get(i);
181       if (rec && (rec->_source_mapping == source_mapping) ) {
182         zap(i, i);
183         return true;
184       }
185     }
186     return false;
187   }
188
189   // returns a string dump of the fields in this list.
190   astring text_form() const {
191     astring to_return;
192     for (int i = 0; i < elements(); i++) {
193       const file_transfer_record *rec = get(i);
194       if (rec)
195         to_return += rec->text_form() + parser_bits::platform_eol_to_chars();
196     }
197     return to_return;
198   }
199 };
200
201 //////////////
202
203 class file_transfer_cleaner : public ethread
204 {
205 public:
206   file_transfer_cleaner(file_transfer_tentacle &parent)
207       : ethread(FTT_CLEANING_INTERVAL, SLACK_INTERVAL), _parent(parent) {}
208
209   virtual void perform_activity(void *formal(ptr)) { _parent.periodic_actions(); }
210
211 private:
212   file_transfer_tentacle &_parent;
213 };
214
215 //////////////
216
217 file_transfer_tentacle::file_transfer_tentacle(int maximum_transfer,
218     file_transfer_tentacle::transfer_modes mode_of_transfer)
219 : tentacle_helper<file_transfer_infoton>
220       (file_transfer_infoton::file_transfer_classifier(), false),
221   _maximum_transfer(maximum_transfer),
222   _transfers(new file_transfer_status),
223   _correspondences(new file_transfer_status),
224   _lock(new mutex),
225   _cleaner(new file_transfer_cleaner(*this)),
226   _mode(mode_of_transfer)
227 {
228   _cleaner->start(NIL);
229 }
230
231 file_transfer_tentacle::~file_transfer_tentacle()
232 {
233   _cleaner->stop();
234   WHACK(_transfers);
235   WHACK(_correspondences);
236   WHACK(_cleaner);
237   WHACK(_lock);
238 }
239
240 astring file_transfer_tentacle::text_form() const
241 {
242   AUTO_LOCK;
243   return _transfers->text_form();
244 }
245
246 void file_transfer_tentacle::expunge(const octopus_entity &to_remove)
247 {
248   AUTO_LOCK;
249   _transfers->whack_all(to_remove);
250 }
251
252 outcome file_transfer_tentacle::add_correspondence
253     (const astring &source_mapping, const astring &source_root,
254      int refresh_interval)
255 {
256   FUNCDEF("add_correspondence");
257   AUTO_LOCK;
258
259   remove_correspondence(source_mapping);  // clean the old one out first.
260
261   // create new file transfer record to hold this correspondence.
262   file_transfer_record *new_record = new file_transfer_record;
263   new_record->_source_mapping = source_mapping;
264   new_record->_src_root = source_root;
265   new_record->_refresh_interval = refresh_interval;
266   new_record->_local_dir = new directory_tree(source_root);
267 //hmmm: doesn't say anything about a pattern.  do we need to worry about that?
268
269   // check that the directory looked healthy.
270   if (!new_record->_local_dir->good()) {
271     WHACK(new_record);
272     return common::ACCESS_DENIED;
273   }
274 #ifdef DEBUG_FILE_TRANSFER_TENTACLE
275   LOG(astring("adding tree for: ent=") + new_record->_ent.text_form()
276       + " src=" + new_record->_src_root + " dest=" + new_record->_dest_root);
277 #endif
278   // calculate size and checksum info for the directory.
279   new_record->_local_dir->calculate( !(_mode & COMPARE_CONTENT_SAMPLE) );
280
281 #ifdef DEBUG_FILE_TRANSFER_TENTACLE
282   LOG(astring("done adding tree for: ent=") + new_record->_ent.text_form()
283       + " src=" + new_record->_src_root + " dest=" + new_record->_dest_root);
284 #endif
285
286   _correspondences->append(new_record);
287
288   return OKAY;
289 }
290
291 outcome file_transfer_tentacle::remove_correspondence
292     (const astring &source_mapping)
293 {
294   AUTO_LOCK;
295   if (!_correspondences->whack_mapping(source_mapping))
296     return NOT_FOUND;
297   return OKAY;
298 }
299
300 bool file_transfer_tentacle::get_differences(const octopus_entity &ent,
301     const astring &src, const astring &dest, filename_list &diffs)
302 {
303   FUNCDEF("get_differences");
304   diffs.reset();
305   AUTO_LOCK;
306   file_transfer_record *the_rec = _transfers->find(ent, src, dest);
307   if (!the_rec) return false;
308   if (!the_rec->_diffs) return false;  // no diffs listed.
309   diffs = *the_rec->_diffs;
310   return true;
311 }
312
313 bool file_transfer_tentacle::status(const octopus_entity &ent,
314     const astring &src, const astring &dest, double &total_size,
315     int &total_files, double &current_size, int &current_files, bool &done,
316     time_stamp &last_active)
317 {
318   FUNCDEF("status");
319   total_size = 0;
320   total_files = 0;
321   current_files = 0;
322   current_size = 0;
323   AUTO_LOCK;
324   file_transfer_record *the_rec = _transfers->find(ent, src, dest);
325   if (!the_rec) return false;
326   done = the_rec->_done;
327   last_active = the_rec->_last_active;
328
329   if (the_rec->_diffs) {
330     the_rec->_diffs->calculate_progress(the_rec->_last_sent._filename,
331         the_rec->_last_sent._byte_start + the_rec->_last_sent._length,
332         current_files, current_size);
333     total_files = the_rec->_diffs->total_files();
334     total_size = the_rec->_diffs->total_size();
335   }
336
337   return true;
338 }
339
340 outcome file_transfer_tentacle::register_file_transfer
341     (const octopus_entity &ent, const astring &src_root,
342     const astring &dest_root, const string_array &includes)
343 {
344   FUNCDEF("register_file_transfer");
345   AUTO_LOCK;
346   // make sure that this isn't an existing transfer.  if so, we just update
347   // the status.
348   file_transfer_record *the_rec = _transfers->find(ent, src_root, dest_root);
349   if (!the_rec) {
350     the_rec = new file_transfer_record;
351     the_rec->_src_root = src_root;
352     the_rec->_dest_root = dest_root;
353     the_rec->_ent = ent;
354     the_rec->_includes = includes;
355     _transfers->append(the_rec);  // add the new record.
356   } else {
357     the_rec->_done = false;
358     the_rec->_includes = includes;
359     the_rec->_last_active.reset();  // freshen up the last activity time.
360   }
361   return OKAY;
362 }
363
364 outcome file_transfer_tentacle::cancel_file_transfer(const octopus_entity &ent,
365     const astring &src_root, const astring &dest_root)
366 {
367   AUTO_LOCK;
368   return _transfers->whack(ent, src_root, dest_root)?  OKAY : NOT_FOUND;
369 }
370
371 directory_tree *file_transfer_tentacle::lock_directory(const astring &key)
372 {
373   _lock->lock();
374   file_transfer_record *the_rec = _correspondences->find_mapping(key);
375   if (!the_rec || !the_rec->_local_dir) {
376     _lock->unlock();
377     return NIL;  // unknown transfer.
378   }
379   return the_rec->_local_dir;
380 }
381
382 void file_transfer_tentacle::unlock_directory()
383 {
384   _lock->unlock();
385 }
386
387 bool file_transfer_tentacle::add_path(const astring &key,
388     const astring &new_path)
389 {
390   AUTO_LOCK;
391   file_transfer_record *the_rec = _correspondences->find_mapping(key);
392   if (!the_rec) return false;  // unknown transfer.
393   if (!the_rec->_local_dir) return false;  // not right type.
394   return the_rec->_local_dir->add_path(new_path) == common::OKAY;
395 }
396
397 bool file_transfer_tentacle::remove_path(const astring &key,
398     const astring &old_path)
399 {
400   AUTO_LOCK;
401   file_transfer_record *the_rec = _correspondences->find_mapping(key);
402   if (!the_rec) return false;  // unknown transfer.
403   if (!the_rec->_local_dir) return false;  // not right type.
404   return the_rec->_local_dir->remove_path(old_path) == common::OKAY;
405 }
406
407 void file_transfer_tentacle::periodic_actions()
408 {
409   FUNCDEF("periodic_actions");
410   AUTO_LOCK;
411
412   // first, we'll clean out old transfers.
413   time_stamp oldest_allowed(-TRANSFER_TIMEOUT);
414     // nothing older than this should be kept.
415   for (int i = _transfers->elements() - 1; i >= 0; i--) {
416     const file_transfer_record *curr = _transfers->get(i);
417     if (curr->_last_active < oldest_allowed) {
418 #ifdef DEBUG_FILE_TRANSFER_TENTACLE
419       LOG(astring("cleaning record for: ent=") + curr->_ent.text_form()
420           + " src=" + curr->_src_root + " dest=" + curr->_dest_root);
421 #endif
422       _transfers->zap(i, i);
423     }
424   }
425
426   // then we'll rescan any trees that are ready for it.
427   for (int i = 0; i < _correspondences->elements(); i++) {
428     file_transfer_record *curr = _correspondences->borrow(i);
429     if (curr->_last_active < time_stamp(-curr->_refresh_interval)) {
430       if (curr->_local_dir) {
431 #ifdef DEBUG_FILE_TRANSFER_TENTACLE
432         LOG(astring("refreshing tree for: ent=") + curr->_ent.text_form()
433             + " src=" + curr->_src_root + " dest=" + curr->_dest_root);
434 #endif
435         WHACK(curr->_local_dir);
436         curr->_local_dir = new directory_tree(curr->_src_root);
437         curr->_local_dir->calculate( !(_mode & COMPARE_CONTENT_SAMPLE) );
438 #ifdef DEBUG_FILE_TRANSFER_TENTACLE
439         LOG(astring("done refreshing tree for: ent=") + curr->_ent.text_form()
440             + " src=" + curr->_src_root + " dest=" + curr->_dest_root);
441 #endif
442       }
443       curr->_last_active.reset();  // reset our action time.
444     }
445   }
446 }
447
448 outcome file_transfer_tentacle::reconstitute(const string_array &classifier,
449     byte_array &packed_form, infoton * &reformed)
450 {
451   // this method doesn't use the lists, so it doesn't need locking.
452   if (classifier != file_transfer_infoton::file_transfer_classifier())
453     return NO_HANDLER;
454   return reconstituter(classifier, packed_form, reformed,
455       (file_transfer_infoton *)NIL);
456 }
457
458 // the "handle_" and "conclude_" methods are thread-safe because the mutex is locked before
459 // their invocations.
460
461 outcome file_transfer_tentacle::handle_tree_compare_request
462     (file_transfer_infoton &req, const octopus_request_id &item_id)
463 {
464   FUNCDEF("handle_tree_compare_request");
465
466   // get the mapping from the specified location on this side.
467   filename splitting(req._src_root);
468   string_array pieces;
469   splitting.separate(pieces);
470   astring source_mapping = pieces[0];
471
472   // patch the name up to find the sub_path for the source.
473   filename source_start;
474   pieces.zap(0, 0);
475   source_start.join(pieces);
476
477   // locate the allowed transfer depot for the mapping they provided.
478   file_transfer_record *mapping_record
479       = _correspondences->find_mapping(source_mapping);
480   if (!mapping_record) {
481     LOG(astring("could not find source mapping of ") + source_mapping);
482     return NOT_FOUND;
483   }
484
485   // unpack the tree that they sent us which describes their local area.
486   directory_tree *dest_tree = new directory_tree;
487   if (!dest_tree->unpack(req._packed_data)) {
488     LOG(astring("could not unpack requester's directory tree"));
489     WHACK(dest_tree);
490     return GARBAGE;
491   }
492
493   string_array requested_names;
494   if (!requested_names.unpack(req._packed_data)) {
495     LOG(astring("could not unpack requester's filename includes"));
496     WHACK(dest_tree);
497     return GARBAGE;
498   }
499
500   // look up to see if this is about something that has already been seen.
501   // we don't want to add a new transfer record if they're already working on
502   // this.  that also lets them do a new tree compare to restart the transfer.
503   file_transfer_record *the_rec = _transfers->find(item_id._entity,
504       req._src_root, req._dest_root);
505   if (!the_rec) {
506     // there was no existing record; we'll create a new one.
507     the_rec = new file_transfer_record;
508     the_rec->_ent = item_id._entity;
509     the_rec->_src_root = req._src_root;
510     the_rec->_dest_root = req._dest_root;
511     _transfers->append(the_rec);
512   } else {
513     // record some activity on this record.
514     the_rec->_done = false;
515     the_rec->_last_active.reset();
516   }
517
518   the_rec->_diffs = new filename_list;
519
520   int how_comp = file_info::EQUAL_NAME;  // the prize for doing nothing.
521   if (_mode & COMPARE_SIZE_AND_TIME)
522     how_comp |= file_info::EQUAL_FILESIZE | file_info::EQUAL_TIMESTAMP;
523   if (_mode & COMPARE_CONTENT_SAMPLE)
524     how_comp |= file_info::EQUAL_CHECKSUM;
525
526   // compare the two trees of files.
527   directory_tree::compare_trees(*mapping_record->_local_dir,
528       source_start.raw(), *dest_tree, astring::empty_string(),
529       *the_rec->_diffs, (file_info::file_similarity)how_comp);
530
531 //LOG(astring("filenames decided as different:\n") + the_rec->_diffs->text_form());
532
533   // now prune the diffs to accord with what they claim they want.
534   if (requested_names.length()) {
535     for (int i = the_rec->_diffs->elements() - 1; i >= 0; i--) {
536       filename diff_curr = *the_rec->_diffs->get(i);
537       bool found = false;
538       for (int j = 0; j < requested_names.length(); j++) {
539         filename req_curr(requested_names[j]);
540         if (req_curr.compare_suffix(diff_curr)) {
541           found = true;
542 //LOG(astring("will use: ") + req_curr);
543           break;
544         }
545       }
546       if (!found) the_rec->_diffs->zap(i, i);
547     }
548   }
549
550   req._packed_data.reset();  // clear out existing stuff before cloning.
551   file_transfer_infoton *reply = dynamic_cast<file_transfer_infoton *>(req.clone());
552   the_rec->_diffs->pack(reply->_packed_data);
553
554 //hmmm: does the other side really need the list of filenames?  i guess we
555 //      could check validity of what's transferred or check space available
556 //      before the client starts the transfer.
557
558   reply->_request = false;  // it's a response now.
559   store_product(reply, item_id);
560     // send back the comparison list.
561
562   return OKAY;
563 }
564
565 outcome file_transfer_tentacle::handle_tree_compare_response
566     (file_transfer_infoton &resp, const octopus_request_id &item_id)
567 {
568   FUNCDEF("handle_tree_compare_response");
569   file_transfer_record *the_rec = _transfers->find(item_id._entity,
570       resp._src_root, resp._dest_root);
571   if (!the_rec) {
572     LOG(astring("could not find the record for this transfer: item=")
573         + item_id.text_form() + " src=" + resp._src_root + " dest="
574         + resp._dest_root);
575     return NOT_FOUND;  // not registered, so reject it.
576   }
577
578   the_rec->_last_active.reset();  // record some activity on this record.
579
580   filename_list *flist = new filename_list;
581   if (!flist->unpack(resp._packed_data)) {
582     WHACK(flist);
583     return GARBAGE;
584   }
585
586 //hmmm: verify space on device?
587
588   the_rec->_diffs = flist;  // set the list of differences.
589   return OKAY;
590 }
591
592 outcome file_transfer_tentacle::handle_storage_request
593     (file_transfer_infoton &req, const octopus_request_id &item_id)
594 {
595   FUNCDEF("handle_storage_request");
596   if (_mode & ONLY_REPORT_DIFFS) {
597     // store an unhandled infoton.
598     unhandled_request *deny = new unhandled_request(item_id, req.classifier(), NO_HANDLER);
599     store_product(deny, item_id);
600     return NO_HANDLER;
601   }
602
603   // look up the transfer record.
604   file_transfer_record *the_rec = _transfers->find(item_id._entity,
605       req._src_root, req._dest_root);
606   if (!the_rec) {
607     LOG(astring("could not find the record for this transfer: item=")
608         + item_id.text_form() + " src=" + req._src_root + " dest="
609         + req._dest_root);
610     return NOT_FOUND;  // not registered, so reject it.
611   }
612
613   the_rec->_last_active.reset();  // mark it as still active.
614
615   file_transfer_infoton *resp = dynamic_cast<file_transfer_infoton *>(req.clone());
616
617   if (!the_rec->_diffs) return BAD_INPUT;  // wrong type of object.
618
619   outcome bufret = heavy_file_operations::buffer_files
620       (_correspondences->translate(the_rec->_src_root), *the_rec->_diffs,
621       the_rec->_last_sent, resp->_packed_data, _maximum_transfer);
622   if (bufret == heavy_file_operations::FINISHED) {
623     // finish by setting command to be a conclude marker.
624     the_rec->_done = true;
625     resp->_command = file_transfer_infoton::CONCLUDE_TRANSFER_MARKER;
626     bufret = OKAY;  // now it's no longer an exceptional outcome.
627   } else if (bufret != OKAY) {
628     // complain, but still send.
629     LOG(astring("buffer files returned an error on item=")
630         + item_id.text_form() + " src=" + req._src_root + " dest="
631         + req._dest_root);
632   }
633
634 //can remove this block if stops saying it.
635   if ((bufret == OKAY) && !resp->_packed_data.length() ) {
636     LOG("marking empty transfer as done; why not caught above at FINISHED check?");
637     the_rec->_done = true;
638     resp->_command = file_transfer_infoton::CONCLUDE_TRANSFER_MARKER;
639   }
640 //end of can remove.
641
642   resp->_request = false;  // it's a response now.
643   store_product(resp, item_id);
644   return bufret;
645 }
646
647 outcome file_transfer_tentacle::handle_storage_response
648     (file_transfer_infoton &resp, const octopus_request_id &item_id)
649 {
650   FUNCDEF("handle_storage_response");
651   if (_mode & ONLY_REPORT_DIFFS) {
652     // not spoken here.
653     return NO_HANDLER;
654   }
655
656   // look up the transfer record.
657   file_transfer_record *the_rec = _transfers->find(item_id._entity,
658       resp._src_root, resp._dest_root);
659   if (!the_rec) return NOT_FOUND;  // not registered, so reject it.
660
661   the_rec->_last_active.reset();  // mark it as still active.
662
663   if (!resp._packed_data.length()) {
664     // mark that we're done now.
665     the_rec->_done = true;
666   }
667
668   // chew on all the things they sent us.
669   while (resp._packed_data.length()) {
670     file_time empty;
671     file_transfer_header found(empty);
672     if (!found.unpack(resp._packed_data)) {
673       // bomb out now.
674       LOG(astring("corruption seen on item=") + item_id.text_form()
675           + " src=" + resp._src_root + " dest=" + resp._dest_root);
676       return GARBAGE;
677     }
678     the_rec->_last_sent = found;
679
680     if (found._length > resp._packed_data.length()) {
681       // another case for leaving--not enough data left in the buffer.
682       LOG(astring("data underflow seen on item=") + item_id.text_form()
683           + " src=" + resp._src_root + " dest=" + resp._dest_root);
684       return GARBAGE;
685     }
686     byte_array to_write = resp._packed_data.subarray(0, found._length - 1);
687     resp._packed_data.zap(0, found._length - 1);
688
689     if (!the_rec->_diffs) return BAD_INPUT;
690
691     const file_info *recorded_info = the_rec->_diffs->find(found._filename);
692     if (!recorded_info) {
693       LOG(astring("unrequested file seen: ") + found._filename);
694       continue;  // maybe there are others that aren't confused.
695     }
696
697     astring full_file = resp._dest_root + filename::default_separator()
698         + recorded_info->secondary();
699
700     outcome ret = heavy_file_operations::write_file_chunk(full_file,
701         found._byte_start, to_write);
702     if (ret != OKAY) {
703       LOG(astring("failed to write file chunk: error=")
704           + heavy_file_operations::outcome_name(ret) + " file=" + full_file
705           + a_sprintf(" start=%d len=%d", found._byte_start, found._length));
706     }
707     found._time.set_time(full_file);
708   }
709
710   // there is no response product to store.
711   return OKAY;
712 }
713
714 outcome file_transfer_tentacle::conclude_storage_request
715     (file_transfer_infoton &req, const octopus_request_id &item_id)
716 {
717   FUNCDEF("conclude_storage_request");
718   if (_mode & ONLY_REPORT_DIFFS) {
719     // store an unhandled infoton.
720     unhandled_request *deny = new unhandled_request(item_id, req.classifier(), NO_HANDLER);
721     store_product(deny, item_id);
722     return NO_HANDLER;
723   }
724
725   // look up the transfer record.
726   file_transfer_record *the_rec = _transfers->find(item_id._entity,
727       req._src_root, req._dest_root);
728   if (!the_rec) {
729     LOG(astring("could not find the record for this transfer: item=")
730         + item_id.text_form() + " src=" + req._src_root + " dest="
731         + req._dest_root);
732     return NOT_FOUND;  // not registered, so reject it.
733   }
734
735   the_rec->_last_active.reset();  // mark it as still active.
736
737   file_transfer_infoton *resp = dynamic_cast<file_transfer_infoton *>(req.clone());
738
739   if (!the_rec->_diffs) return BAD_INPUT;  // wrong type of object.
740
741   the_rec->_done = true;  // we're concluding the transfer, so that's that.
742   resp->_request = false;  // it's a response now.
743   store_product(resp, item_id);
744
745   LOG(astring("concluding transfer request on src=") + req._src_root + " dest="
746       + req._dest_root);
747
748   return common::OKAY;
749 }
750
751 outcome file_transfer_tentacle::conclude_storage_response
752     (file_transfer_infoton &resp, const octopus_request_id &item_id)
753 {
754   FUNCDEF("conclude_storage_response");
755   if (_mode & ONLY_REPORT_DIFFS) {
756     // not spoken here.
757     return NO_HANDLER;
758   }
759
760   // look up the transfer record.
761   file_transfer_record *the_rec = _transfers->find(item_id._entity,
762       resp._src_root, resp._dest_root);
763   if (!the_rec) return NOT_FOUND;  // not registered, so reject it.
764
765   the_rec->_last_active.reset();  // mark it as still active.
766
767   // mark that we're done now.
768   the_rec->_done = true;
769
770   LOG(astring("concluding transfer response on src=") + resp._src_root + " dest="
771       + resp._dest_root);
772
773   // there is no response product to store.
774   return OKAY;
775 }
776
777 // consume() is the only method that is allowed to invoke the "handle_X" methods
778 // and it must lock the object beforehand.
779
780 outcome file_transfer_tentacle::consume(infoton &to_chow,
781     const octopus_request_id &item_id, byte_array &transformed)
782 {
783   FUNCDEF("consume");
784   transformed.reset();
785   file_transfer_infoton *inf = dynamic_cast<file_transfer_infoton *>(&to_chow);
786   if (!inf) return DISALLOWED;  // not for us.
787
788   AUTO_LOCK;  // protect our lists while we're working on them.
789
790   switch (inf->_command) {
791     case file_transfer_infoton::TREE_COMPARISON: {
792       if (inf->_request) return handle_tree_compare_request(*inf, item_id);
793       else return handle_tree_compare_response(*inf, item_id);
794     }
795     case file_transfer_infoton::PLACE_FILE_CHUNKS: {
796       if (inf->_request) return handle_storage_request(*inf, item_id);
797       else return handle_storage_response(*inf, item_id);
798     }
799     case file_transfer_infoton::CONCLUDE_TRANSFER_MARKER: {
800       if (inf->_request) return conclude_storage_request(*inf, item_id);
801       else return conclude_storage_response(*inf, item_id);
802     }
803   }
804   return BAD_INPUT;  // not a recognized command.
805 }
806
807 outcome file_transfer_tentacle::refresh_now(const astring &source_mapping)
808 {
809   FUNCDEF("refresh_now");
810   AUTO_LOCK;
811   for (int i = 0; i < _correspondences->elements(); i++) {
812     file_transfer_record *curr = _correspondences->borrow(i);
813     if (!curr) continue;
814     if (curr->_source_mapping != source_mapping) continue;
815     if (curr->_local_dir) {
816 #ifdef DEBUG_FILE_TRANSFER_TENTACLE
817       LOG(astring("refreshing tree for: ent=") + curr->_ent.text_form()
818           + " src=" + curr->_src_root + " dest=" + curr->_dest_root);
819 #endif
820       WHACK(curr->_local_dir);
821       curr->_local_dir = new directory_tree(curr->_src_root);
822       curr->_local_dir->calculate( !(_mode & COMPARE_CONTENT_SAMPLE) );
823 #ifdef DEBUG_FILE_TRANSFER_TENTACLE
824       LOG(astring("done refreshing tree for: ent=") + curr->_ent.text_form()
825           + " src=" + curr->_src_root + " dest=" + curr->_dest_root);
826 #endif
827     }
828     curr->_last_active.reset();  // reset our action time.
829     return OKAY;
830   }
831   return NOT_FOUND;
832 }
833
834 } //namespace.
835
836