src/strip.vala
[app.mailtrimmer] / src / strip.vala
1 /**
2
3  ** check left to do:  
4   - range scans on maildir
5   - see how replacing the links works in the resulting email via thunderbird etc..
6   - some checksum issues (see dupelicates?? suspect 0byte issues?)  -- seems ok now?
7  
8
9
10
11   needs to scan 2 things
12   a) our mailfort email database
13        point it at the top directory, containing YEAR/MONTH/DAY.... directories.
14        scan each file (over a year old...)
15        extract out the attachment, and replace with HTML
16        DATABASE? - mysql or sqlite? - 
17            filesize / name / date / checksum / mimetype -- into mailfort should be OK.
18   b) the imap user emails
19            loop through user's directories
20            check age of email .. over 1 years..
21            ?? how to prevent 'repeat' scanning of emails?
22               ??? hidden '.' files containing last scan date?
23
24            check if file exists in our DB.. - replace the link...
25            otherwise generate a file. + add to DB...
26            
27    c) retreival system
28      -> URL -> get file
29    d) redirect system.
30      -> URL -> redirect to correct server
31
32
33 More notes on our Mailfort DB sync:
34 * some of these attachments are already in the database...
35  - so we need to update the DB..
36  - probably worth putting the code in a stored procedure..
37  
38  -- key scenarios
39    * first scan (and extract)
40    * rescan (as I messed up the first time - fix the DB...)
41    * email scan - attachments might not have related messages.
42  
43  
44  - {id} attachment_init(
45                 {exim_msg_id}
46                 {chksum}
47                 {filename),
48         )
49         // creates or returns id (can look for existing messages?
50         // can do a merge?? - copy 'old' record data into 'new'....  "prefer checksummed"
51         
52         attachment_update(
53                 {id}
54                 {exim_msg_id}
55                 {mailfort_msg_sig}
56                 {file_size}
57                 {created} // message date..
58                 {chksum}
59                 {filename),
60         {mime_type}
61         )
62         attachment_update_store(
63                         {id}
64                         {stored_filename}
65         )
66
67
68 */ 
69
70 // valac --pkg gmime --vapi
71 /*
72
73 // http://www.fromdual.com/mysql-vala-program-example << check mysql if this does not work.
74
75  valac  -g --vapidir=. --thread  strip.vala   --vapidir=../vapi \
76      --pkg glib-2.0 --pkg mysql --pkg gio-2.0 --pkg posix --pkg gmime-2.6 \
77       --Xcc=-lmysqlclient  -v \
78        -o /tmp/strip
79 */ 
80  
81 public class StripApplication : GLib.Application {
82
83         public static string? opt_path = null;
84         public static string? opt_file = null;  
85         public static string? opt_target_path = null;
86         public static string? opt_db_host = "127.0.0.1";
87         public static string? opt_db_name = null;       
88         public static string? opt_db_user = null;               
89         public static string? opt_db_pass = null;               
90
91         public static int    opt_limit = -1;
92
93         public static int    opt_age_newest = 1;
94         public static int    opt_age_oldest = 6;
95
96
97         public static bool      opt_is_extracting = false;
98         public static bool      opt_is_replacing = false;
99         public static bool      opt_scan_maildir  = false; 
100         public static bool      opt_scan_mailfort  = false;     
101         public static bool              opt_dump = false;       
102         public static bool              opt_debug = false; 
103         
104         public static bool opt_debug_sql = false;       
105         public static string? opt_replace_link = null;
106         
107         
108         public const GLib.OptionEntry[] options = {
109                 
110                 { "debug", 0, 0, OptionArg.NONE, ref opt_debug, "show debug messages for components", null },
111                 { "debug-sql", 0, 0, OptionArg.NONE, ref opt_debug_sql, "debug the SQL statements", null },         
112
113                 { "path", 0, 0, OptionArg.STRING, ref opt_path, "Directory where email to be parsed is", null },        
114                 { "file", 0, 0, OptionArg.STRING, ref opt_file, "A specific file to be parsed", null }, 
115
116                 { "target-path", 0, 0, OptionArg.STRING, ref opt_target_path, "Directory where attachments are to be put", null },
117
118                 { "link", 0, 0, OptionArg.STRING, ref opt_replace_link, "url for the replement link: eg. http://www.mysite.com/xxxx/%s", null },         
119                         
120                 { "host", 0, 0, OptionArg.STRING, ref opt_db_host, "Mysql host (default localhost)", null },    
121                 { "name", 0, 0, OptionArg.STRING, ref opt_db_name, "Mysql database name REQUIRED", null },      
122                 { "user", 0, 0, OptionArg.STRING, ref opt_db_user, "Mysql database user REQUIRED", null },      
123                 { "pass", 0, 0, OptionArg.STRING, ref opt_db_pass, "Mysql database password (default empty)", null },            
124
125                 { "extract", 0, 0, OptionArg.NONE, ref opt_is_extracting, "Should attachments be extracted (default NO)", null },
126                 { "replace", 0, 0, OptionArg.NONE, ref opt_is_replacing, "Should attachments be replaced (default NO)", null },
127                 { "dump", 0, 0, OptionArg.NONE, ref opt_dump, "Print the replaced mail contents to stdout", null },         
128
129                 { "limit", 0, 0, OptionArg.INT, ref opt_limit, "stop after X number of messages with attachments have been processed", null },         
130                 { "newest", 0, 0, OptionArg.INT, ref opt_age_newest, "do not replace messages newer that X months (default is 1 months)", null },
131                 { "oldest", 0, 0, OptionArg.INT, ref opt_age_oldest, "do not replace messages older than X (default is 6 months)", null },
132
133                 { "scan-maildir", 0, 0, OptionArg.NONE, ref opt_scan_maildir, "scan an maildir tree", null },
134                 { "scan-mailfort", 0, 0, OptionArg.NONE, ref opt_scan_mailfort, "scan a mailfort tree", null },  
135                 { null }       
136         };         
137     public StripApplication( string[] args ) 
138     {
139                  Object(
140             application_id: "org.roojs.mailstripper",
141             flags: ApplicationFlags.FLAGS_NONE
142          );
143  
144                         
145          var opt_context =  new GLib.OptionContext ("Mail Stripper");
146                         
147          try {
148                                 
149             opt_context.set_help_enabled (true);
150             opt_context.add_main_entries (options, null);
151             opt_context.parse ( ref  args);
152             //opt_detach = !optx_no_detach;
153                             
154  
155                             
156              // options that have to be set.. bee or hive... (or stop all)
157             if ((!opt_scan_mailfort && !opt_scan_maildir) || (opt_scan_mailfort && opt_scan_maildir))  {
158                stdout.printf ("You must specify the type of directory tree to scan - either imap or mailfort\n%s",
159                    opt_context.get_help(true, null));
160                GLib.Process.exit(Posix.EXIT_FAILURE);
161             }
162                         
163                          if ((opt_db_name == null || opt_db_name.length < 1 || opt_db_user == null || opt_db_user.length < 1))  {
164                stdout.printf ("You must specify the database name / user \n%s",
165                    opt_context.get_help(true, null));
166                GLib.Process.exit(Posix.EXIT_FAILURE);
167             }
168                          if ((opt_path == null || opt_path.length < 1)   )  {
169                stdout.printf ("You must specify the scan start path\n%s",
170                    opt_context.get_help(true, null));
171                GLib.Process.exit(Posix.EXIT_FAILURE);
172             }
173                         if (opt_replace_link == null || (opt_replace_link.length < 1))  {
174                stdout.printf ("You must specify the link to use in the replacement \n%s",
175                    opt_context.get_help(true, null));
176                GLib.Process.exit(Posix.EXIT_FAILURE);
177             }
178             if ((opt_is_replacing || opt_is_extracting ) && (opt_target_path == null || opt_target_path.length < 1)) {
179                       stdout.printf ("You must specify a target path to put attachments\n%s",
180                    opt_context.get_help(true, null));
181                GLib.Process.exit(Posix.EXIT_FAILURE);
182             }
183             
184             
185          } catch (GLib.OptionError e) {
186             stdout.printf ("error: %s\n", e.message);
187             stdout.printf ("Run '%s --help' to see a full list of available command line options.\n%s", 
188                       args[0], opt_context.get_help(true, null));
189             GLib.Process.exit(Posix.EXIT_FAILURE);
190          }
191         }
192          
193     public static int main(string[] args) 
194     {
195                 
196                 var application = new StripApplication(  args);
197                 
198                 GLib.Log.set_always_fatal(LogLevelFlags.LEVEL_ERROR | LogLevelFlags.LEVEL_CRITICAL); 
199            
200            if (opt_debug || opt_debug_sql) {
201                         GLib.Log.set_handler(null, 
202                         GLib.LogLevelFlags.LEVEL_DEBUG | GLib.LogLevelFlags.LEVEL_WARNING | GLib.LogLevelFlags.LEVEL_INFO, 
203                         (dom, lvl, msg) => {
204                                         print("%s\n", msg);
205                                 }
206                         );
207                 }
208         
209         GMime.init(0);
210                 if (StripApplication.opt_is_replacing) {
211                         StripApplication.opt_is_extracting = true;
212                 }
213   
214                 GLib.debug("scanning folder: %s", opt_path );
215                 
216                 var strip = new Strip( opt_path );
217  
218                 
219                 strip.mysql  = new Mysql.Database();
220                 if (!strip.mysql.real_connect(
221                                 opt_db_host,
222                                 opt_db_user ,
223                                 opt_db_pass == null ? "" : opt_db_pass, //passwd
224                                 opt_db_name, //DB
225                                 3306, // not changable...?
226                                 null
227                         )
228                 ) {
229                         stdout.printf("ERROR %u: Connection failed: %s\n", 
230                                 strip.mysql.errno(), strip.mysql.error()
231                         );
232
233                         return 1;
234                 }
235         if (opt_file != null) {
236                 strip.base_dir = opt_path;
237                 strip.scan_file( GLib.Path.get_dirname(opt_file),  GLib.Path.get_basename(opt_file));
238                 return 0;
239         }
240
241                 strip.scan_dir(opt_path, "");
242         
243
244         
245         return 0;
246     }
247 }
248
249 public class Strip : GLib.Object {
250         
251  
252         
253         public string base_dir = "";
254         
255         public Mysql.Database mysql;
256         
257         int processed = 0;
258     
259     uint64 used_space_before = 0;
260     uint64 used_space_after = 0;
261     
262     
263     public Strip(string base_dir)
264     {
265         this.base_dir = base_dir;
266     }
267     
268     public void handle_part(GMime.Object parent, GMime.Object mime_obj)
269     {
270                 if (mime_obj is GMime.Part) {
271                    var  p = (GMime.Part)mime_obj;
272                         var ct = p.get_content_type();
273                         var cd = p.get_content_disposition();
274                         
275                         var sid = p.get_header("X-strip-id");
276                     if (sid != null && sid.length > 0) {
277                         this.update_attachment_db(p);
278                             GLib.debug("Skip attachment replace - it's already been done");
279                         return;
280                         }
281                         
282                         if (cd == null || cd.get_disposition().down() != "attachment") {
283                                 return;
284                         }
285                         if (ct.get_media_type() == "text") {
286                                 return;
287                         }
288                         if (ct.to_string() == "application/pgp-encrypted") {
289                                 return;
290                         }
291                         if (ct.to_string() == "application/pgp-keys") {
292                                 return;
293                         }
294                         if (p.get_filename() == null) {
295                                 return;
296                         }
297                          // print("got part %s\n", ct.to_string());
298                          if (parent is GMime.Multipart) {
299                                 
300                                 this.replace_attachment(((GMime.Multipart)parent), p);
301                                 // remove it !?
302
303                           }
304
305
306                         return;
307                 }
308                 if (mime_obj is GMime.Multipart) {
309                         
310
311                         var  mp = (GMime.Multipart)mime_obj;
312                         //var ct = mp.get_content_type();
313
314                         //print("got multi-part %s\n", ct.to_string());
315                         for (var i = 0; i< mp.get_count(); i++) { 
316                           var mo = mp.get_part(i);
317                           this.handle_part(mime_obj,mo);
318                         }
319                    // ((GMime.Multipart)mime_obj).foreach((sub_obj) => {
320                    //     Strip.handle_part(sub_obj);
321                 //
322                    // });
323
324
325                         return;
326                 }
327
328                 if (mime_obj is GMime.MessagePart) {
329                         var msg = ((GMime.MessagePart)mime_obj).get_message();
330                         msg.foreach((subobj) => {
331                          this.handle_part(msg,subobj);
332                     });
333                 
334                         //print("got message-part\n");
335                         return;
336                 }
337                 
338                 if (mime_obj is GMime.Message) {
339                         var mp = ((GMime.Message) mime_obj).get_mime_part();
340
341                         if (!(mp is GMime.Multipart)) {
342                                 //GLib.debug("get mimepart does not return a Multipart?");
343                                 return;
344                         }
345                         
346                         var mpc = ((GMime.Multipart)mp).get_count();
347                         
348                         //GLib.debug("Message has %d parts", mpc); 
349                         for (var i =0 ; i < mpc; i++) {
350                                 //GLib.debug("Getting part %d", i); 
351                                 var submime_obj = ((GMime.Multipart)mp).get_part(i);
352                         this.handle_part(mp,submime_obj);                       
353                     }
354                         print("got message??\n");
355                         return;
356                 }
357                 
358                 print("got something else\n");
359
360
361     }
362     public void update_attachment_db(GMime.Part attachment)
363     {
364         // only called when we have an sid...
365         var sid = attachment.get_header("X-strip-id");
366         if (sid == null || sid.length < 1) {
367                 GLib.debug("Strange - update attachment db called ?");
368                 return;
369         }
370         
371         // initialize it with known data..
372         // that should wipe out dupes.
373         var matches = this.execute("SELECT count(id) as nid FROM Attachment WHERE id = %d".printf(
374                         int.parse(sid)));  
375
376                  
377                 if (matches == "") {     
378                         // our old mailfort code deleted the crap out of old records...
379                         // if this occurs we will need to create the record again..
380                         this.fix_deleted_attachment_db(int.parse(sid),attachment);
381                         return;
382  
383                 }
384         
385         
386         // initialize it with known data..
387         // that should wipe out dupes.
388         var filesize = this.execute("SELECT filesize FROM Attachment WHERE id = %d".printf(
389                         int.parse(sid)));  
390
391                 if (filesize=="") {      
392                    GLib.error("Ignoring record id (missing in database) :%s", sid);
393                    return;
394                 }
395                 if (int.parse(filesize) < 1) {
396                 GLib.debug("Could not get filesize from id :%s = %s", sid,filesize);
397                 Posix.exit(0);
398                 return;
399         }
400         
401         var chksum = this.query("SELECT  checksum FROM Attachment WHERE id = %d".printf(
402                         int.parse(sid)
403                 ));
404         var mime_filename = this.query("SELECT  mime_filename FROM Attachment WHERE id = %d".printf(
405                         int.parse(sid)));       
406                 
407         this.query("""
408              SELECT 
409                  attachment_init(
410                      '%s', '%s', '%s', %d
411                  ) as id 
412                  
413           """.printf(
414                           this.mysql_escape(this.active_message_exim_id),
415                           this.mysql_escape(chksum),
416                           this.mysql_escape(mime_filename),                       
417                           int.parse(filesize)
418                 ));
419         this.query("""
420                  SELECT attachment_update(
421                       %d, -- in_id INT(11),
422                       '%s', -- in_mime_type varchar(255),
423                       '%s', -- in_created DATETIME,
424                       '%s' -- in_mailfort_sig varchar(64)
425                  )
426               """.printf(
427                         int.parse(sid),
428                         "", // this will be ignored..
429                                 this.created_date,
430                                 this.mysql_escape(this.active_message_x_mailfort_sig)
431               
432               )
433                 );
434                 this.mysql.store_result();
435                 
436
437     
438     }
439     
440     
441     public void fix_deleted_attachment_db(int id, GMime.Part attachment)
442     {
443                 
444         var filename = attachment.get_header("X-strip-content-name");
445         var file_path  = attachment.get_header("X-strip-path");
446         var fn =  StripApplication.opt_target_path + "/" + file_path;
447         var chksum = this.md5_file(fn);
448                 var mime_type = attachment.get_header("X-strip-content-type");
449
450                 var fileinfo = File.new_for_path(fn)
451                                         .query_info(GLib.FileAttribute.STANDARD_SIZE+","+GLib.FileAttribute.TIME_MODIFIED
452                                                 ,GLib.FileQueryInfoFlags.NONE,null);
453         var file_size = (int) fileinfo.get_size();
454
455                 
456
457       
458                 this.query("""
459                        
460                        
461                                 INSERT INTO Attachment  (  
462                                         id, 
463                                         
464                                     msgid ,
465                                     queue_id ,
466                                     mime_filename ,
467                                     mime_type,
468                                      
469                                     stored_filename ,
470                                     mime_charset ,
471                                     mime_cdisp ,
472                                     mime_is_cover ,
473                                     
474                                     mime_is_multi ,
475                                     mime_is_mail,
476                                     mime_size ,
477                                     filesize,
478                                     
479                                     checksum
480
481                                 ) VALUES (
482                                         %d,  -- id
483                                         
484                                     '%s' , -- msgid
485                                     0,
486                                     '%s'  , -- filename
487                                     '%s',  -- mimetype
488                                     
489                                     '%s', -- stored file anme
490                                     '',
491                                     'attachment',
492                                     0,
493                                     0,
494                                     0,
495                                     %d, -- size
496                                     %d, -- size
497                                     '%s' -- checkum
498
499                                 )"
500                        
501                        
502                       """.printf(
503                                 id,
504                                       this.mysql_escape(this.active_message_exim_id),
505                                       this.mysql_escape(filename),                                                            
506                                   this.mysql_escape(mime_type),                                                       
507                                   this.mysql_escape(file_path),                                                       
508                               file_size
509                       file_size
510                                       this.mysql_escape(chksum),
511
512
513                                       file_size
514                          ));
515                          
516                  this.query("""
517                  SELECT attachment_update(
518                       %d, -- in_id INT(11),
519                       '%s', -- in_mime_type varchar(255),
520                       '%s', -- in_created DATETIME,
521                       '%s' -- in_mailfort_sig varchar(64)
522                  )
523               """.printf(
524                                 id,
525                         "", // this will be ignored..
526                                 this.created_date,
527                                 this.mysql_escape(this.active_message_x_mailfort_sig)
528               
529               )
530                 );
531                  GLib.error("added attachment?");
532     }
533     
534     
535     public void replace_attachment(GMime.Multipart parent, GMime.Part attachment)
536     {
537         var sid = attachment.get_header("X-strip-id");
538         if (sid != null && sid.length > 0) {
539                 GLib.debug("Skip attachment replace - it's already been done");
540                 return;
541         }
542         
543         var c = attachment.get_content_object();
544         
545         var filename = attachment.get_filename().replace("/", "-").replace("\n", "").replace("\t", " ");
546         var fn = GLib.Environment.get_tmp_dir() +
547                         "/"+ this.active_name + "."+   filename;
548
549             var outfile = new GMime.StreamFile.for_path(fn, "w");
550             outfile.set_owner(true);
551             var file_size = (int) c.write_to_stream(outfile);
552             var chksum = this.md5_file(fn);
553             outfile.flush();
554             outfile = null;
555         
556         if (file_size == 0) {
557
558                 GLib.debug("ERROR - file size of write to stream returned 0?");
559                 Posix.unlink(fn);               
560                 return;
561         }
562         
563         
564         
565  
566         var mime_type= attachment.get_content_type().to_string();
567         // at this point we have to do our database magic...
568         //filesize / name / date / checksum / mimetype -- into mailfort should be OK.
569         
570         var file_id = this.query("""
571                 SELECT 
572                 
573                 attachment_init(
574                                 '%s', -- in_msgid VARCHAR(32),
575                                 '%s', -- in_checksum VARCHAR(64),
576                                 '%s', -- in_mime_filename varchar(255)
577                                 %d -- filesize
578                         ) as id 
579                         
580           """.printf(
581                         this.mysql_escape(this.active_message_exim_id),
582                         chksum,
583                         this.mysql_escape( attachment.get_filename() ), // what is thsi is invalid?
584                          file_size)
585                 );
586                  
587                 
588                 if (file_id.length < 1) {
589                         GLib.debug("ERROR - CALL to attachment_init failed");
590                 Posix.unlink(fn);               
591                 return;
592                 
593                 }
594  
595                 if (int.parse(file_id) < 1) {
596                         GLib.debug("ERROR - CALL to attachment_init failed - returned 0?");
597                 Posix.unlink(fn);               
598                 return;
599                 
600                 }
601  
602         
603                 GLib.debug("fn = %s, m5=%s, id= %s", filename, mime_type, this.active_message_id);
604                 this.query("""
605                 
606                         SELECT attachment_update(
607                                 %d, -- in_id INT(11),
608                                 '%s', -- in_mime_type varchar(255),
609                                 '%s', -- in_created DATETIME,
610                                 '%s' -- in_mailfort_sig varchar(64)
611                                 
612                                 ) as result
613       """.printf(
614                 int.parse(file_id),
615                         this.mysql_escape(mime_type),
616                         this.created_date,
617                         this.mysql_escape(this.active_message_x_mailfort_sig)
618                 ));
619                  this.mysql.store_result();
620                                  
621  
622                 this.used_space_after += file_size;
623                         
624                 var target_fn = "";
625
626             if (StripApplication.opt_is_extracting) {
627                         target_fn = StripApplication.opt_target_path + "/" + this.created_dir +"/"+ file_id  + "-" + filename;
628                 } 
629                     
630             var stored =  "/" + this.created_dir +"/"+ file_id  + "-" + filename;
631                  this.query("""
632                 
633                         SELECT attachment_update_store(
634                                 %d, -- in_id INT(11),
635                                 '%s'  -- in_store_filename varchar(255),
636                          
637                                 
638                                 ) as result
639       """.printf(
640                 int.parse(file_id),
641                          this.mysql_escape( stored)
642                 ));   
643                          
644         var rep = new GMime.Part.with_type("text","html");
645         // we have to set up a redirect server - to redirect hpasite... to their internal service..
646         rep.set_filename(filename);
647         string txt = "<html><body>"+
648             "<a href=\"" + StripApplication.opt_replace_link + "/" +
649                         file_id + "/" + this.created_dir + "/"+chksum+"/"+ GLib.Uri.escape_string( filename) +"\">" + 
650             GLib.Uri.escape_string( filename) + // fixme needs html escaping...
651             "</a>" +
652             "</body></html>";
653
654         rep.get_content_type().set_parameter("charset", "utf-8");
655                 rep.set_header("X-strip-id", file_id);
656                 rep.set_header("X-strip-content-name",  filename);                              
657                 rep.set_header("X-strip-path", this.created_dir + "/" + file_id + "-" + filename);              
658                 rep.set_header("X-strip-content-type", mime_type);              
659         var stream =  new GMime.StreamMem.with_buffer(txt.data);
660         var con = new GMime.DataWrapper.with_stream(stream,GMime.ContentEncoding.DEFAULT);
661
662         rep.set_content_object(con);
663         GLib.debug("Replacing Attachment with HTML");
664         parent.replace(parent.index_of(attachment), rep);
665                 this.has_replaced = true;
666                  
667                 if (StripApplication.opt_is_extracting && target_fn.length > 0) {
668                         var dir = GLib.Path.get_dirname(target_fn);
669                         if (!FileUtils.test (dir, FileTest.IS_DIR)) {
670                                 GLib.DirUtils.create_with_parents(dir, 0755);
671                         }
672                         GLib.debug("Creating file %s", target_fn);
673                         if (!FileUtils.test (target_fn, FileTest.EXISTS)) {
674                                 var from = File.new_for_path (fn);
675                                 var to =  File.new_for_path (target_fn);
676                                 from.copy(to, 0, null);
677
678                         }
679                 } else { 
680                         GLib.debug("Skipping extraction %s", target_fn);
681                 }
682                 Posix.unlink(fn);
683                 
684
685
686     }
687     public string query(string str)
688     {
689             return this.real_query(true, str);
690     }
691     public string execute(string str)
692     {
693             return this.real_query(false, str);
694     }
695     public string real_query(bool need_return, string str)
696     {
697                 GLib.debug("Before Query : %u  : %s\n", this.mysql.errno(), this.mysql.error());
698
699
700         if (StripApplication.opt_debug_sql) {
701                 GLib.debug("SQL: %s\n", str);
702                 }
703                 
704                 
705         
706         var rc=  this.mysql.query(str); 
707         if ( rc != 0 ) {
708
709                     GLib.debug("ERROR %u: Query failed: %s\n", this.mysql.errno(), this.mysql.error());
710                                 Posix.exit(1);
711                 }
712                 
713
714         var rs = mysql.use_result();
715         
716         //GLib.debug("got %d rows", (int) rs.num_rows());
717         
718         var got_row = false;
719                 string[] row;
720                 string ret = "";
721                 while( (row = rs.fetch_row()) != null) { 
722                         got_row = true;
723                         ret = row[0];
724                 
725                 }
726                 if (!need_return) {
727                 if (StripApplication.opt_debug_sql) {
728                                 GLib.debug("got %s", got_row ? "=Nothing=" : ret);
729                         }
730                         return got_row ? "" : ret;
731                 }
732                 if (!got_row) {
733
734                          GLib.debug("ERROR : no rows returned");
735                         Posix.exit(1);
736                         return "";
737                 }
738         if (StripApplication.opt_debug_sql) {
739                         GLib.debug("got %s", ret);
740                 }
741                 return ret;
742                 
743                  
744         }
745     
746     public string mysql_escape(string str)
747     {
748             unichar[] value_escaped = new unichar[str.length * 2 + 1];
749                 this.mysql.real_escape_string ((string) value_escaped, str, str.length);
750                 return (string) value_escaped;
751     }
752     
753     public string  md5_file(string fn) {
754               Checksum checksum = new Checksum (ChecksumType.MD5);
755
756               FileStream stream = FileStream.open (fn, "rb");
757               uint8 fbuf[100];
758               size_t size;
759
760               while ((size = stream.read (fbuf)) > 0) {
761                       checksum.update (fbuf, size);
762               }
763
764               unowned string digest = checksum.get_string ();
765               return digest;
766     }
767
768         string active_path = "";    
769     string active_name = "";
770     string active_message_id = "";
771     string active_message_x_mailfort_sig = "";
772     string active_message_exim_id = "";
773     bool has_replaced = false;
774     string created_date = ""; // should be YYYY-mm-dd
775     string created_dir = ""; // should be YYY/mm/dd
776     
777     public void scan_file(string path, string name)
778     {
779                 GLib.debug("Scan: %s/%s", path,name); 
780                 
781                 this.has_replaced = false; 
782         this.active_path = path;
783         this.active_name = name;
784         this.active_message_id = "";
785
786                 var mailtime = new DateTime.now_local();
787                 if (StripApplication.opt_scan_mailfort) {
788                     this.created_dir = this.active_path.substring(this.base_dir.length + 1 );
789                         this.created_date = this.created_dir.replace("/", "-");
790                         var bits = this.created_date.split("-");
791                         mailtime = new DateTime.local(int.parse(bits[0]),int.parse(bits[1]),int.parse(bits[2]),0,0,0);
792                         
793                         var oldest = new  DateTime.now_local();
794                         oldest = oldest.add_months(-1 * StripApplication.opt_age_oldest);
795                         var tspan = mailtime.difference(oldest) / GLib.TimeSpan.DAY;
796
797                         if (tspan < 0) {
798                                 GLib.debug("skip file is %d days older than %d months", (int)tspan, StripApplication.opt_age_oldest);
799                                 return;
800                         }
801                         
802                         var newest = new  DateTime.now_local();
803                         newest = newest.add_months(-1 * StripApplication.opt_age_newest);
804                         tspan = mailtime.difference(newest) / GLib.TimeSpan.DAY;
805                         if (tspan > 0) {
806                                 GLib.debug("skip file is %d days newer than %d months", (int)tspan, StripApplication.opt_age_newest);
807                                 return;
808                         }
809                         
810                 }
811         
812         
813                 var fileinfo = File.new_for_path(path +"/" + name)
814                                         .query_info(GLib.FileAttribute.STANDARD_SIZE+","+GLib.FileAttribute.TIME_MODIFIED
815                                                 ,GLib.FileQueryInfoFlags.NONE,null);
816         var file_size = (int) fileinfo.get_size();
817                 var mod_time = fileinfo.get_modification_time();
818                 
819                 
820                 
821                 if (!StripApplication.opt_scan_mailfort) {
822                    
823                 // it's a mail directory...
824                 // use the last modification time? as the default...
825                  mailtime = new DateTime.from_timeval_utc(mod_time);
826                  this.created_dir = mailtime.format("%Y/%m/%d");
827                          this.created_date =  mailtime.format("%Y-%m-%d %H:%M:%S");
828  
829         }
830                 // check on age of file...
831                 
832                 
833                 
834                 
835                 
836         this.used_space_before += file_size;
837         
838         var stream = new GMime.StreamFs.for_path (path +"/" + name,Posix.O_RDONLY, 0);
839         //stream.set_owner(true);
840         var parser = new GMime.Parser.with_stream(stream);
841         var message = parser.construct_message();
842  
843                 if (message == null) {
844                         GLib.debug("Could not parse file? %s/%s", path,name);
845                 this.used_space_after += file_size;                     
846                 return;
847                 }       
848
849
850                 // check : - is message over a year old?                
851                 // get various msg info..
852                 this.active_message_id = message.get_message_id();
853                 this.active_message_x_mailfort_sig = message.get_header("x-mailfort-sig");
854                 var recvd = message.get_header("received");
855                 this.active_message_exim_id = "";
856                 if (recvd != null && recvd.length > 1) {
857                         GLib.debug("RECV: %s", recvd);
858                         var lines = recvd.split("\t");
859                         for (var i = 0; i < lines.length;i++) {
860                                 var bits = lines[i].strip().split(" ");
861                                 if (bits[0] == "id") {
862                                         this.active_message_exim_id = bits[1].replace(";","");
863
864                                 }
865                                 
866                                 if (lines[i].contains(";")) {
867                                         var dbits = lines[i].strip().split(";");                                
868                                         GLib.debug("Reading time from : %s", dbits[1]);
869                                         var timez = GMime.utils_header_decode_date(dbits[1], null);
870                                         if (timez != 0) {
871                                                 mailtime = new DateTime.from_unix_utc(timez);
872                                                 this.created_date = mailtime.format("%Y-%m-%d %H:%M:%S");
873                                                 GLib.debug("Time is %s",this.created_date);
874                                                 // if it's not mailfort we can use that date to determine where to store it...
875                                                 if (!StripApplication.opt_scan_mailfort) {
876                                                         this.created_dir = mailtime.format("%Y/%m/%d");
877                                                 }
878                                         } else {
879                                                 GLib.debug("Could not read time from headers?");
880                                         }
881                                 }
882
883                         }
884                 }
885                 
886                 var oldest = new  DateTime.now_local();
887                 oldest = oldest.add_months(-1 * StripApplication.opt_age_oldest);
888                 var rtspan = mailtime.difference(oldest) / GLib.TimeSpan.DAY;
889                 GLib.debug("Checking oldest %d days difference", (int)rtspan   );
890                 if (rtspan < 0) {
891                         GLib.debug("skip(2) file is %d days older than %d months", (int)rtspan, StripApplication.opt_age_oldest);
892                         return;
893                 }
894                 var newest = new  DateTime.now_local();
895                 newest = newest.add_months(-1 * StripApplication.opt_age_newest);
896                 rtspan = mailtime.difference(newest) / GLib.TimeSpan.DAY;
897                 if (rtspan > 0) {
898                         GLib.debug("skip(2) file is %d days newer than %d months : %s", (int)rtspan, StripApplication.opt_age_newest,
899                                 mailtime.format("%Y-%m-%d %H:%M:%S"));
900                         return;
901                 }
902                 
903                 
904                 
905                 /*
906                 GLib.debug("Message DATA:\n mid: %s\nmailfort: %s \nexim_id: %s",
907                         this.active_message_id,
908                         this.active_message_x_mailfort_sig,
909                         this.active_message_exim_id
910                 );
911                  */
912                         
913                 // DATE?
914                 
915                 var mp = message.get_mime_part();
916
917                 if (!(mp is GMime.Multipart)) {
918                         //GLib.debug("get mimepart does not return a Multipart?");
919                 this.used_space_after += file_size;                                             
920                         return;
921                 }
922                 
923                 var mpc = ((GMime.Multipart)mp).get_count();
924                 
925                 //GLib.debug("Message has %d parts", mpc); 
926                 for (var i =0 ; i < mpc; i++) {
927                         //GLib.debug("Getting part %d", i); 
928                         var mime_obj = ((GMime.Multipart)mp).get_part(i);
929             this.handle_part(mp,mime_obj);                      
930         }
931                 
932         parser= null;
933
934       //  stream.set_owner(false);
935             //stream.close();
936         stream = null;//.close();
937         
938         
939                 if (!this.has_replaced) {
940                         this.used_space_after += file_size;
941                         GLib.debug("skpping write file - no replacement occured");
942                         return;
943                 }
944                 string tmpfile = "";
945                 GMime.Stream outstream = new GMime.StreamNull();
946                 if (StripApplication.opt_is_replacing) {
947                 
948                         tmpfile = GLib.Environment.get_tmp_dir() +"/" + name;
949                 outstream = new GMime.StreamFile.for_path (tmpfile,"w");
950                 ((GMime.StreamFile)outstream).set_owner(true);
951         }
952                 if (StripApplication.opt_dump) {
953                         outstream = new GMime.StreamMem();
954         }
955         
956         file_size = (int) message.write_to_stream(outstream);
957         if (StripApplication.opt_is_replacing) {
958                 ((GMime.StreamFile)outstream).set_owner(false);
959         }
960                 if (StripApplication.opt_dump) {
961                         var ua = ((GMime.StreamMem)outstream).get_byte_array().data;
962                         print("%s\n", (string) ua);
963                 }        
964         message = null;
965         outstream.flush();
966         outstream.close();
967         GLib.debug("finished writing output %d", file_size);
968
969         //
970         outstream = null;
971         
972           
973         this.used_space_after += file_size;
974         
975         
976         if (StripApplication.opt_is_replacing) {
977                 Posix.unlink(path +"/" + name);         
978                 GLib.debug("copy tmp file %s to %s" , tmpfile, path +"/" + name);               
979                 
980                 // link will not work, as we are doing it accross file systems
981                         var from = File.new_for_path (tmpfile);
982                         var nf =  File.new_for_path (path +"/" + name);
983                         from.copy(nf, 0, null);
984                         
985
986                 var newfileinfo = nf.query_info(GLib.FileAttribute.TIME_MODIFIED,GLib.FileQueryInfoFlags.NONE,null);
987                 newfileinfo.set_modification_time(mod_time);
988                 nf.set_attributes_from_info(newfileinfo,FileQueryInfoFlags.NONE);
989                 Posix.unlink(tmpfile);
990                 }
991         this.processed++;
992         
993         if (StripApplication.opt_limit > -1 && this.processed >= StripApplication.opt_limit) {
994                 GLib.debug("Reached replacement limit");
995                 Posix.exit(1);
996         }
997         
998         
999         
1000         
1001     }
1002     
1003     
1004     public void scan_dir(string basepath, string subpath)
1005     {
1006         
1007         
1008         // determine if path is to old to scan..
1009         if (subpath.length > 0 && StripApplication.opt_scan_mailfort) {
1010                         var year =  int.parse(subpath.substring(1,4));  // "/2000"
1011                         var month = subpath.length > 5 ? int.parse(subpath.substring(6,2)) : 999; // "/2000/12"                 
1012                         var day = subpath.length > 8 ? int.parse(subpath.substring(9,2)) : 999; // "/2000/12/01"                        
1013                 
1014                 var oldest = new  DateTime.now_local();
1015                         oldest = oldest.add_months(-1 * StripApplication.opt_age_oldest);
1016                         
1017                         //GLib.debug("Checking directory %s is older than min: %d/%d/%d", subpath, oldest.get_year() , oldest.get_month(), oldest.get_day_of_month() );                                 
1018                         
1019                         if (year < oldest.get_year()) {
1020                                 GLib.debug("Skip directory %s is older than min year: %d", subpath, oldest.get_year());
1021                                 return;
1022                         }
1023                         if (year == oldest.get_year() &&  month < oldest.get_month()) {
1024                                 GLib.debug("Skip directory %s is older than min month: %d/%d", subpath, oldest.get_year() , oldest.get_month() );
1025                                 return;
1026                         }
1027                 if (year == oldest.get_year() &&  month == oldest.get_month() && day < oldest.get_day_of_month()) {
1028                                 GLib.debug("Skip directory %s is older than min day: %d/%d/%d", subpath, oldest.get_year() , oldest.get_month(), oldest.get_day_of_month() );           
1029                                 return;
1030                         }
1031                 
1032                 var newest = new  DateTime.now_local();
1033                         newest = newest.add_months(-1 * StripApplication.opt_age_newest);
1034                         
1035                         //GLib.debug("Checking directory %s is newer than max: %d/%d/%d", subpath, newest.get_year() , newest.get_month(), newest.get_day_of_month() );                                 
1036                         
1037                         if (year > newest.get_year()) {
1038                                 GLib.debug("Skip directory %s is newer than max year: %d", subpath, newest.get_year());
1039                                 return;
1040                         }
1041                         if (year == newest.get_year() &&  month != 999 && month > newest.get_month()) {
1042                                 GLib.debug("Skip directory %s is newer than max month: %d/%d", subpath, newest.get_year() , newest.get_month() );
1043                                 return;
1044                         }
1045                 if (year == newest.get_year() &&  month == newest.get_month() &&  day != 999 && day > newest.get_day_of_month()) {
1046                                 GLib.debug("Skip directory %s is newer than max day: %d/%d/%d", subpath, newest.get_year() , newest.get_month(), newest.get_day_of_month() );           
1047                                 return;
1048                         }
1049                 
1050                 
1051                 
1052         }
1053         
1054         
1055         var f = File.new_for_path(basepath + subpath);
1056                 FileEnumerator file_enum;
1057         var cancellable = new Cancellable ();
1058         try {      
1059             file_enum = f.enumerate_children(
1060                 FileAttribute.STANDARD_DISPLAY_NAME + "," +   FileAttribute.STANDARD_TYPE,
1061                         FileQueryInfoFlags.NOFOLLOW_SYMLINKS,  // FileQueryInfoFlags.NONE,
1062                         cancellable
1063                 );
1064         } catch (Error e) {
1065                 GLib.debug("Got error scanning dir? %s", e.message);
1066             // FIXME - show error..
1067             return;
1068         }
1069         FileInfo next_file;
1070          
1071         while (cancellable.is_cancelled () == false ) {
1072             try {
1073                 next_file = file_enum.next_file (cancellable);
1074             } catch(Error e) {
1075                 GLib.debug("error getting next file? %s", e.message);
1076                 break;
1077             }
1078
1079             if (next_file == null) {
1080                 break;
1081             }
1082                 
1083                 
1084                 if (next_file.get_is_symlink()) {
1085                 next_file = null;
1086                 continue;
1087             }
1088             
1089             var ds = next_file.get_display_name();
1090             if (next_file.get_file_type() != FileType.DIRECTORY) {
1091                 
1092                 
1093                 
1094                 if (ds[0] == ',') {
1095                         continue;
1096                 }
1097                 // other files to ignore?
1098                 if (Regex.match_simple (".tgz$", ds)) {
1099                         continue;
1100                 }
1101                 this.scan_file(basepath + subpath , ds);
1102                                 if(this.has_replaced) {
1103                          this.report_state("After scanning %s/%s".printf(basepath + subpath , ds));
1104                         }
1105                 continue;
1106             }
1107
1108
1109             //stdout.printf("Monitor.monitor: got file %s : type :%u\n",
1110             //        next_file.get_display_name(), next_file.get_file_type());
1111
1112
1113         
1114
1115             // not really needed?? - we are storing attachments in a seperate location now...
1116             if (ds[0] == '.') {
1117                 next_file = null;
1118                 continue;
1119             }
1120             if (ds == "attachments") {
1121                         continue;
1122                 }
1123             
1124             
1125             var sp = subpath+"/"+next_file.get_display_name();
1126             // skip modules.
1127             //print("got a file : " + sp);
1128          
1129             next_file = null;
1130             
1131             
1132             this.scan_dir(basepath,sp);
1133             
1134         }
1135     
1136     
1137     }
1138     void report_state(string msg) 
1139     {
1140         // Saved: 2G  Original 10G : 20%
1141         GLib.debug("Saved : %s (%.1f%%) | Original %s | %s", 
1142                         GLib.format_size(this.used_space_before - this.used_space_after), 
1143                         100f * ((1f * (this.used_space_before - this.used_space_after)) / (this.used_space_before * 1f)), 
1144                         GLib.format_size(this.used_space_before),                       
1145                         msg
1146                 );
1147         
1148         }
1149         
1150         
1151
1152 }