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