updates from orpheus for windoze build
[feisty_meow.git] / nucleus / applications / bundler / bundle_creator.cpp
1
2 //hmmm: anything related to _stub_size should be kept, but that is where
3 //      we need a redundant search mechanism that can't be fooled so easily
4 //      by modifying exe; make a pattern that will be found and is the first
5 //      place to start looking for manifest.
6
7 /*****************************************************************************\
8 *                                                                             *
9 *  Name   : bundle_creator                                                    *
10 *  Author : Chris Koeritz                                                     *
11 *                                                                             *
12 *******************************************************************************
13 * Copyright (c) 2006-$now By Author.  This program is free software; you can  *
14 * redistribute it and/or modify it under the terms of the GNU General Public  *
15 * License as published by the Free Software Foundation; either version 2 of   *
16 * the License or (at your option) any later version.  This is online at:      *
17 *     http://www.fsf.org/copyleft/gpl.html                                    *
18 * Please send any updates to: fred@gruntose.com                               *
19 \*****************************************************************************/
20
21 #include "common_bundle.h"
22
23 #include <application/hoople_main.h>
24 #include <application/command_line.h>
25 #include <basis/array.h>
26 #include <basis/byte_array.h>
27 #include <basis/environment.h>
28 #include <configuration/application_configuration.h>
29 #include <configuration/ini_configurator.h>
30 #include <configuration/variable_tokenizer.h>
31 #include <filesystem/byte_filer.h>
32 #include <filesystem/directory.h>
33 #include <filesystem/filename.h>
34 #include <filesystem/file_time.h>
35 #include <loggers/console_logger.h>
36 #include <loggers/file_logger.h>
37 #include <processes/launch_process.h>
38 #include <structures/static_memory_gremlin.h>
39 #include <structures/string_table.h>
40 #include <textual/byte_formatter.h>
41 #include <textual/list_parsing.h>
42 #include <textual/parser_bits.h>
43 #include <timely/time_stamp.h>
44
45 #include <stdio.h>
46 #include <sys/stat.h>
47 #include <zlib.h>
48 //#ifdef __WIN32__
49   //#include <io.h>
50 //#endif
51
52 using namespace application;
53 using namespace basis;
54 using namespace configuration;
55 using namespace filesystem;
56 using namespace loggers;
57 using namespace filesystem;
58 using namespace processes;
59 using namespace structures;
60 using namespace textual;
61 using namespace timely;
62
63 const int CHUNKING_SIZE = 256 * KILOBYTE;
64   // we'll read this big a chunk from a source file at a time.
65
66 const astring SUBVERSION_FOLDER = ".svn";
67   // we don't want to include this in a bundle.
68
69 #define BASE_LOG(to_print) program_wide_logger::get().log(to_print, ALWAYS_PRINT)
70 #define LOG(to_print) CLASS_EMERGENCY_LOG(program_wide_logger::get(), to_print)
71
72 //#define DEBUG_BUNDLER
73   // uncomment for noisy debugging version.
74
75 // returns the "retval" and mentions that this is a failure at "where".
76 #define FAIL_RETURN(retval, where) { \
77   LOG(astring("failure in ") + where + a_sprintf(", exit=%d", retval)); \
78   return retval; \
79 }
80
81 ////////////////////////////////////////////////////////////////////////////
82
83 bool true_value(const astring &value)
84 { return (!value.equal_to("0")) && (!value.equal_to("false")); }
85
86 ////////////////////////////////////////////////////////////////////////////
87
88 // this structure overrides the manifest_chunk by providing a source string.
89
90 struct bundled_chunk : manifest_chunk
91 {
92   astring _source;  //!< where the file comes from on the source system.
93   virtual ~bundled_chunk() {}
94 };
95
96 ////////////////////////////////////////////////////////////////////////////
97
98 // main bundler class.
99
100 class bundle_creator : public application_shell
101 {
102 public:
103   bundle_creator()
104       : application_shell(),
105         _app_name(filename(_global_argv[0]).basename()),
106         _bundle(NULL_POINTER), _stub_size(0), _keyword() {}
107
108   virtual ~bundle_creator() {
109     WHACK(_bundle);
110   }
111
112   DEFINE_CLASS_NAME("bundle_creator");
113   virtual int execute();
114   int print_instructions();
115
116   astring determine_stub_file_and_validate();
117     //!< returns the stub file location if it could be successfully located.
118
119   int open_output_file();
120     //!< prepares the output file to be written into.
121     /*!< non-zero return indicates an error. */
122
123   int read_manifest();
124     //!< reads manifest definition specifying files in the bundle.
125     /*!< creates the list of bundle pieces. */
126
127   int write_stub_and_toc();
128     //!< stuffs the unpacker stub into output file and table of contents.
129
130   int bundle_sources();
131     //!< reads all of the input files and dumps them into the bundle.
132
133   int finalize_file();
134     //!< puts finishing touches on the output file and closes it.
135
136   int write_offset();
137     //!< writes the offset position into the output file.
138     /*!< this happens at the specially marked location (muftiloc). */
139
140   int patch_recursive_target(const astring &source, const astring &target,
141           int manifest_index);
142     //!< processes the recursive target specified in "curr".
143     /*!< the manifest_index tells the function where the external caller
144     is currently working on the manifest.  new items will appear just after
145     that index. */
146
147   int recurse_into_dir(const astring &source, const astring &target,
148           int manifest_index);
149     //!< adds all files from "source" to our list, recurses on dirs.
150
151   int patch_wildcard_target(const astring &source, const astring &target,
152           int manifest_index);
153     //!< processes the wildcard bearing target specified in "curr".
154     /*!< any new source items will get dropped on the end of the manifest. */
155
156   int add_files_here(directory &dirndl, const astring &source,
157           const astring &target, int manifest_index);
158     //!< takes all the files found in "source" and adds them to manifest.
159
160   bool get_file_size(const astring &file, un_int &size, byte_array &timestamp);
161     //!< returns the file "size" and "timestamp" found for "file".
162
163 private:
164   astring _app_name;  //!< application name for this program.
165   astring _output_file;  //!< what bundle file to create.
166   astring _manifest_file;  //!< the manifest of what's included in bundle.
167   array<bundled_chunk> _manifest_list;  //!< the parsed list of contents.
168   byte_filer *_bundle;  //!< points at the bundled output file.
169   int _stub_size;  //!< where the TOC will be located.
170   astring _keyword;  // set if we were given a keyword on cmd line.
171 };
172
173 ////////////////////////////////////////////////////////////////////////////
174
175 int bundle_creator::print_instructions()
176 {
177   BASE_LOG(a_sprintf("\
178 %s: This program needs two parameters on the command line.\n\
179 The -o flag must point at the bundled output file to create.  The -m flag\n\
180 must point at a valid manifest file that defines what will be packed into\n\
181 the output file.  See the example manifest in the bundler example\n\
182 (in setup_src/bundle_example) for more information on the required file\n\
183 format.\n\
184 ", _app_name.s()));
185   return 4;
186 }
187
188 int bundle_creator::execute()
189 {
190   FUNCDEF("execute");
191
192   BASE_LOG(astring("starting file bundling at ") + time_stamp::notarize(false));
193
194   command_line cmds(_global_argc, _global_argv);
195   astring temp;
196   if (cmds.get_value('?', temp)) return print_instructions();
197   if (cmds.get_value("?", temp)) return print_instructions();
198   if (!cmds.get_value('o', _output_file)) return print_instructions();
199   if (!cmds.get_value('m', _manifest_file)) return print_instructions();
200
201   if (filename(_output_file).exists()) {
202     BASE_LOG(a_sprintf("\
203 %s: The output file already exists.  Please move it out of\n\
204 the way; this program will not overwrite existing files.\n",
205 _app_name.s()));
206     return 3;
207   }
208
209   if (!filename(_manifest_file).exists()) {
210     BASE_LOG(a_sprintf("\
211 %s: The manifest file does not exist.  This program cannot do anything\n\
212 without a valid packing manifest.\n", _app_name.s()));
213     return 2;
214   }
215
216   // test this early on so we don't waste time uselessly.
217   astring stub_file_okay = determine_stub_file_and_validate();
218   if (!stub_file_okay) {
219     BASE_LOG(a_sprintf("\
220 %s: The unpacking stub file does not exist (check binaries folder).\n\
221 Abandoning bundling process.\n", _app_name.s()));
222     return 4;
223   }
224
225   // make sure we snag any keyword that was passed on the command line.
226   cmds.get_value("keyword", _keyword);
227
228   // first step is to provide some built-in variables that can be used to
229   // make the manifests less platform specific.  this doesn't really help
230   // if you bundle it on linux and try to run it on windows.  but either
231   // platform's resources can easily be made into a bundle with the same
232   // packing manifest.
233 #ifndef __WIN32__
234   environment::set("EXE_END", "");  // executable file ending.
235   environment::set("DLL_START", "lib");  // dll file prefix.
236   environment::set("DLL_END", ".so");  // dll file ending.
237 #else
238   environment::set("EXE_END", ".exe");
239   environment::set("DLL_START", "");
240   environment::set("DLL_END", ".dll");
241 #endif
242   // specify a target variable on the source side so that we can operate in there,
243   // even if the bundle doesn't specify one.  otherwise we can't run source side commands
244   // properly if the paths are based on TARGET (like TMP often is).
245   environment::set("TARGET", environment::TMP());
246
247   int ret = 0;
248   if ( (ret = read_manifest()) ) FAIL_RETURN(ret, "reading manifest");
249     // read manifest to build list of what's what.
250   if ( (ret = open_output_file()) ) FAIL_RETURN(ret, "opening output file");
251     // open up our output file for the bundled chunks.
252   if ( (ret = write_stub_and_toc()) ) FAIL_RETURN(ret, "writing stub and TOC");
253     // writes the stub unpacker application and the table of contents to the 
254     // output file.
255   if ( (ret = bundle_sources()) ) FAIL_RETURN(ret, "bundling source files");
256     // stuff all the source files into the output bundle.
257   if ( (ret = finalize_file()) ) FAIL_RETURN(ret, "finalizing file");
258     // finishes with the file and closes it up.
259   if ( (ret = write_offset()) ) FAIL_RETURN(ret, "writing offset");
260     // stores the offset of the TOC into the output file in a special location
261     // that is delineated by a known keyword (muftiloc) and which should only
262     // exist in the file in one location.
263
264   return 0;
265 }
266
267 int bundle_creator::open_output_file()
268 {
269   FUNCDEF("open_output_file");
270   _bundle = new byte_filer(_output_file, "wb");
271   if (!_bundle->good()) {
272     LOG(astring("failed to open the output file: ") + _output_file);
273     return 65;
274   }
275   return 0;
276 }
277
278 bool bundle_creator::get_file_size(const astring &infile, un_int &size,
279     byte_array &time_stamp)
280 {
281   FUNCDEF("get_file_size");
282   time_stamp.reset();
283   // access the source file to get its size.
284   byte_filer source_file(infile, "rb");
285   if (!source_file.good()) {
286     LOG(astring("could not access the file for size check: ") + infile);
287     return false;
288   }
289   size = int(source_file.length());
290   file_time tim(infile);
291   tim.pack(time_stamp);
292   return true;
293 }
294
295 int bundle_creator::add_files_here(directory &dirndl, const astring &source,
296     const astring &target, int manifest_index)
297 {
298   FUNCDEF("add_files_here");
299   for (int i = 0; i < dirndl.files().length(); i++) {
300     astring curry = dirndl.files()[i];
301     // skip .svn folders and contents.
302     if (curry.contains(SUBVERSION_FOLDER)) continue;
303 //hmmm: this could be a much nicer generalized file exclusion list.
304
305 //LOG(astring("file is: ") + curry);
306     bundled_chunk new_guy;
307     new_guy._source = source + "/" + curry;  // the original full path to it.
308     new_guy._payload = target + "/" + curry;
309     new_guy._keywords = _manifest_list[manifest_index]._keywords;
310     // copy the flags from the parent, so we don't forget options.
311     new_guy._flags = _manifest_list[manifest_index]._flags;
312     // remove some flags that make no sense for the new guy.
313     new_guy._flags &= ~RECURSIVE_SRC;
314
315 //LOG(a_sprintf("adding: source=%s targ=%s", new_guy._source.s(), new_guy._payload.s()));
316     bool okaysize = get_file_size(new_guy._source, new_guy._size, new_guy.c_filetime);
317     if (!okaysize || (new_guy._size < 0) ) {
318       LOG(astring("failed to get file size for ") + new_guy._source);
319       return 75;
320     }
321
322     _manifest_list.insert(manifest_index + 1, 1);
323     _manifest_list[manifest_index + 1] = new_guy;
324   }
325   return 0;
326 }
327
328 int bundle_creator::recurse_into_dir(const astring &source,
329     const astring &target, int manifest_index)
330 {
331   FUNCDEF("recurse_into_dir");
332 //LOG(astring("src=") + source + " dest=" + target);
333
334   // we won't include the subversion folder.
335   if (source.contains(SUBVERSION_FOLDER)) return 0;
336
337   string_array dirs;  // culled from the directory listing.
338   {
339     // don't pay for the directory object on the recursive invocation stack;
340     // just have what we need on the stack (the directory list).
341     directory dirndl(source);
342 //check dir for goodness!
343     int ret = add_files_here(dirndl, source, target, manifest_index);
344       // add in just the files that were found.
345     if (ret != 0) {
346       // this is a failure, but the function complains about it already.
347       return 75;
348     }
349     dirs = dirndl.directories();
350   }
351
352 //LOG("now scanning directories...");
353
354   // now scan across the directories we found.
355   for (int i = 0; i < dirs.length(); i++) {
356     astring s = dirs[i];
357 //LOG(astring("curr dir is ") + s);
358     int ret = recurse_into_dir(source + "/" + s, target + "/"
359         + s, manifest_index);
360     if (ret != 0) return ret;  // bail out.
361   }
362
363   return 0;
364 }
365
366 int bundle_creator::patch_recursive_target(const astring &source,
367     const astring &target, int manifest_index)
368 {
369   FUNCDEF("patch_recursive_target");
370 //LOG(astring("patch recurs src=") + source + " targ=" + target);
371   return recurse_into_dir(source, target, manifest_index);
372 }
373
374 int bundle_creator::patch_wildcard_target(const astring &source,
375     const astring &target, int manifest_index)
376 {
377   FUNCDEF("patch_wildcard_target");
378   // find the last slash.  the rest is our wildcard component.
379   int src_end = source.end();
380   int slash_indy = source.find('/', src_end, true);
381   astring real_source = source.substring(0, slash_indy - 1);
382   astring wild_pat = source.substring(slash_indy + 1, src_end);
383 //BASE_LOG(astring("got src=") + real_source + " wildpat=" + wild_pat);
384
385   directory dirndl(real_source, wild_pat.s());
386 //check dir for goodness!
387   int ret = add_files_here(dirndl, real_source, target, manifest_index);
388   if (ret != 0) {
389     // this is a failure, but the function complains about it already.
390     return 75;
391   }
392
393   return 0;
394 }
395
396 int bundle_creator::read_manifest()
397 {
398   FUNCDEF("read_manifest");
399   ini_configurator ini(_manifest_file, configurator::RETURN_ONLY);
400   string_table toc;
401   bool worked = ini.get_section("toc", toc);
402   if (!worked) {
403     LOG(astring("failed to read TOC section in manifest:\n") + _manifest_file
404         + "\ndoes that file exist?");
405     return 65;
406   }
407
408 //hmmm: make a class member.
409   file_logger noisy_logfile(application_configuration::make_logfile_name
410       ("bundle_creator_activity.log"));
411   noisy_logfile.log(astring('-', 76));
412   noisy_logfile.log(astring("Bundling starts at ") + time_stamp::notarize(false));
413
414   // add enough items in the list for our number of sections.
415   _manifest_list.insert(0, toc.symbols());
416   astring value;  // temporary string used below.
417   int final_return = 0;  // if non-zero, an error occurred.
418
419 #define BAIL(retval) \
420   final_return = retval; \
421   toc.zap_index(i); \
422   _manifest_list.zap(i, i); \
423   i--; \
424   continue
425
426   for (int i = 0; i < toc.symbols(); i++) {
427     // read all the info in this section and store it into our list.
428     astring section_name = toc.name(i);
429     section_name.strip_spaces(astring::FROM_FRONT);
430     if (section_name[0] == '#') {
431 //hmmm: this looks a bit familiar from bail macro above.  abstract out?
432       toc.zap_index(i);
433       _manifest_list.zap(i, i);
434       i--;
435       continue;  // skip comments.
436     }
437
438     // check for any keywords on the section.  these are still needed for
439     // variables, which otherwise would skip the rest of the field checks.
440     if (ini.get(section_name, "keyword", value)) {
441 ///LOG(astring("into keyword processing--value held is ") + value);
442       string_array keys;
443       bool worked = list_parsing::parse_csv_line(value, keys);
444       if (!worked) {
445         LOG(astring("failed to parse keywords for section ")
446             + section_name + " in " + _manifest_file);
447         BAIL(82);
448       }
449 ///LOG(astring("parsed list is ") + keys.text_form());
450       _manifest_list[i]._keywords = keys;
451       astring dumped;
452       list_parsing::create_csv_line(_manifest_list[i]._keywords, dumped);
453       noisy_logfile.log(section_name + " keywords: " + dumped);
454     }
455
456     if (ini.get(section_name, "variable", value)) {
457       // this is a variable assignment.  it is the only thing we care about
458       // for this section, so the rest is ignored.
459       variable_tokenizer zohre;
460       zohre.parse(value);
461       if (zohre.symbols() < 1) {
462         LOG(astring("failed to parse a variable statement from ") + value);
463         BAIL(37);
464       }
465       _manifest_list[i]._flags = SET_VARIABLE;  // not orred, just this.
466       // set the two parts of our variable.
467       _manifest_list[i]._payload = zohre.table().name(0);
468       _manifest_list[i]._parms = zohre.table()[0];
469       BASE_LOG(astring("will set ") + _manifest_list[i]._payload + " = "
470           + _manifest_list[i]._parms);
471       astring new_value = parser_bits::substitute_env_vars(_manifest_list[i]._parms);
472       environment::set(_manifest_list[i]._payload, new_value);
473           
474 #ifdef DEBUG_BUNDLER
475       BASE_LOG(astring("** variable ") + _manifest_list[i]._payload + " should have value=" + new_value);
476       BASE_LOG(astring("** variable ") + _manifest_list[i]._payload + " now does have value=" + environment::get(_manifest_list[i]._payload));
477 #endif
478
479       continue;
480     } else if (ini.get(section_name, "assert_defined", value)) {
481       // they are just asking for a variable test, to see if a variable
482       // that the installer needs is actually defined at unpacking time.
483       _manifest_list[i]._payload = value;
484       _manifest_list[i]._flags = TEST_VARIABLE_DEFINED;
485       BASE_LOG(astring("will test ") + _manifest_list[i]._payload + " is "
486           + "defined at unpacking time.");
487       continue;
488     }
489
490     if (!ini.get(section_name, "source", _manifest_list[i]._source)) {
491       // check whether they told us not to pack and it's executable.
492       bool okay_to_omit_source = false;
493       astring value2;
494       if (ini.get(section_name, "no_pack", value)
495           && ini.get(section_name, "exec_target", value2) ) {
496         if (true_value(value) && true_value(value2)) {
497           // this type of section doesn't need source declared.
498           okay_to_omit_source = true;
499         }
500       }
501       if (!okay_to_omit_source) {
502         LOG(astring("failed to read the source entry for section ")
503             + section_name + " in " + _manifest_file);
504         BAIL(67);
505       }
506     }
507     // fix meshugener backslashes so we can count on the slash direction.
508     _manifest_list[i]._source.replace_all('\\', '/');
509
510     if (!ini.get(section_name, "target", _manifest_list[i]._payload)) {
511       // check whether they told us not to pack and it's executable.
512       bool okay_to_omit_target = false;
513       astring value2;
514       if (ini.get(section_name, "no_pack", value)
515           && ini.get(section_name, "exec_source", value2) ) {
516         if (true_value(value) && true_value(value2)) {
517           // this type of section doesn't need target declared.
518           okay_to_omit_target = true;
519         }
520       }
521       if (!okay_to_omit_target) {
522         LOG(astring("failed to read the target entry for section ")
523             + section_name + " in " + _manifest_file);
524         BAIL(68);
525       }
526     }
527     // fix backslashes in target also.
528     _manifest_list[i]._payload.replace_all('\\', '/');
529
530     // capture any parameters they have specified for exec or other options.
531     if (ini.get(section_name, "parms", value)) {
532       _manifest_list[i]._parms = value;
533 #ifdef DEBUG_BUNDLER
534       BASE_LOG(astring("got parms for ") + section_name + " as: " + value);
535 #endif
536       if (value[0] != '"') {
537         // repair the string if we're running on windows.
538         _manifest_list[i]._parms = astring("\"") + value + "\"";
539       }
540       noisy_logfile.log(section_name + " parms: " + _manifest_list[i]._parms);
541     }
542
543     // check for the ignore errors flag.
544     if (ini.get(section_name, "error_okay", value)) {
545       if (true_value(value))
546         _manifest_list[i]._flags |= IGNORE_ERRORS;
547     }
548
549     // see if they are saying not to overwrite the target file.
550     if (ini.get(section_name, "no_replace", value)) {
551       if (true_value(value))
552         _manifest_list[i]._flags |= NO_OVERWRITE;
553     }
554
555     // test whether they are saying not to complain about a failure with
556     // our normal pop-up dialog (on winders).
557     if (ini.get(section_name, "quiet", value)) {
558       if (true_value(value))
559         _manifest_list[i]._flags |= QUIET_FAILURE;
560     }
561
562     // did they want a backup of the original to be made, instead of
563     // just overwriting the file?
564     if (ini.get(section_name, "make_backup", value)) {
565       if (true_value(value))
566         _manifest_list[i]._flags |= MAKE_BACKUP_FILE;
567     }
568
569     // look for our recursion flag.
570     if (ini.get(section_name, "recurse", value)) {
571       if (true_value(value))
572         _manifest_list[i]._flags |= RECURSIVE_SRC;
573     } else {
574       // the options here are only appropriate when the target is NOT set to
575       // be recursive.
576
577       if (ini.get(section_name, "no_pack", value)) {
578         // allow either side to not be required if this is an executable.
579         if (true_value(value))
580           _manifest_list[i]._flags |= OMIT_PACKING;
581       }
582
583       // check if they have specified a source side executable.
584       if (ini.get(section_name, "exec_source", value)) {
585         if (true_value(value)) {
586           _manifest_list[i]._flags |= SOURCE_EXECUTE;
587         }
588       } else {
589         // check if they have specified a target side executable.  this is
590         // mutually exclusive with a source side exec.
591         if (ini.get(section_name, "exec_target", value)) {
592           if (true_value(value))
593             _manifest_list[i]._flags |= TARGET_EXECUTE;
594         }
595       }
596     }
597
598     // replace environment variables in the source now...
599     _manifest_list[i]._source = parser_bits::substitute_env_vars
600         (_manifest_list[i]._source, false);
601
602     // look for wildcards in the source.
603     int indy = _manifest_list[i]._source.find("*");
604
605     // see if they specified a keyword on the command line and if this matches.
606     // if not we need to abandon this item.
607     if (!!_keyword && !_manifest_list[i]._keywords.member(_keyword)) {
608       // their keyword choice didn't match what we were told to use.
609       noisy_logfile.log(astring("skipping ") + _manifest_list[i]._payload
610           + " file check; doesn't match keyword \"" + _keyword + "\"");
611       continue;
612     }
613
614     // we only access the source file here if it's finalized.  we can't do
615     // this if the target is supposed to be recursive or if it's got a wildcard
616     // pattern in it.
617     if (!(_manifest_list[i]._flags & RECURSIVE_SRC) && negative(indy)
618         && !(_manifest_list[i]._flags & OMIT_PACKING) ) {
619       // access the source file to get its size.
620       byte_filer source_file(_manifest_list[i]._source, "rb");
621       if (!source_file.good()) {
622         LOG(astring("could not access the source file for bundling: ")
623             + _manifest_list[i]._source);
624         BAIL(69);
625       }
626       bool okaysize = get_file_size(_manifest_list[i]._source,
627           _manifest_list[i]._size, _manifest_list[i].c_filetime);
628       if (!okaysize || (_manifest_list[i]._size < 0) ) {
629         // this is a failure, but the function complains about it already.
630         BAIL(75);
631       }
632     }
633   }
634
635   // patch the manifest list for wildcards and recursive sources.
636   for (int i = 0; i < _manifest_list.length(); i++) {
637     bundled_chunk curr = _manifest_list[i];
638
639     if (!!_keyword && !curr._keywords.member(_keyword)) {
640       // this item's keyword doesn't match the one we were given, so skip it.
641       noisy_logfile.log(astring("zapping entry for ") + curr._payload
642           + "; doesn't match keyword \"" + _keyword + "\"");
643       _manifest_list.zap(i, i);
644       i--;  // skip back since we eliminated an index.
645       continue;
646     }
647
648     if (curr._flags & SET_VARIABLE) {
649       // we're done working on this.
650       continue;
651     } else if (curr._flags & TEST_VARIABLE_DEFINED) {
652       // this also requires no further effort.
653       continue;
654     } else if (curr._flags & RECURSIVE_SRC) {
655       // handle a recursive style target.
656       int star_indy = curr._source.find("*");
657       if (non_negative(star_indy)) {
658         // this is currently illegal.  we don't allow recursion + wildcards.
659         LOG(astring("illegal combination of recursion and wildcard: ")
660             + curr._source);
661         BAIL(70);
662       }
663       // handle the recursive guy.
664       int ret = patch_recursive_target(curr._source, curr._payload, i);
665       if (ret != 0) {
666         LOG(astring("failed during packing of recursive source: ")
667             + curr._source);
668         BAIL(72);
669       }
670       // take this item out of the picture, since all contents got included.
671       _manifest_list.zap(i, i);
672       i--;  // skip back since we eliminated an index.
673       continue;
674     } else if (curr._flags & SOURCE_EXECUTE) {
675       // we have massaged the current manifest chunk as much as we can, so now
676       // we will execute the source item if that was specified.
677       BASE_LOG(astring("launching ") + curr._source);
678       if (!!curr._parms) {
679         curr._parms = parser_bits::substitute_env_vars(curr._parms, false);
680         BASE_LOG(astring("\tparameters ") + curr._parms);
681       }
682       BASE_LOG(astring('-', 76));
683       basis::un_int kid;
684       basis::un_int retval = launch_process::run(curr._source, curr._parms,
685           launch_process::AWAIT_APP_EXIT, kid);
686       if (retval != 0) {
687         LOG(astring("failed to launch process, source=") + curr._source
688             + ", with parms " + curr._parms);
689         if (! (curr._flags & IGNORE_ERRORS) ) {
690           BAIL(92);
691         }
692       }
693       BASE_LOG(astring('-', 76));
694       if (curr._flags & OMIT_PACKING) {
695         // this one shouldn't be included in the package.
696         _manifest_list.zap(i, i);
697         i--;  // skip back since we eliminated an index.
698       }
699       continue;
700     } else {
701       // check for a wildcard.
702       int star_indy = curr._source.find("*");
703       if (negative(star_indy)) continue;  // simple targets are boring.
704       // this does have a wildcard in it.  let's make sure it's in the right
705       // place for a wildcard in our scheme.
706       int slash_indy = curr._source.find('/', curr._source.end(), true);
707       if (star_indy < slash_indy) {
708         BASE_LOG(astring("illegal wildcard placement in ") + curr._source);
709         BASE_LOG(astring("  (the wildcard must be in the last component of the path)"));
710         BAIL(71);
711       }
712       // handle the wildcarded source.
713       int ret = patch_wildcard_target(curr._source, curr._payload, i);
714       if (ret != 0) {
715         LOG(astring("failed during packing of wildcarded source: ")
716             + curr._source);
717         BAIL(73);
718       }
719       _manifest_list.zap(i, i);
720       i--;  // skip back since we eliminated an index.
721       continue;
722     }
723   }
724
725 #ifdef DEBUG_BUNDLER
726   if (!final_return) {
727     // we had a successful run so we can print this stuff out.
728     LOG("read the following info from manifest:");
729     for (int i = 0; i < _manifest_list.length(); i++) {
730       bundled_chunk &curr = _manifest_list[i];
731       BASE_LOG(a_sprintf("(%d) size %d, %s => %s", i, curr._size,
732           curr._source.s(), curr._payload.s()));
733     }
734   }
735 #endif
736
737   return final_return;
738 }
739
740 astring bundle_creator::determine_stub_file_and_validate()
741 {
742   FUNCDEF("determine_stub_file_and_validate");
743   // define our location to find the unpacking stub program.
744 //hmmm: make this a command line parameter.
745 #ifdef __UNIX__
746   astring stub_filename("unpacker_stub");
747 #endif
748 #ifdef __WIN32__
749   astring stub_filename("unpacker_stub.exe");
750 #endif
751   astring repo_dir = "$RUNTIME_PATH";
752   astring stub_file = parser_bits::substitute_env_vars
753       (repo_dir + "/binaries/" + stub_filename, false);
754   if (!filename(stub_file).exists()) {
755     // we needed to find that to build the bundle.
756     LOG(astring("could not find unpacking stub file at: ") + stub_file);
757     return astring::empty_string();
758   }
759   return stub_file;
760 }
761
762 int bundle_creator::write_stub_and_toc()
763 {
764   FUNCDEF("write_stub_and_toc");
765
766   astring stub_file = determine_stub_file_and_validate();
767   if (!stub_file) return 1;
768  
769   // make sure the stub is accessible.
770   byte_filer stubby(stub_file, "rb");
771   if (!stubby.good()) {
772     FAIL_RETURN(80, astring("could not read the unpacking stub at: ") + stub_file);
773   }
774   _stub_size = int(stubby.length());  // get the stub size for later reference.
775   byte_array whole_stub;
776   stubby.read(whole_stub, _stub_size + 100);
777   stubby.close();
778   _bundle->write(whole_stub);
779
780   byte_array packed_toc_len;
781   structures::obscure_attach(packed_toc_len, _manifest_list.length());
782   int ret = _bundle->write(packed_toc_len);
783   if (ret < 0) {
784     LOG(astring("could not write the TOC length to the bundle: ")
785         + _output_file);
786     return 81;
787   }
788
789   // dump out the manifest list in our defined format.
790   for (int i = 0; i < _manifest_list.length(); i++) {
791     bundled_chunk &curr = _manifest_list[i];
792 //LOG(a_sprintf("flag %d is %d", i, curr._flags));
793     byte_array chunk;
794     curr.pack(chunk);
795     if (_bundle->write(chunk) <= 0) {
796       LOG(a_sprintf("could not write item #%d [%s] to the bundle: ", i,
797           curr._source.s())
798           + _output_file);
799       return 88;
800     }
801   }
802
803   return 0;
804 }
805
806 int bundle_creator::bundle_sources()
807 {
808   FUNCDEF("bundle_sources");
809   // go through all the source files and append them to the bundled output.
810   file_logger noisy_logfile(application_configuration::make_logfile_name
811       ("bundle_creator_activity.log"));
812   for (int i = 0; i < _manifest_list.length(); i++) {
813     bundled_chunk &curr = _manifest_list[i];
814
815     if (curr._flags & SET_VARIABLE) {
816       // all we need to do is keep this in the manifest.
817       noisy_logfile.log(astring("bundling: variable setting ") + curr._payload
818           + "=" + curr._parms);
819       continue;
820     } else if (curr._flags & TEST_VARIABLE_DEFINED) {
821       // just remember to test this when running the unpack.
822       noisy_logfile.log(astring("bundling: test variable ") + curr._payload
823           + " is defined.");
824       continue;
825     } else if (curr._flags & OMIT_PACKING) {
826       // this one shouldn't be included in the package.
827       continue;
828     }
829
830     noisy_logfile.log(astring("bundling: ") + curr._source);
831     byte_filer source(curr._source, "rb");
832     if (!source.good()) {
833       LOG(a_sprintf("could not read item #%d for the bundle: \"", i)
834           + curr._source + "\"");
835       return 98;
836     }
837
838     byte_array compressed(256 * KILOBYTE);  // expand the buffer to start with.
839     byte_array temp;  // temporary read buffer.
840
841     // chew on the file a chunk at a time.  this allows us to easily handle
842     // arbitrarily large files rather than reading their entirety into memory.
843     int total_written = 0;
844     do {
845       int ret = source.read(temp, CHUNKING_SIZE);
846       if (ret < 0) {
847         LOG(a_sprintf("failed while reading item #%d: ", i) + curr._source);
848         return 99;
849       } 
850       total_written += ret;  // add in what we expect to write.
851       // skip compressing if there's no data.
852       uLongf destlen = 0;
853       bool null_chunk = false;
854       if (ret == 0) {
855         compressed.reset();
856         null_chunk = true;
857       } else {
858         compressed.reset(int(0.1 * ret) + ret + KILOBYTE);
859           // provide some extra space as per zlib instructions.  we're giving it
860           // way more than they request.
861         destlen = compressed.length();
862         // pack the chunks first so we can know sizes needed.
863         int comp_ret = compress(compressed.access(), &destlen, temp.observe(),
864             temp.length());
865         if (comp_ret != Z_OK) {
866           LOG(a_sprintf("failed while compressing item #%d: ", i)
867               + curr._source);
868           return 99;
869         }
870         compressed.zap(destlen, compressed.length() - 1);
871       }
872       byte_array just_sizes;
873       structures::obscure_attach(just_sizes, temp.length());
874         // add in the real size.
875       structures::obscure_attach(just_sizes, int(destlen));
876         // add in the packed size.
877       ret = _bundle->write(just_sizes);
878       if (ret <= 0) {
879         LOG(a_sprintf("failed while writing sizes for item #%d: ", i)
880             + curr._source);
881         return 93;
882       }
883       if (!null_chunk) {
884         ret = _bundle->write(compressed);
885         if (ret <= 0) {
886           LOG(a_sprintf("failed while writing item #%d: ", i) + curr._source);
887           return 93;
888         } else if (ret != compressed.length()) {
889           LOG(a_sprintf("wrote different size for item #%d (tried %d, "
890               "wrote %d): ", i, compressed.length(), ret) + curr._source);
891           return 93;
892         }
893       }
894     } while (!source.eof());
895 //hmmm: very common code to above size writing.
896     byte_array just_sizes;
897     structures::obscure_attach(just_sizes, -1);
898     structures::obscure_attach(just_sizes, -1);
899     int ret = _bundle->write(just_sizes);
900     if (ret <= 0) {
901       LOG(a_sprintf("failed while writing sentinel of item #%d: ", i)
902           + curr._source);
903       return 96;
904     }
905     source.close();
906     if (total_written != curr._size) {
907       LOG(a_sprintf("size (%d) disagrees with initial size (%d) for "
908           "item #%d: ", total_written, curr._size, i) + curr._source);
909     }
910   }
911   noisy_logfile.log(astring("Bundling run ends at ") + time_stamp::notarize(false));
912   noisy_logfile.log(astring('-', 76));
913
914   return 0;
915 }
916
917 int bundle_creator::finalize_file()
918 {
919   _bundle->close();
920   return 0;
921 }
922
923 int bundle_creator::write_offset()
924 {
925   FUNCDEF("write_offset");
926   byte_filer bun(_output_file, "r+b");  // open the file for updating.
927
928   astring magic_string("muftiloc");  // our sentinel string.
929   astring temp_string;  // data from the file.
930
931   while (!bun.eof()) {
932     // find the telltale text in the file.
933     bool found_it = false;  // we'll set this to true if we see the string.
934     int location = 0;  // where the sentinel's end is.
935     for (int i = 0; i < magic_string.length(); i++) {
936       int ret = bun.read(temp_string, 1);
937       if (ret <= 0) break;
938       if (temp_string[0] != magic_string[i]) break;  // no match.
939       if (i == magic_string.end()) {
940         // we found a match to our string!
941         found_it = true;
942         location = int(bun.tell());
943 //LOG(a_sprintf("found the sentinel in the file!  posn=%d", location));
944       }
945     }
946     if (!found_it) continue;  // keep reading.
947     bun.seek(location);
948     byte_array packed_offset;
949     structures::obscure_attach(packed_offset, _stub_size);
950 //LOG(astring("pattern of len is:\n") + byte_format::text_dump(packed_offset));
951     // write the offset into the current position, which should be just after
952     // the sentinel's location.
953     bun.write(packed_offset);
954 //LOG(a_sprintf("wrote manifest offset before posn=%d", bun.tell()));
955     break;  // done with looking for that pattern.
956   }
957   bun.close();  // completely finished now.
958
959   chmod(_output_file.s(), 0766);
960     // make sure it's an executable file when we're done with it.
961
962   BASE_LOG(astring("done file bundling at ") + time_stamp::notarize(false));
963
964   return 0;
965 }
966
967 ////////////////////////////////////////////////////////////////////////////
968
969 HOOPLE_MAIN(bundle_creator, )
970
971 #ifdef __BUILD_STATIC_APPLICATION__
972   // static dependencies found by buildor_gen_deps.sh:
973   #include <application/application_shell.cpp>
974   #include <application/command_line.cpp>
975   #include <basis/astring.cpp>
976   #include <basis/common_outcomes.cpp>
977   #include <basis/environment.cpp>
978   #include <basis/mutex.cpp>
979   #include <basis/utf_conversion.cpp>
980   #include <configuration/application_configuration.cpp>
981   #include <configuration/configurator.cpp>
982   #include <configuration/ini_configurator.cpp>
983   #include <configuration/ini_parser.cpp>
984   #include <configuration/table_configurator.cpp>
985   #include <configuration/variable_tokenizer.cpp>
986   #include <filesystem/byte_filer.cpp>
987   #include <filesystem/directory.cpp>
988   #include <filesystem/filename.cpp>
989   #include <filesystem/file_time.cpp>
990   #include <loggers/combo_logger.cpp>
991   #include <loggers/console_logger.cpp>
992   #include <loggers/critical_events.cpp>
993   #include <loggers/file_logger.cpp>
994   #include <loggers/program_wide_logger.cpp>
995   #include <processes/launch_process.cpp>
996   #include <structures/bit_vector.cpp>
997   #include <structures/checksums.cpp>
998   #include <structures/object_packers.cpp>
999   #include <structures/static_memory_gremlin.cpp>
1000   #include <structures/string_hasher.cpp>
1001   #include <structures/string_table.cpp>
1002   #include <structures/version_record.cpp>
1003   #include <textual/byte_formatter.cpp>
1004   #include <textual/list_parsing.cpp>
1005   #include <textual/parser_bits.cpp>
1006   #include <textual/string_manipulation.cpp>
1007   #include <timely/earth_time.cpp>
1008   #include <timely/time_control.cpp>
1009   #include <timely/time_stamp.cpp>
1010 #endif // __BUILD_STATIC_APPLICATION__
1011