File: filsubs.c

package info (click to toggle)
acedb 4.9.39%2Bdfsg.01-5
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 33,320 kB
  • ctags: 21,771
  • sloc: ansic: 256,960; perl: 2,803; cpp: 2,534; csh: 1,712; python: 862; sh: 658; makefile: 326; awk: 249; lex: 225; yacc: 221
file content (1048 lines) | stat: -rw-r--r-- 31,254 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
/*  File: filsubs.c
 *  Author: Jean Thierry-Mieg (mieg@mrc-lmb.cam.ac.uk)
 *  Copyright (C) J Thierry-Mieg and R Durbin, 1991
 * -------------------------------------------------------------------
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * -------------------------------------------------------------------
 * This file is part of the ACEDB genome database package, written by
 * 	Richard Durbin (MRC LMB, UK) rd@mrc-lmb.cam.ac.uk, and
 *	Jean Thierry-Mieg (CRBM du CNRS, France) mieg@kaa.cnrs-mop.fr
 *
 * Description:
 *                   cross platform file system routines
 *              
 * Exported functions:
 * HISTORY:
 * Last edited: Dec 12 11:32 2003 (edgrif)
 * * Nov 29 11:53 1999 (edgrif): Added new filCopyFile function.
 * * Apr 13 13:40 1999 (fw): fixed bug in filCheck if spec is "wd" or "ad"
 * * Dec  8 10:20 1998 (fw): new function filAge to determine time since
 *              last modification of file
 * * Oct 22 16:17 1998 (edgrif): Replace unsafe strtok with strstr.
 * * Oct 15 11:47 1998 (fw): include messSysErrorText in some messges
 * * Sep 30 09:37 1998 (edgrif): Replaced my strdup with acedb strnew.
 * * Sep  9 14:07 1998 (edgrif): Add filGetFilename routine that will 
 *               return the filename given a pathname 
 *              (NOT the same as the UNIX basename).
 * * DON'T KNOW WHO DID THE BELOW..assume Richard Bruskiewich (edgrif)
 *	-	fix root path detection for default drives (in WIN32)
 * * Oct  8 23:34 1996 (rd)
 *              filDirectory() returns a sorted Array of character 
 *              strings of the names of files, with specified ending 
 *              and spec's, listed in a given directory "dirName";
 *              If !dirName or directory is inaccessible, 
 *              the function returns 0
 * * Jun  6 17:58 1996 (rd)
 * * Mar 24 02:42 1995 (mieg)
 * * Feb 13 16:11 1993 (rd): allow "" endName, and call getwd if !*dname
 * * Sep 14 15:57 1992 (mieg): sorted alphabetically
 * * Sep  4 13:10 1992 (mieg): fixed NULL used improperly when 0 is meant
 * * Jul 20 09:35 1992 (aochi): Add directory names to query file chooser
 * * Jan 11 01:59 1992 (mieg): If file has no ending i suppress the point
 * * Nov 29 19:15 1991 (mieg): If file had no ending, we were losing the
                               last character in dirDraw()
 * Created: Fri Nov 29 19:15:34 1991 (mieg)
 * CVS info:   $Id: filsubs.c,v 1.80 2003/12/12 14:13:41 edgrif Exp $
 *-------------------------------------------------------------------
 */

#include <wh/regular.h>
#include <wh/aceio.h>
#include <wh/mytime.h>
#include <wh/call.h>					    /* for callScript (to mail stuff) */
#include <wh/mydirent.h>
#include <sys/file.h>

/********************************************************************/




/*****************************************************************************/
/* This function returns the directory part of a given path,                 */
/*                                                                           */
/*   Given   "/some/load/of/directories/filename"  returns                   */
/*   returns "/some/load/of/directories"                                     */
/*                                                                           */
/* The function returns NULL for the following input:                        */
/*                                                                           */
/* 1) supplying a NULL ptr as the path                                       */
/* 2) supplying "" as the path                                               */
/*                                                                           */
/* and returns "." for the following input:                                  */
/*    supplying a path that does not contain a "/"                           */
/*                                                                           */
/* NOTE, this function is _NOT_ the same as the UNIX dirname command or the  */
/* XPG4_UNIX dirname() function which do different things.                   */
/*                                                                           */
/* The function makes a copy of the supplied path on which to work, this     */
/* copy is thrown away each time the function is called.                     */
/*                                                                           */
char *filGetDirname(char *path)
{
  static char *path_copy = NULL ;
  char *result = NULL, *tmp = NULL ;
    
  if (path != NULL)
    {
      if (path_copy != NULL)
	messfree(path_copy) ;
	  
      path_copy = strnew(path, 0) ;

      tmp = strrchr(path_copy, SUBDIR_DELIMITER) ;
      if (tmp)
	{
	  *tmp = '\0' ;
	  result = path_copy ;
	}
      else
	result = "." ;
    }
  
  return(result) ;
} /* filGetDirname */


/*****************************************************************************/
/* This function returns the filename part of a given path,                  */
/*                                                                           */
/*   Given   "/some/load/of/directories/filename"  returns  "filename"       */
/*                                                                           */
/* The function returns NULL for the following errors:                       */
/*                                                                           */
/* 1) supplying a NULL ptr as the path                                       */
/* 2) supplying "" as the path                                               */
/* 3) supplying a path that ends in "/"                                      */
/*                                                                           */
/* NOTE, this function is _NOT_ the same as the UNIX basename command or the */
/* XPG4_UNIX basename() function which do different things.                  */
/*                                                                           */
/* The function makes a copy of the supplied path on which to work, this     */
/* copy is thrown away each time the function is called.                     */
/*                                                                           */
char *filGetFilename(char *path)
{
  static char *path_copy = NULL ;
  const char *path_delim = SUBDIR_DELIMITER_STR ;
  char *result = NULL, *tmp ;
    
  if (path != NULL)
    {
      if (strcmp((path + strlen(path) - 1), path_delim) != 0) /* Last char = "/" ?? */
	{
	  if (path_copy != NULL) messfree(path_copy) ;
	  
	  path_copy = strnew(path, 0) ;
	  
	  tmp = path ;
	  while (tmp != NULL)
	    {
	      result = tmp ;
	      
	      tmp = strstr(tmp, path_delim) ;
	      if (tmp != NULL) tmp++ ;
	    }
	}
    }
  
  return(result) ;
} /* filGetFilename */


/*****************************************************************************/
/* This function returns the base filename part of a given path.             */
/*                                                                           */
/*   Given   "/some/load/of/directories/filename.something.ext"              */
/* returns   "filename.something"                                            */
/*                                                                           */
/* i.e. it lops off the directory bit and the _last_ extension.              */
/*                                                                           */
/* The function returns NULL for the following errors:                       */
/*                                                                           */
/* 1) supplying a NULL ptr as the path                                       */
/* 2) supplying "" as the path                                               */
/* 3) supplying a path that ends in "/"                                      */
/*                                                                           */
/* NOTE, this function is _NOT_ the same as the UNIX basename command or the */
/* XPG4_UNIX basename() function which do different things.                  */
/*                                                                           */
/* The function makes a copy of the supplied path on which to work, this     */
/* copy is thrown away each time the function is called.                     */
/*                                                                           */
char *filGetFilenameBase(char *path)
{
  static char *path_copy = NULL ;
  const char *path_delim = SUBDIR_DELIMITER_STR ;
  char *result = NULL, *tmp ;
    
  if (path != NULL)
    {
      if (strcmp((path + strlen(path) - 1), path_delim) != 0) /* Last char = "/" ?? */
	{
	  if (path_copy != NULL)
	    messfree(path_copy) ;
	  
	  path_copy = strnew(path, 0) ;
	  
	  tmp = path ;
	  while (tmp != NULL)
	    {
	      result = tmp ;
	      
	      tmp = strstr(tmp, path_delim) ;
	      if (tmp != NULL)
		tmp++ ;
	    }

	  tmp = strrchr(result, EXT_DELIMITER) ;
	  if (tmp)
	    *tmp = '\0' ;
	}
    }
  
  return(result) ;
}


/*****************************************************************************/
/* This function returns the file-extension part of a given path/filename,   */
/*                                                                           */
/*   Given   "/some/load/of/directories/filename.ext"  returns  "ext"        */
/*                                                                           */
/* The function returns NULL for the following errors:                       */
/*                                                                           */
/* 1) supplying a NULL ptr as the path                                       */
/* 2) supplying a path with no filename                                      */
/*                                                                           */
/* The function returns "" for a filename that has no extension              */
/*                                                                           */
/* The function makes a copy of the supplied path on which to work, this     */
/* copy is thrown away each time the function is called.                     */
/*                                                                           */
char *filGetExtension(char *path)
{
  static char *path_copy = NULL ;
  char *extension = NULL, *cp ;
    
  if (path == NULL)
    return NULL;

  if (strlen(path) == 0)
    return NULL;

  if (path_copy != NULL) messfree(path_copy) ;
  path_copy = messalloc ((strlen(path)+1) * sizeof(char));
  strcpy (path_copy, path);

  cp = path_copy + (strlen(path_copy) - 1);
  while (cp > path_copy &&
	 *cp != SUBDIR_DELIMITER &&
	 *cp != EXT_DELIMITER)
    --cp;

  extension = cp+1;
    
  return(extension) ;
} /* filGetExtension */


/***************************************************************************/

static BOOL filCheck (char *name, char *spec)
	/* allow 'd' as second value of spec for a directory */
{
  char *cp ;
  BOOL result ;
  struct stat status ;

  if (spec[1] == 'd')
    if (stat (name, &status) == 0 && (!(status.st_mode & S_IFDIR)))
      /* the pathname isn't a directory, but we asked for that */
      return FALSE;

  switch (*spec)
    {
    case 'e':						    /* file exists. */
      if (access (name, F_OK) == 0)
	{
	  if (spec[1] != 'd')
	    if (stat (name, &status) == 0 && (status.st_mode & S_IFDIR))
	      /* the pathname exists and is readable, but it is a
		 directory and we didn't ask for that */
	      return FALSE;

	  return TRUE;
	}
      return FALSE;

    case 'r':
      if (access (name, R_OK) == 0)
	{
	  if (spec[1] != 'd')
	    if (stat (name, &status) == 0 && (status.st_mode & S_IFDIR))
	      /* the pathname exists and is readbale, but it is a
		 directory and we didn't ask for that */
	      return FALSE;

	  return TRUE;
	}
      return FALSE;
    case 'w':
    case 'a':
      if (access (name, W_OK) == 0) /* requires file exists */
	{
	  if (spec[1] != 'd')
	    if (stat (name, &status) == 0 && (status.st_mode & S_IFDIR))
	      /* the pathname exists and is writable, but it is a
		 directory and we didn't ask for that */
	      return FALSE;

	  return TRUE ;
	}
      if (spec[1] == 'd')
	return FALSE;

      if (stat (name, &status) == 0)
	/* write access failed, but file exists, so check failed */
	return FALSE;

      /* for file check, we test whether its directory is writable */
      cp = name + strlen (name) ;
      while (cp > name)
	if (*--cp == SUBDIR_DELIMITER) break ;
      if (cp == name)
	return !(access (".", W_OK)) ;
      else
	{ *cp = 0 ;
	  result = !(access (name, W_OK)) ;
	  *cp = SUBDIR_DELIMITER ;
	  return result ;
	}
    case 'x':
      return (access (name, X_OK) == 0) ;
    default:
      messcrash ("Unknown spec %s passed to filName", spec) ;
    }
  return FALSE ;
}

/************************************************/

static BOOL filCanonPath (Stack s, char *name, char *ending)
{
#ifdef __CYGWIN__
  char posix[PATH_MAX];
  
  /* cygwin_conv doesn't like these (but they're already posix) */
  if ((*name) && (strcmp(name, ".") != 0) && (*name != '~'))
    cygwin_conv_to_full_posix_path(name, posix);
  else
    strcpy(posix, name);
  
  /* win32 doesn't like : in filenames - replace with . */
  for (name = posix; *name; name++)
    if (*name == ':')
      *name = '.';
      
  name = posix;
#endif

  if (*name == '/') /* absolute path */
    catText(s, name);
  else if (*name == '~') /* tilde expansion */
   {
     char *name_copy = strnew(name, 0);
     char *user = name_copy+1;
     char *user_endp, *path;
     char *homedir;
     
     /* get the username */

     user_endp = strstr (name_copy, "/");
     if (user_endp)
       {
	 *user_endp = 0;
	 path = user_endp+1;
       }
     else
       path = 0;
     
      if (strlen(user) == 0)
	user = getLogin(TRUE);
      
      homedir = getUserHomeDir (user, 0);
      messfree(name_copy);
      
      if (homedir)
	{
	  catText(s, homedir);
	  catText(s, "/");
	  messfree(homedir);
	}
      else
	return FALSE;
      
      if (path)
	catText(s, path);
   } 
  else /* Add cwd to make absolute path */
    {
      int wdsiz = MAXPATHLEN;
      char *wd = messalloc(wdsiz);
      
      while (!getcwd(wd, wdsiz))
	{ 
	  messfree(wd);
	  wdsiz += MAXPATHLEN;
	  wd = messalloc(wdsiz);
	}
      catText(s, wd);
      if ((*name) && (strcmp(name, ".") != 0))
	/* dump empty name or "." */
	{
	  catText(s, "/");
	  catText(s, name);
	}
      messfree(wd);
    }
  
  if (ending && *ending)
    { 
      catText(s, ".");
      catText(s, ending);
    }

  return TRUE;
}


char *filGetName(char *name, char *ending, 
		 char *spec, STORE_HANDLE handle)
{
  Stack s = stackCreate(MAXPATHLEN);
  char *ret;
  
  if (!name)
    messcrash ("filGetName received a null name") ;
  
  if (filCanonPath(s, name, ending) && filCheck(stackText(s, 0), spec))
    ret = strnew(stackText(s, 0), handle);
  else
    ret = NULL;
  
  stackDestroy(s);
  
  return ret;
}

BOOL filCheckName(char *name, char *ending, char *spec)
{
  Stack s = stackCreate(MAXPATHLEN);
  BOOL ret;

  if (!name)
    messcrash ("filCheckName received a null name") ;
  
  ret = filCanonPath(s, name, ending) && filCheck(stackText(s, 0), spec);

  stackDestroy(s);
  
  return ret;
}

char *filGetFullPath(char *dir, STORE_HANDLE handle)
{
  Stack s = stackCreate(MAXPATHLEN);
  char *ret;
  
  if (filCanonPath(s, dir, 0))
    ret = strnew(stackText(s, 0), handle);
  else
    ret = NULL;

  stackDestroy(s);

  return ret;
}
  
/* Compatibilty function: Note that:
   THIS IS NOT THREADSAFE.
   Continued use of this function will send you blind. */
char *filName (char *name, char *ending, char *spec)
{ 
  static Stack s = NULL;
  
  if (!s)
    s = stackCreate(MAXPATHLEN);
  else
    stackClear(s);
    
  if (filCanonPath(s, name, ending) && filCheck(stackText(s, 0), spec))
    return stackText(s, 0);
  else
    return NULL;
}

/************************************************************/

BOOL filremove (char *name, char *ending) 
				/* TRUE if file is deleted. -HJC*/
{
  Stack s = stackCreate(MAXPATHLEN);
  BOOL ret;
  
  filCanonPath(s, name, ending) ;
  ret = unlink(stackText(s, 0)) ? FALSE : TRUE ;
  
  stackDestroy(s);
  
  return ret;
} /* filremove */

/**************************************************************/

FILE *filopen (char *name, char *ending, char *spec)
{
  Stack s = stackCreate(MAXPATHLEN);
  FILE *result = 0 ;
  
  filCanonPath(s, name, ending);

  if (!filCheck(stackText(s, 0), spec))
    {
      if (spec[0] == 'r')
	messerror ("Failed to open for reading: %s (%s)",
		   stackText(s, 0),
		   messSysErrorText()) ;
      else if (spec[0] == 'w')
	messerror ("Failed to open for writing: %s (%s)",
		   stackText(s ,0),
		   messSysErrorText()) ;
      else if (spec[0] == 'a')
	messerror ("Failed to open for appending: %s (%s)",
		   stackText(s ,0),
		   messSysErrorText()) ;
      else
	messcrash ("filopen() received invalid filespec %s",
		   spec ? spec : "(null)");
    }
  else  if (!(result = fopen (stackText(s, 0), spec)))
    messerror ("Failed to open %s (%s)",
	       stackText(s, 0), messSysErrorText()) ;
     
 
  stackDestroy(s);

  return result ;
} /* filopen */

/********************* temporary file stuff *****************/

static Associator tmpFiles = 0 ;

FILE *filtmpopen (char **nameptr, char *spec)
{
  return filTmpOpenWithSuffix(nameptr, 0, spec);
}


FILE *filTmpOpenWithSuffix (char **nameptr, char *suffix, char *spec)
{
  char *nam, *realname;
  

#ifdef __CYGWIN__
  char *tmpenv = getenv("TEMP");
  char tmppath[PATH_MAX];
  
  if (tmpenv)
    cygwin_conv_to_full_posix_path(tmpenv, tmppath);
  else
    cygwin_conv_to_full_posix_path("c:\\Temp", tmppath);
#endif

  if (!nameptr)
    messcrash ("filtmpopen requires a non-null nameptr") ;

  if (!strcmp (spec, "r"))
    return filopen (*nameptr, 0, spec) ;

#if defined(SUN) || defined(SOLARIS)
  if (!(nam = tempnam ("/var/tmp", "ACEDB")))
#elif defined(__CYGWIN__)
  if (!(nam = tempnam(tmppath, "ACEDB")))
#else
  if (!(nam = tempnam ("/tmp", "ACEDB")))
#endif
    { 
      messerror ("failed to create temporary file (%s)",
		 messSysErrorText()) ;
      return 0 ;
    }
  
  if (suffix == 0)
    {
      realname = strnew(nam, 0);
    }
  else
    {
      realname = messalloc(strlen(nam)+strlen(suffix)+2); 
      /* . and terminator */
      strcpy(realname, nam);
      strcat(realname, ".");
      strcat(realname, suffix);
    }
  
  free(nam);

  if (!tmpFiles)
    tmpFiles = assCreate () ;
  assInsert (tmpFiles, realname, realname) ;

  *nameptr = realname;
  return filopen (*nameptr, 0, spec) ;
} /* filtmpopen */

/************************************************************/

BOOL filtmpremove (char *name)	/* delete and free()  */
{
  BOOL result = filremove (name, 0) ;
  assRemove (tmpFiles, name) ;
  messfree(name);
  return result ;
}

/************************************************************/

void filtmpcleanup (void)
{ char *name = 0 ;
 
  if (tmpFiles)
    while (assNext (tmpFiles, &name, 0))
      { 
	char *name1 = name;
	filremove (name, 0) ;
	messfree (name1) ; /* Since messfree zeros it. */
      }
}

/************* filqueryopen() ****************/

static QueryOpenRoutine queryOpenFunc = 0 ;

QueryOpenRoutine filQueryOpenRegister (QueryOpenRoutine new)
{ QueryOpenRoutine old = queryOpenFunc ; queryOpenFunc = new ; return old ; }

FILE *filqueryopen (char *dname, char *fname, char *end, char *spec, char *title)
{
  Stack s ;
  FILE*	fil = 0 ;
  int i ;
  ACEIN answer_in;
				/* use registered routine if available */
  if (queryOpenFunc)
    return (*queryOpenFunc)(dname, fname, end, spec, title) ;

  /* otherwise do here and use messPrompt() */
  s = stackCreate(50);

  if (dname && *dname)
    { pushText(s, dname) ; catText(s,"/") ; }
  if (fname)
    catText(s,fname) ; 
  if (end && *end)
    { catText(s,".") ; catText(s,end) ; }

 lao:
  answer_in = messPrompt("File name please", stackText(s,0), "w", 0);

  if (!answer_in)
    { 
      stackDestroy(s) ;
      return 0 ;
    }

  i = stackMark(s) ;
  pushText(s, aceInPath(answer_in));
  aceInDestroy (answer_in);

  if (spec[0] == 'w' && filCheckName (stackText(s,i), "", "r"))
    { 
      if (messQuery (messprintf ("Overwrite %s?",
				 stackText(s,i))))
	{ 
	  if ((fil = filopen (stackText(s,i), "", spec)))
	    goto bravo ;
	  else
	    messout ("Sorry, can't open file %s for writing",
		     stackText (s,i)) ;
	}
      goto lao ;
    }
  else if (!(fil = filopen (stackText(s,i), "", spec))) 
    messout ("Sorry, can't open file %s",
	     stackText(s,i));

bravo:
  stackDestroy(s) ;

  return fil ;
} /* filqueryopen */

/*********************************************/

Associator mailFile = 0, mailAddress = 0 ;

void filclose (FILE *fil)
{
  char *address ;
  char *filename ;

  if (!fil || fil == stdin || fil == stdout || 
      fil == stderr || fil == (FILE *)0x1) 
    /* see filquery.c - 0x1 == dummy directory */
    return ;
  fclose (fil) ;
  if (mailFile && assFind (mailFile, fil, &filename))
    { if (assFind (mailAddress, fil, &address))
	callScript ("mail", messprintf ("%s < %s", address, filename)) ;
      else
	messerror ("Have lost the address for mailfile %s", filename) ;
      assRemove (mailFile, fil) ;
      assRemove (mailAddress, fil) ;
      filtmpremove (filename) ;	/* came from filmail() */
    }
} /* filclose */

/***********************************/

FILE *filmail (char *address)	/* requires filclose() */
{
  char *filename ;
  FILE *fil ;

  if (!mailFile)
    { mailFile = assCreate () ;
      mailAddress = assCreate () ;
    }
  if (!(fil = filtmpopen (&filename, "w")))
    { messout ("failed to open temporary mail file %s", filename) ;
      return 0 ;
    }
  assInsert (mailFile, fil, filename) ;
  assInsert (mailAddress, fil, address) ;
  return fil ;
} /* filmail */

/******************* directory stuff *************************/

static int dirOrder(void *a, void *b)
{
  char *cp1 = *(char **)a, *cp2 = *(char**)b;
  return strcmp(cp1, cp2) ;
} /* dirOrder */

static void filDirFinalise (void *vp)
{
  FilDir fdir = (FilDir)vp;

  handleDestroy (fdir->handle);

  return;
} /* filDirFinalise */


FilDir filDirHandleCopy (FilDir fd, STORE_HANDLE handle)
{
  int i;
  FilDir fdir;

  fdir = (FilDir)halloc(sizeof(struct FilDirStruct), handle);
  blockSetFinalise (fdir, filDirFinalise);

  fdir->handle = handleCreate();
  fdir->entries = arrayHandleCreate (arrayMax(fd->entries), char*, fdir->handle) ;

  for (i = 0; i < filDirMax(fd); ++i)
    {
      array (fdir->entries, i, char*) = strnew(filDirEntry(fd, i), fdir->handle);
    }

  return fdir;
} /* filDirCopy */


/* returns a directory listing of strings representing the filename in the
   given directory according to the spec. "r" will list all files,
   and "rd" will list all directories.
   The behavior of the "w" spec is undefined.

   The directory entries are accessed using 
      char *filDirEntry (FilDir dir, int i);
      int filDirMax (FilDir dir);

   The returned FilDir object has to be destroyed using messfree,
   which reclaims all memory. */

FilDir filDirHandleCreate (char *dirName,
			   char *ending, 
			   char *spec,
			   STORE_HANDLE handle)
{
  FilDir fdir ;
  DIR	*dirp ;
  char	*dName, entryPathName[MAXPATHLEN], *leaf ;
  int	dLen, endLen ;
  MYDIRENT *dent ;

  if (!dirName || !(dirp = opendir (dirName)))
    return 0 ;

  fdir = (FilDir)halloc(sizeof(struct FilDirStruct), handle);
  blockSetFinalise (fdir, filDirFinalise);

  fdir->handle = handleCreate();
  fdir->entries = arrayHandleCreate (16, char*, fdir->handle) ;


  if (ending)
    endLen = strlen (ending) ;
  else
    endLen = 0 ;

  strcpy (entryPathName, dirName) ;
  strcat (entryPathName, "/") ;
  leaf = entryPathName + strlen(dirName) + 1 ;

  while ((dent = readdir (dirp)))           
    { dName = dent->d_name ;
      dLen = strlen (dName) ;
      if (endLen && (dLen <= endLen ||
		     dName[dLen-endLen-1] != '.'  ||
		     strcmp (&dName[dLen-endLen],ending)))
	continue ;

      strcpy (leaf, dName) ;
      if (!filCheck (entryPathName, spec))
	continue ;

      if (ending && dName[dLen - endLen - 1] == '.') /* remove ending */
	dName[dLen - endLen - 1] = 0 ;

      /* the memory of these strings is reclaimed
	 by filDirFinalise, if the returned FilDir object 
	 is destroyed using messfree() */
      array(fdir->entries,  arrayMax(fdir->entries), char*) = 
	strnew (dName, fdir->handle);
    }
  
  closedir (dirp) ;
  
  /************* reorder ********************/
    
  arraySort(fdir->entries, dirOrder) ;
  return fdir ;
} /* filDirCreate */

/*************************************************************/


/* This function copies a file (surprisingly there is no standard Posix      */
/* function to do this). The file is created with read/write permissions     */
/* for the user. Note that it is permissible for the new file to exist, in   */
/* which case its contents will be OVERWRITTEN. This is to allow the caller  */
/* to create a file with a unique name, close it and then supply it as an    */
/* argument to this call (e.g. caller may use aceTmpCreate() to create the   */
/* file).                                                                    */
/*                                                                           */
/* The function returns FALSE for the following errors:                      */
/*                                                                           */
/* 1) supplying a NULL ptr or empty string for either file name.             */
/* 2) if the file to be copied does not exist/is not readable.               */
/* 3) if the file to be created is not writeable.                            */
/* 4) if the copy fails for some other reason (e.g. read/write failed)       */
/*                                                                           */
/* This code is adapted from ffcopy.c from "POSIX Programmers Guide"         */
/* by Donald Levine, publ. by O'Reilly.                                      */
/*                                                                           */
/* It would be handy to use access() to check whether we can read a file     */
/* but this only uses the real UID, not the effective UID. stat() returns    */
/* info. about the file mode but we would need to get hold of all sorts of   */
/* other information (effective UID, group membership) to use it.            */
/*                                                                           */
BOOL filCopyFile(char *curr_name, char *new_name)
{
  BOOL status = TRUE ;
  struct stat file_stat ;
  ssize_t buf_size ;
  size_t bytes_left ;
  enum {BUF_MAX_BYTES = 4194304} ;			    /* Buffer can be up to this size. */
  char *buffer = NULL ;
  int curr_file = -1, new_file = -1 ;

  /* File names supplied ?                                                   */
  if (!curr_name || !(*curr_name) || !new_name || !(*new_name))
    status = FALSE ;

  /* Make sure file to be copied exists and can be opened for reading.       */
  if (status)
    {
      if (stat(curr_name, &file_stat) != 0)
       status = FALSE ;
      else
	{
	  bytes_left = buf_size = file_stat.st_size ;
	  if (buf_size > BUF_MAX_BYTES)
	    buf_size = BUF_MAX_BYTES ;
	  
	  if ((curr_file = open(curr_name, O_RDONLY, 0)) == -1)
	    status = FALSE ;
	}
    }

  /* Make sure file to be written can be opened for writing (O_TRUNC means   */
  /* existing contents of the file will be overwritten).                     */
  if (status)
    {
      if ((new_file = open(new_name, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR)) == -1)
	status = FALSE ;
    }

  
  /* allocate a buffer for the whole file, or the maximum chunk if the file  */
  /* is bigger.                                                              */
  if (status)
    {
      if((buffer = (char *)messalloc(buf_size)) == NULL)
	status = FALSE ;
    }
  

  /* Copy the file. */
  if (status)
    {
      while (bytes_left > 0 && status)
	{
	  if (read(curr_file, buffer, buf_size) != buf_size)
	    status = FALSE ;

	  if (status)
	    {
	      if (write(new_file, buffer, buf_size) != buf_size)
		status = FALSE ;
	    }

	  if (status)
	    {
	      bytes_left -= buf_size;
	      if (bytes_left < buf_size)
		buf_size = bytes_left ;
	    }
	}

    }

  /* Clear up buffer and files.                                              */
  if (buffer != NULL)
    messfree(buffer) ;

  if (curr_file > -1)
    {
      if (close(curr_file) != 0)
	messcrash("close() of file being copied failed.") ;
    }
  if (new_file > -1)
    {
      if (close(new_file) != 0)
	messcrash("close() of file being copied failed.") ;
    }

  return status ;
}



/************************************************************/
/* determines the age of a file, according to its last modification date.

   returns TRUE if the age could determined and the int-pointers
   (if non-NULL will be filled with the numbers).

   returns FALSE if the file doesn't exist, is not readable,
   or the age could not be determined. */
/************************************************************/
BOOL filAge (char *name, char *end,
	     int *diffYears, int *diffMonths, int *diffDays,
	     int *diffHours, int *diffMins, int *diffSecs)
{
  struct stat status;
  mytime_t time_now, time_modified;
  char time_modified_str[25];
  char *filName;
  time_t t;
  struct tm *ts;

  /* get the last-modification time of the file,
     we parse the time into two acedb-style time structs
     in order to compare them using the timediff functions */
  
  if (!(filName = filGetName(name, end, "r", 0)))
    return FALSE;

  if (stat (filName, &status) == -1)
    {
      messfree(filName);
      return FALSE;
    }
  
  messfree(filName);
  
  t = status.st_mtime;
  
  /* convert the time_t time into a tm-struct time */
  ts = localtime(&t);		
  
  /* get a string with that time in it */
  strftime (time_modified_str, 25, "%Y-%m-%d_%H:%M:%S", ts) ;
    
  time_now =      timeNow();
  time_modified = timeParse(time_modified_str);
  
  if (diffYears)
    timeDiffYears (time_modified, time_now, diffYears);
  
    if (diffMonths)
      timeDiffMonths (time_modified, time_now, diffMonths);
    
    if (diffDays)
      timeDiffDays (time_modified, time_now, diffDays);
    
    if (diffHours)
      timeDiffHours (time_modified, time_now, diffHours);
    
    if (diffMins)
      timeDiffMins (time_modified, time_now, diffMins);
    
    if (diffSecs)
      timeDiffSecs (time_modified, time_now, diffSecs);

    
    return TRUE;
} /* filAge */


/*************** end of file ****************/