6c4765e9243fb83c88773f1e8cdd8c50ee8ba6dd
[feisty_meow.git] / nucleus / library / filesystem / heavy_file_ops.cpp
1 /*****************************************************************************\
2 *                                                                             *
3 *  Name   : heavy file operations                                             *
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 "directory.h"
16 #include "filename.h"
17 #include "filename_list.h"
18 #include "heavy_file_ops.h"
19 #include "huge_file.h"
20
21 #include <basis/functions.h>
22 #include <basis/guards.h>
23 #include <structures/object_packers.h>
24
25 using namespace basis;
26 using namespace structures;
27
28 namespace filesystem {
29
30 #define DEBUG_HEAVY_FILE_OPS
31   // uncomment for noisier debugging.
32
33 #undef LOG
34 #ifdef DEBUG_HEAVY_FILE_OPS
35   #include <stdio.h>
36   #define LOG(to_print) printf("%s::%s: %s\n", static_class_name(), func, astring(to_print).s())
37 #else
38   #define LOG(s) {if(!!s){}}
39 #endif
40
41 //////////////
42
43 // the smallest we let the packing area's available space get before we stop filling it.
44 const int MINIMUM_ARRAY_SIZE = 1024;
45
46 //////////////
47
48 file_transfer_header::file_transfer_header(const file_time &time_stamp)
49 : _filename(),
50   _byte_start(0),
51   _length(0),
52   _time(time_stamp)
53 {
54 }
55
56 astring file_transfer_header::text_form() const
57 {
58   astring time_text;
59   _time.text_form(time_text);
60   return astring("file=") + _filename
61       + a_sprintf(" start=%d len=%d stamp=", _byte_start, _length)
62       + time_text;
63 }
64
65 astring file_transfer_header::readable_text_form() const
66 {
67   astring time_text;
68   _time.readable_text_form(time_text);
69   return _filename
70       + a_sprintf(" [%d bytes, mod ", _length)
71       + time_text + "]";
72 }
73
74 void file_transfer_header::pack(byte_array &packed_form) const
75 {
76   _filename.pack(packed_form);
77   attach(packed_form, _byte_start);
78   attach(packed_form, _length);
79   _time.pack(packed_form);
80 }
81
82 bool file_transfer_header::unpack(byte_array &packed_form)
83 {
84   if (!_filename.unpack(packed_form)) return false;
85   if (!detach(packed_form, _byte_start)) return false;
86   if (!detach(packed_form, _length)) return false;
87   if (!_time.unpack(packed_form)) return false;
88   return true;
89 }
90
91 int file_transfer_header::packed_size() const
92 {
93 byte_array temp;
94 attach(temp, _byte_start);
95 //hmmm: really ugly above; we should get a more exact way to know the size of
96 //      packed doubles.
97   return _filename.length() + 1
98       + temp.length()
99       + sizeof(int)
100       + _time.packed_size();
101 }
102
103 //////////////
104
105 const size_t heavy_file_operations::COPY_CHUNK_FACTOR = 1 * MEGABYTE;
106
107 size_t heavy_file_operations::copy_chunk_factor()
108 { return COPY_CHUNK_FACTOR; }
109
110 heavy_file_operations::~heavy_file_operations() {}
111   // we only need this due to our use of the root_object class_name support.
112
113 const char *heavy_file_operations::outcome_name(const outcome &to_name)
114 {
115   switch (to_name.value()) {
116     case SOURCE_MISSING: return "SOURCE_MISSING";
117     case TARGET_ACCESS_ERROR: return "TARGET_ACCESS_ERROR";
118     case TARGET_DIR_ERROR: return "TARGET_DIR_ERROR";
119     default: return common::outcome_name(to_name);
120   }
121 }
122
123 outcome heavy_file_operations::copy_file(const astring &source,
124     const astring &destination, int copy_chunk_factor)
125 {
126 #ifdef DEBUG_HEAVY_FILE_OPS
127   FUNCDEF("copy_file");
128 #endif
129   // check that the source exists...
130   filename source_path(source);
131   if (!source_path.exists()) return SOURCE_MISSING;
132   file_time source_time(source_path);  // get the time on the source.
133
134   // make sure the target directory exists...
135   filename target_path(destination);
136   filename targ_dir = target_path.dirname();
137   if (!directory::recursive_create(targ_dir.raw())) return TARGET_DIR_ERROR;
138
139   // open the source for reading.
140   huge_file source_file(source, "rb");
141   if (!source_file.good()) return SOURCE_MISSING;
142 //hmmm: could be source is not accessible instead.
143
144   // open target file for writing.
145   huge_file target_file(destination, "wb");
146   if (!target_file.good()) return TARGET_ACCESS_ERROR;
147
148   byte_array chunk;
149   int bytes_read = 0;
150   outcome ret;
151   while ( (ret = source_file.read(chunk, copy_chunk_factor, bytes_read))
152       == huge_file::OKAY) {
153     int bytes_stored;
154     ret = target_file.write(chunk, bytes_stored);
155     if (bytes_stored != bytes_read) return TARGET_ACCESS_ERROR;
156     if (source_file.eof()) break;  // time to escape.
157   }
158
159   // set the time on the target file from the source's time.
160   source_time.set_time(target_path);
161
162 #ifdef DEBUG_HEAVY_FILE_OPS
163   astring time;
164   source_time.text_form(time);
165   LOG(astring("setting file time for ") + source + " to " + time);
166 #endif
167
168   return OKAY;
169 }
170
171 outcome heavy_file_operations::write_file_chunk(const astring &target,
172     double byte_start, const byte_array &chunk, bool truncate,
173     int copy_chunk_factor)
174 {
175   FUNCDEF("write_file_chunk");
176   if (byte_start < 0) return BAD_INPUT;
177
178   filename targ_name(target);
179   if (!directory::recursive_create(targ_name.dirname().raw()))
180     return TARGET_DIR_ERROR;
181
182   if (!targ_name.exists()) {
183     huge_file target_file(target, "w");
184   }
185
186   huge_file target_file(target, "r+b");
187     // open the file for updating (either read or write).
188   if (!target_file.good()) return TARGET_ACCESS_ERROR;
189   double curr_len = target_file.length();
190
191   if (curr_len < byte_start) {
192     byte_array new_chunk;
193     while (curr_len < byte_start) {
194       target_file.seek(0, byte_filer::FROM_END);  // go to the end of the file.
195       new_chunk.reset(minimum(copy_chunk_factor,
196           int(curr_len - byte_start + 1)));
197       int written;
198       outcome ret = target_file.write(new_chunk, written);
199       if (written < new_chunk.length()) return TARGET_ACCESS_ERROR;
200       curr_len = target_file.length();
201     }
202   }
203   target_file.seek(byte_start, byte_filer::FROM_START);
204     // jump to the proper location in the file.
205   int wrote;
206   outcome ret = target_file.write(chunk, wrote);
207   if (wrote != chunk.length()) return TARGET_ACCESS_ERROR;
208   if (truncate) {
209     target_file.truncate();
210   }
211   return OKAY;
212 }
213
214 basis::outcome heavy_file_operations::advance(const filename_list &to_transfer,
215     file_transfer_header &last_action)
216 {
217   FUNCDEF("advance");
218   int indy = to_transfer.locate(last_action._filename);
219   if (negative(indy)) return BAD_INPUT;  // error, file not found in list.
220   if (indy >= to_transfer.elements() - 1) return FINISHED;  // done.
221   const file_info *currfile = to_transfer.get(indy + 1);
222   last_action._filename = currfile->raw();
223   last_action._time = currfile->_time;
224
225 #ifdef DEBUG_HEAVY_FILE_OPS
226   if (currfile->_time == file_time(time_t(0)))
227     LOG(astring("failed for ") + currfile->raw() + " -- has zero file time");
228 #endif
229
230   last_action._byte_start = 0;
231   last_action._length = 0;
232   return OKAY;
233 }
234
235 outcome heavy_file_operations::buffer_files(const astring &source_root,
236     const filename_list &to_transfer, file_transfer_header &last_action,
237     byte_array &storage, int maximum_bytes)
238 {
239   FUNCDEF("buffer_files");
240   storage.reset();  // clear out the current contents.
241
242   if (!to_transfer.elements()) {
243     // we seem to be done.
244     return FINISHED;
245   }
246
247   outcome to_return = OKAY;
248
249   // start filling the array with bytes from the files.
250   while (storage.length() < maximum_bytes) {
251     double remaining_in_array = maximum_bytes - storage.length()
252         - last_action.packed_size();
253     if (remaining_in_array < MINIMUM_ARRAY_SIZE) {
254       // ensure that we at least have a reasonable amount of space left
255       // for storing into the array.
256       break;
257     }
258
259     // find the current file we're at, as provided in record.
260     if (!last_action._filename) {
261       // no filename yet.  assume this is the first thing we've done.
262       const file_info *currfile = to_transfer.get(0);
263       last_action._filename = currfile->raw();
264       last_action._time = currfile->_time;
265       last_action._byte_start = 0;
266       last_action._length = 0;
267     }
268
269     const file_info *found = to_transfer.find(last_action._filename);
270     if (!found) {
271       // they have referenced a file that we don't have.  that's bad news.
272       return BAD_INPUT;
273     }
274
275     astring full_file = source_root + "/" + last_action._filename;
276     huge_file current(full_file, "rb");
277     if (!current.good()) {
278       // we need to skip this file.
279       LOG(astring("skipping bad file: ") + full_file);
280       to_return = advance(to_transfer, last_action);
281       if (to_return != OKAY) break;
282       continue;
283     }
284
285     if (last_action._byte_start + last_action._length >= current.length()) {
286       // this file is done now.  go to the next one.
287       LOG(astring("finished stuffing file: ") + full_file);
288       to_return = advance(to_transfer, last_action);
289       if (to_return != OKAY) break;
290       continue;
291     }
292
293     // calculate the largest piece remaining of that file that will fit in the
294     // allotted space.
295     double new_start = last_action._byte_start + last_action._length;
296     double remaining_in_file = current.length() - new_start;
297     if (remaining_in_file < 0) remaining_in_file = 0;
298     double new_len = minimum(remaining_in_file, remaining_in_array);
299     
300     // pack this new piece of the file.
301     current.seek(new_start, byte_filer::FROM_START);
302     byte_array new_chunk;
303     int bytes_read = 0;
304     outcome ret = current.read(new_chunk, int(new_len), bytes_read);
305     if (bytes_read != new_len) {
306       if (!bytes_read) {
307         // some kind of problem reading the file.
308         to_return = advance(to_transfer, last_action);
309         if (to_return != OKAY) break;
310         continue;
311       }
312 //why would this happen?  just complain, i guess.
313     }
314
315     // update the record since it seems we're successful here.
316     last_action._byte_start = new_start;
317     last_action._length = int(new_len);
318
319     // add in this next new chunk of file.
320     last_action.pack(storage);  // add the header.
321     storage += new_chunk;  // add the new stuff.
322
323     if (!current.length()) {
324       // ensure we don't get stuck redoing zero length files, which we allowed
325       // to go past their end above (since otherwise we'd never see them).
326       to_return = advance(to_transfer, last_action);
327       if (to_return != OKAY) break;
328       continue;
329     }
330     
331     // just keep going, if there's space...
332   }
333
334   return to_return;
335 }
336
337 } //namespace.
338