1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %             U   U  TTTTT  IIIII  L      IIIII  TTTTT  Y   Y                 %
7 %             U   U    T      I    L        I      T     Y Y                  %
8 %             U   U    T      I    L        I      T      Y                   %
9 %             U   U    T      I    L        I      T      Y                   %
10 %              UUU     T    IIIII  LLLLL  IIIII    T      Y                   %
11 %                                                                             %
12 %                                                                             %
13 %                       MagickCore Utility Methods                            %
14 %                                                                             %
15 %                             Software Design                                 %
16 %                                  Cristy                                     %
17 %                              January 1993                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    https://imagemagick.org/script/license.php                               %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %
37 */
38 
39 /*
40   Include declarations.
41 */
42 #include "MagickCore/studio.h"
43 #include "MagickCore/property.h"
44 #include "MagickCore/blob.h"
45 #include "MagickCore/color.h"
46 #include "MagickCore/exception.h"
47 #include "MagickCore/exception-private.h"
48 #include "MagickCore/geometry.h"
49 #include "MagickCore/image-private.h"
50 #include "MagickCore/list.h"
51 #include "MagickCore/log.h"
52 #include "MagickCore/magick-private.h"
53 #include "MagickCore/memory_.h"
54 #include "MagickCore/nt-base-private.h"
55 #include "MagickCore/option.h"
56 #include "MagickCore/policy.h"
57 #include "MagickCore/random_.h"
58 #include "MagickCore/registry.h"
59 #include "MagickCore/resource_.h"
60 #include "MagickCore/semaphore.h"
61 #include "MagickCore/signature-private.h"
62 #include "MagickCore/statistic.h"
63 #include "MagickCore/string_.h"
64 #include "MagickCore/string-private.h"
65 #include "MagickCore/token.h"
66 #include "MagickCore/token-private.h"
67 #include "MagickCore/utility.h"
68 #include "MagickCore/utility-private.h"
69 #if defined(MAGICKCORE_HAVE_PROCESS_H)
70 #include <process.h>
71 #endif
72 #if defined(MAGICKCORE_HAVE_MACH_O_DYLD_H)
73 #include <mach-o/dyld.h>
74 #endif
75 
76 /*
77   Static declarations.
78 */
79 static const char
80   Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
81 
82 /*
83   Forward declaration.
84 */
85 static int
86   IsPathDirectory(const char *);
87 
88 /*
89 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
90 %                                                                             %
91 %                                                                             %
92 %                                                                             %
93 %   A c q u i r e U n i q u e F i l e n a m e                                 %
94 %                                                                             %
95 %                                                                             %
96 %                                                                             %
97 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
98 %
99 %  AcquireUniqueFilename() replaces the contents of path by a unique path name.
100 %
101 %  The format of the AcquireUniqueFilename method is:
102 %
103 %      MagickBooleanType AcquireUniqueFilename(char *path)
104 %
105 %  A description of each parameter follows.
106 %
107 %   o  path:  Specifies a pointer to an array of characters.  The unique path
108 %      name is returned in this array.
109 %
110 */
AcquireUniqueFilename(char * path)111 MagickExport MagickBooleanType AcquireUniqueFilename(char *path)
112 {
113   int
114     file;
115 
116   file=AcquireUniqueFileResource(path);
117   if (file == -1)
118     return(MagickFalse);
119   file=close(file)-1;
120   return(MagickTrue);
121 }
122 
123 /*
124 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
125 %                                                                             %
126 %                                                                             %
127 %                                                                             %
128 %   A c q u i r e U n i q u e S ym b o l i c L i n k                          %
129 %                                                                             %
130 %                                                                             %
131 %                                                                             %
132 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
133 %
134 %  AcquireUniqueSymbolicLink() creates a unique symbolic link to the specified
135 %  source path and returns MagickTrue on success otherwise MagickFalse.  If the
136 %  symlink() method fails or is not available, a unique file name is generated
137 %  and the source file copied to it.  When you are finished with the file, use
138 %  RelinquishUniqueFilename() to destroy it.
139 %
140 %  The format of the AcquireUniqueSymbolicLink method is:
141 %
142 %      MagickBooleanType AcquireUniqueSymbolicLink(const char *source,
143 %        char destination)
144 %
145 %  A description of each parameter follows.
146 %
147 %   o  source:  the source path.
148 %
149 %   o  destination:  the destination path.
150 %
151 */
152 
AcquireUniqueSymbolicLink(const char * source,char * destination)153 MagickExport MagickBooleanType AcquireUniqueSymbolicLink(const char *source,
154   char *destination)
155 {
156   int
157     destination_file,
158     source_file;
159 
160   MagickBooleanType
161     status;
162 
163   size_t
164     length,
165     quantum;
166 
167   ssize_t
168     count;
169 
170   struct stat
171     attributes;
172 
173   unsigned char
174     *buffer;
175 
176   assert(source != (const char *) NULL);
177   assert(destination != (char *) NULL);
178 #if defined(MAGICKCORE_HAVE_SYMLINK)
179   {
180     char
181       *passes;
182 
183     (void) AcquireUniqueFilename(destination);
184     (void) RelinquishUniqueFileResource(destination);
185     passes=GetPolicyValue("system:shred");
186     if (passes != (char *) NULL)
187       passes=DestroyString(passes);
188     else
189       {
190         if (*source == *DirectorySeparator)
191           {
192             if (symlink(source,destination) == 0)
193               return(MagickTrue);
194           }
195         else
196           {
197             char
198               path[MagickPathExtent];
199 
200             *path='\0';
201             if (getcwd(path,MagickPathExtent) == (char *) NULL)
202               return(MagickFalse);
203             (void) ConcatenateMagickString(path,DirectorySeparator,
204               MagickPathExtent);
205             (void) ConcatenateMagickString(path,source,MagickPathExtent);
206             if (symlink(path,destination) == 0)
207               return(MagickTrue);
208           }
209       }
210   }
211 #endif
212   destination_file=AcquireUniqueFileResource(destination);
213   if (destination_file == -1)
214     return(MagickFalse);
215   source_file=open_utf8(source,O_RDONLY | O_BINARY,0);
216   if (source_file == -1)
217     {
218       (void) close(destination_file);
219       (void) RelinquishUniqueFileResource(destination);
220       return(MagickFalse);
221     }
222   quantum=(size_t) MagickMaxBufferExtent;
223   if ((fstat(source_file,&attributes) == 0) && (attributes.st_size > 0))
224     quantum=(size_t) MagickMin(attributes.st_size,MagickMaxBufferExtent);
225   buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer));
226   if (buffer == (unsigned char *) NULL)
227     {
228       (void) close(source_file);
229       (void) close(destination_file);
230       (void) RelinquishUniqueFileResource(destination);
231       return(MagickFalse);
232     }
233   status=MagickTrue;
234   for (length=0; ; )
235   {
236     count=(ssize_t) read(source_file,buffer,quantum);
237     if (count <= 0)
238       break;
239     length=(size_t) count;
240     count=(ssize_t) write(destination_file,buffer,length);
241     if ((size_t) count != length)
242       {
243         (void) RelinquishUniqueFileResource(destination);
244         status=MagickFalse;
245         break;
246       }
247   }
248   (void) close(destination_file);
249   (void) close(source_file);
250   buffer=(unsigned char *) RelinquishMagickMemory(buffer);
251   return(status);
252 }
253 
254 /*
255 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
256 %                                                                             %
257 %                                                                             %
258 %                                                                             %
259 %  A p p e n d I m a g e F o r m a t                                          %
260 %                                                                             %
261 %                                                                             %
262 %                                                                             %
263 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
264 %
265 %  AppendImageFormat() appends the image format type to the filename.  If an
266 %  extension to the file already exists, it is first removed.
267 %
268 %  The format of the AppendImageFormat method is:
269 %
270 %      void AppendImageFormat(const char *format,char *filename)
271 %
272 %  A description of each parameter follows.
273 %
274 %   o  format:  Specifies a pointer to an array of characters.  This the
275 %      format of the image.
276 %
277 %   o  filename:  Specifies a pointer to an array of characters.  The unique
278 %      file name is returned in this array.
279 %
280 */
AppendImageFormat(const char * format,char * filename)281 MagickExport void AppendImageFormat(const char *format,char *filename)
282 {
283   char
284     extension[MagickPathExtent],
285     root[MagickPathExtent];
286 
287   assert(format != (char *) NULL);
288   assert(filename != (char *) NULL);
289   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename);
290   if ((*format == '\0') || (*filename == '\0'))
291     return;
292   if (LocaleCompare(filename,"-") == 0)
293     {
294       char
295         message[MagickPathExtent];
296 
297       (void) FormatLocaleString(message,MagickPathExtent,"%s:%s",format,
298         filename);
299       (void) CopyMagickString(filename,message,MagickPathExtent);
300       return;
301     }
302   GetPathComponent(filename,ExtensionPath,extension);
303   if ((LocaleCompare(extension,"Z") == 0) ||
304       (LocaleCompare(extension,"bz2") == 0) ||
305       (LocaleCompare(extension,"gz") == 0) ||
306       (LocaleCompare(extension,"wmz") == 0) ||
307       (LocaleCompare(extension,"svgz") == 0))
308     {
309       GetPathComponent(filename,RootPath,root);
310       (void) CopyMagickString(filename,root,MagickPathExtent);
311       GetPathComponent(filename,RootPath,root);
312       (void) FormatLocaleString(filename,MagickPathExtent,"%s.%s.%s",root,
313         format,extension);
314       return;
315     }
316   GetPathComponent(filename,RootPath,root);
317   (void) FormatLocaleString(filename,MagickPathExtent,"%s.%s",root,format);
318 }
319 
320 /*
321 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
322 %                                                                             %
323 %                                                                             %
324 %                                                                             %
325 %   B a s e 6 4 D e c o d e                                                   %
326 %                                                                             %
327 %                                                                             %
328 %                                                                             %
329 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
330 %
331 %  Base64Decode() decodes Base64-encoded text and returns its binary
332 %  equivalent.  NULL is returned if the text is not valid Base64 data, or a
333 %  memory allocation failure occurs.
334 %
335 %  The format of the Base64Decode method is:
336 %
337 %      unsigned char *Base64Decode(const char *source,length_t *length)
338 %
339 %  A description of each parameter follows:
340 %
341 %    o source:  A pointer to a Base64-encoded string.
342 %
343 %    o length: the number of bytes decoded.
344 %
345 */
Base64Decode(const char * source,size_t * length)346 MagickExport unsigned char *Base64Decode(const char *source,size_t *length)
347 {
348   int
349     state;
350 
351   const char
352     *p,
353     *q;
354 
355   size_t
356     i;
357 
358   unsigned char
359     *decode;
360 
361   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
362   assert(source != (char *) NULL);
363   assert(length != (size_t *) NULL);
364   *length=0;
365   decode=(unsigned char *) AcquireQuantumMemory((strlen(source)+3)/4,
366     3*sizeof(*decode));
367   if (decode == (unsigned char *) NULL)
368     return((unsigned char *) NULL);
369   i=0;
370   state=0;
371   for (p=source; *p != '\0'; p++)
372   {
373     if (isspace((int) ((unsigned char) *p)) != 0)
374       continue;
375     if (*p == '=')
376       break;
377     q=strchr(Base64,*p);
378     if (q == (char *) NULL)
379       {
380         decode=(unsigned char *) RelinquishMagickMemory(decode);
381         return((unsigned char *) NULL);  /* non-Base64 character */
382       }
383     switch (state)
384     {
385       case 0:
386       {
387         decode[i]=(q-Base64) << 2;
388         state++;
389         break;
390       }
391       case 1:
392       {
393         decode[i++]|=(q-Base64) >> 4;
394         decode[i]=((q-Base64) & 0x0f) << 4;
395         state++;
396         break;
397       }
398       case 2:
399       {
400         decode[i++]|=(q-Base64) >> 2;
401         decode[i]=((q-Base64) & 0x03) << 6;
402         state++;
403         break;
404       }
405       case 3:
406       {
407         decode[i++]|=(q-Base64);
408         state=0;
409         break;
410       }
411     }
412   }
413   /*
414     Verify Base-64 string has proper terminal characters.
415   */
416   if (*p != '=')
417     {
418       if (state != 0)
419         {
420           decode=(unsigned char *) RelinquishMagickMemory(decode);
421           return((unsigned char *) NULL);
422         }
423     }
424   else
425     {
426       p++;
427       switch (state)
428       {
429         case 0:
430         case 1:
431         {
432           /*
433             Unrecognized '=' character.
434           */
435           decode=(unsigned char *) RelinquishMagickMemory(decode);
436           return((unsigned char *) NULL);
437         }
438         case 2:
439         {
440           for ( ; *p != '\0'; p++)
441             if (isspace((int) ((unsigned char) *p)) == 0)
442               break;
443           if (*p != '=')
444             {
445               decode=(unsigned char *) RelinquishMagickMemory(decode);
446               return((unsigned char *) NULL);
447             }
448           p++;
449         }
450         case 3:
451         {
452           for ( ; *p != '\0'; p++)
453             if (isspace((int) ((unsigned char) *p)) == 0)
454               {
455                 decode=(unsigned char *) RelinquishMagickMemory(decode);
456                 return((unsigned char *) NULL);
457               }
458           if ((int) decode[i] != 0)
459             {
460               decode=(unsigned char *) RelinquishMagickMemory(decode);
461               return((unsigned char *) NULL);
462             }
463           break;
464         }
465       }
466     }
467   *length=i;
468   return(decode);
469 }
470 
471 /*
472 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
473 %                                                                             %
474 %                                                                             %
475 %                                                                             %
476 %   B a s e 6 4 E n c o d e                                                   %
477 %                                                                             %
478 %                                                                             %
479 %                                                                             %
480 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
481 %
482 %  Base64Encode() encodes arbitrary binary data to Base64 encoded format as
483 %  described by the "Base64 Content-Transfer-Encoding" section of RFC 2045 and
484 %  returns the result as a null-terminated ASCII string.  NULL is returned if
485 %  a memory allocation failure occurs.
486 %
487 %  The format of the Base64Encode method is:
488 %
489 %      char *Base64Encode(const unsigned char *blob,const size_t blob_length,
490 %        size_t *encode_length)
491 %
492 %  A description of each parameter follows:
493 %
494 %    o blob:  A pointer to binary data to encode.
495 %
496 %    o blob_length: the number of bytes to encode.
497 %
498 %    o encode_length:  The number of bytes encoded.
499 %
500 */
Base64Encode(const unsigned char * blob,const size_t blob_length,size_t * encode_length)501 MagickExport char *Base64Encode(const unsigned char *blob,
502   const size_t blob_length,size_t *encode_length)
503 {
504   char
505     *encode;
506 
507   const unsigned char
508     *p;
509 
510   size_t
511     i;
512 
513   size_t
514     remainder;
515 
516   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
517   assert(blob != (const unsigned char *) NULL);
518   assert(blob_length != 0);
519   assert(encode_length != (size_t *) NULL);
520   *encode_length=0;
521   encode=(char *) AcquireQuantumMemory(blob_length/3+4,4*sizeof(*encode));
522   if (encode == (char *) NULL)
523     return((char *) NULL);
524   i=0;
525   for (p=blob; p < (blob+blob_length-2); p+=3)
526   {
527     encode[i++]=Base64[(int) (*p >> 2)];
528     encode[i++]=Base64[(int) (((*p & 0x03) << 4)+(*(p+1) >> 4))];
529     encode[i++]=Base64[(int) (((*(p+1) & 0x0f) << 2)+(*(p+2) >> 6))];
530     encode[i++]=Base64[(int) (*(p+2) & 0x3f)];
531   }
532   remainder=blob_length % 3;
533   if (remainder != 0)
534     {
535       ssize_t
536         j;
537 
538       unsigned char
539         code[3];
540 
541       code[0]='\0';
542       code[1]='\0';
543       code[2]='\0';
544       for (j=0; j < (ssize_t) remainder; j++)
545         code[j]=(*p++);
546       encode[i++]=Base64[(int) (code[0] >> 2)];
547       encode[i++]=Base64[(int) (((code[0] & 0x03) << 4)+(code[1] >> 4))];
548       if (remainder == 1)
549         encode[i++]='=';
550       else
551         encode[i++]=Base64[(int) (((code[1] & 0x0f) << 2)+(code[2] >> 6))];
552       encode[i++]='=';
553     }
554   *encode_length=i;
555   encode[i++]='\0';
556   return(encode);
557 }
558 
559 /*
560 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
561 %                                                                             %
562 %                                                                             %
563 %                                                                             %
564 %   C h o p P a t h C o m p o n e n t s                                       %
565 %                                                                             %
566 %                                                                             %
567 %                                                                             %
568 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
569 %
570 %  ChopPathComponents() removes the number of specified file components from a
571 %  path.
572 %
573 %  The format of the ChopPathComponents method is:
574 %
575 %      ChopPathComponents(char *path,size_t components)
576 %
577 %  A description of each parameter follows:
578 %
579 %    o path:  The path.
580 %
581 %    o components:  The number of components to chop.
582 %
583 */
ChopPathComponents(char * path,const size_t components)584 MagickPrivate void ChopPathComponents(char *path,const size_t components)
585 {
586   ssize_t
587     i;
588 
589   for (i=0; i < (ssize_t) components; i++)
590     GetPathComponent(path,HeadPath,path);
591 }
592 
593 /*
594 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
595 %                                                                             %
596 %                                                                             %
597 %                                                                             %
598 %   E x p a n d F i l e n a m e                                               %
599 %                                                                             %
600 %                                                                             %
601 %                                                                             %
602 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
603 %
604 %  ExpandFilename() expands '~' in a path.
605 %
606 %  The format of the ExpandFilename function is:
607 %
608 %      ExpandFilename(char *path)
609 %
610 %  A description of each parameter follows:
611 %
612 %    o path: Specifies a pointer to a character array that contains the
613 %      path.
614 %
615 */
ExpandFilename(char * path)616 MagickPrivate void ExpandFilename(char *path)
617 {
618   char
619     expand_path[MagickPathExtent];
620 
621   if (path == (char *) NULL)
622     return;
623   if (*path != '~')
624     return;
625   (void) CopyMagickString(expand_path,path,MagickPathExtent);
626   if ((*(path+1) == *DirectorySeparator) || (*(path+1) == '\0'))
627     {
628       char
629         *home;
630 
631       /*
632         Substitute ~ with $HOME.
633       */
634       (void) CopyMagickString(expand_path,".",MagickPathExtent);
635       (void) ConcatenateMagickString(expand_path,path+1,MagickPathExtent);
636       home=GetEnvironmentValue("HOME");
637       if (home == (char *) NULL)
638         home=GetEnvironmentValue("USERPROFILE");
639       if (home != (char *) NULL)
640         {
641           (void) CopyMagickString(expand_path,home,MagickPathExtent);
642           (void) ConcatenateMagickString(expand_path,path+1,MagickPathExtent);
643           home=DestroyString(home);
644         }
645     }
646   else
647     {
648 #if defined(MAGICKCORE_POSIX_SUPPORT) && !defined(__OS2__)
649       char
650 #if defined(MAGICKCORE_HAVE_GETPWNAM_R)
651         buffer[MagickPathExtent],
652 #endif
653         username[MagickPathExtent];
654 
655       char
656         *p;
657 
658       struct passwd
659         *entry;
660 
661       /*
662         Substitute ~ with home directory from password file.
663       */
664       (void) CopyMagickString(username,path+1,MagickPathExtent);
665       p=strchr(username,'/');
666       if (p != (char *) NULL)
667         *p='\0';
668 #if !defined(MAGICKCORE_HAVE_GETPWNAM_R)
669       entry=getpwnam(username);
670 #else
671       struct passwd
672         pwd;
673 
674       entry=(struct passwd *) NULL;
675       if (getpwnam_r(username,&pwd,buffer,sizeof(buffer),&entry) < 0)
676         return;
677 #endif
678       if (entry == (struct passwd *) NULL)
679         return;
680       (void) CopyMagickString(expand_path,entry->pw_dir,MagickPathExtent);
681       if (p != (char *) NULL)
682         {
683           (void) ConcatenateMagickString(expand_path,"/",MagickPathExtent);
684           (void) ConcatenateMagickString(expand_path,p+1,MagickPathExtent);
685         }
686 #endif
687     }
688   (void) CopyMagickString(path,expand_path,MagickPathExtent);
689 }
690 
691 /*
692 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
693 %                                                                             %
694 %                                                                             %
695 %                                                                             %
696 %   E x p a n d F i l e n a m e s                                             %
697 %                                                                             %
698 %                                                                             %
699 %                                                                             %
700 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
701 %
702 %  ExpandFilenames() checks each argument of the given argument array, and
703 %  expands it if they have a wildcard character.
704 %
705 %  Any coder prefix (EG: 'coder:filename') or read modifier postfix (EG:
706 %  'filename[...]') are ignored during the file the expansion, but will be
707 %  included in the final argument.  If no filename matching the meta-character
708 %  'glob' is found the original argument is returned.
709 %
710 %  For example, an argument of '*.gif[20x20]' will be replaced by the list
711 %    'abc.gif[20x20]',  'foobar.gif[20x20]',  'xyzzy.gif[20x20]'
712 %  if such filenames exist, (in the current directory in this case).
713 %
714 %  Meta-characters handled...
715 %     @    read a list of filenames (no further expansion performed)
716 %     ~    At start of filename expands to HOME environemtn variable
717 %     *    matches any string including an empty string
718 %     ?    matches by any single character
719 %
720 %  WARNING: filenames starting with '.' (hidden files in a UNIX file system)
721 %  will never be expanded.  Attempting to epand '.*' will produce no change.
722 %
723 %  Expansion is ignored for coders "label:" "caption:" "pango:" and "vid:".
724 %  Which provide their own '@' meta-character handling.
725 %
726 %  You can see the results of the expansion using "Configure" log events.
727 %
728 %  The returned list should be freed using  DestroyStringList().
729 %
730 %  However the strings in the original pointed to argv are not
731 %  freed  (TO BE CHECKED).  So a copy of the original pointer (and count)
732 %  should be kept separate if they need to be freed later.
733 %
734 %  The format of the ExpandFilenames function is:
735 %
736 %      status=ExpandFilenames(int *number_arguments,char ***arguments)
737 %
738 %  A description of each parameter follows:
739 %
740 %    o number_arguments: Specifies a pointer to an integer describing the
741 %      number of elements in the argument vector.
742 %
743 %    o arguments: Specifies a pointer to a text array containing the command
744 %      line arguments.
745 %
746 */
ExpandFilenames(int * number_arguments,char *** arguments)747 MagickExport MagickBooleanType ExpandFilenames(int *number_arguments,
748   char ***arguments)
749 {
750   char
751     home_directory[MagickPathExtent],
752     **vector;
753 
754   ssize_t
755     i,
756     j;
757 
758   size_t
759     number_files;
760 
761   ssize_t
762     count,
763     parameters;
764 
765   /*
766     Allocate argument vector.
767   */
768   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
769   assert(number_arguments != (int *) NULL);
770   assert(arguments != (char ***) NULL);
771   vector=(char **) AcquireQuantumMemory((size_t) (*number_arguments+1),
772     sizeof(*vector));
773   if (vector == (char **) NULL)
774     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
775   /*
776     Expand any wildcard filenames.
777   */
778   *home_directory='\0';
779   count=0;
780   for (i=0; i < (ssize_t) *number_arguments; i++)
781   {
782     char
783       **filelist,
784       filename[MagickPathExtent],
785       magick[MagickPathExtent],
786       *option,
787       path[MagickPathExtent],
788       subimage[MagickPathExtent];
789 
790     MagickBooleanType
791       destroy;
792 
793     option=(*arguments)[i];
794     *magick='\0';
795     *path='\0';
796     *filename='\0';
797     *subimage='\0';
798     number_files=0;
799     vector[count++]=ConstantString(option);
800     destroy=MagickTrue;
801     parameters=ParseCommandOption(MagickCommandOptions,MagickFalse,option);
802     if (parameters > 0)
803       {
804         /*
805           Do not expand command option parameters.
806         */
807         for (j=0; j < parameters; j++)
808         {
809           i++;
810           if (i == (ssize_t) *number_arguments)
811             break;
812           option=(*arguments)[i];
813           vector[count++]=ConstantString(option);
814         }
815         continue;
816       }
817     if ((*option == '"') || (*option == '\''))
818       continue;
819     GetPathComponent(option,TailPath,filename);
820     GetPathComponent(option,MagickPath,magick);
821     if ((LocaleCompare(magick,"CAPTION") == 0) ||
822         (LocaleCompare(magick,"LABEL") == 0) ||
823         (LocaleCompare(magick,"PANGO") == 0) ||
824         (LocaleCompare(magick,"VID") == 0))
825       continue;
826     if ((IsGlob(filename) == MagickFalse) && (*option != '@'))
827       continue;
828     if ((*option != '@') && (IsPathAccessible(option) == MagickFalse))
829       {
830         /*
831           Generate file list from wildcard filename (e.g. *.jpg).
832         */
833         GetPathComponent(option,HeadPath,path);
834         GetPathComponent(option,SubimagePath,subimage);
835         ExpandFilename(path);
836         if (*home_directory == '\0')
837           getcwd_utf8(home_directory,MagickPathExtent-1);
838         filelist=ListFiles(*path == '\0' ? home_directory : path,filename,
839           &number_files);
840       }
841     else
842       {
843         char
844           *files;
845 
846         ExceptionInfo
847           *exception;
848 
849         int
850           length;
851 
852         /*
853           Generate file list from file list (e.g. @filelist.txt).
854         */
855         exception=AcquireExceptionInfo();
856         files=FileToString(option+1,~0UL,exception);
857         exception=DestroyExceptionInfo(exception);
858         if (files == (char *) NULL)
859           continue;
860         filelist=StringToArgv(files,&length);
861         if (filelist == (char **) NULL)
862           continue;
863         files=DestroyString(files);
864         filelist[0]=DestroyString(filelist[0]);
865         for (j=0; j < (ssize_t) (length-1); j++)
866           filelist[j]=filelist[j+1];
867         number_files=(size_t) length-1;
868       }
869     if (filelist == (char **) NULL)
870       continue;
871     for (j=0; j < (ssize_t) number_files; j++)
872       if (IsPathDirectory(filelist[j]) <= 0)
873         break;
874     if (j == (ssize_t) number_files)
875       {
876         for (j=0; j < (ssize_t) number_files; j++)
877           filelist[j]=DestroyString(filelist[j]);
878         filelist=(char **) RelinquishMagickMemory(filelist);
879         continue;
880       }
881     /*
882       Transfer file list to argument vector.
883     */
884     vector=(char **) ResizeQuantumMemory(vector,(size_t) *number_arguments+
885       count+number_files+1,sizeof(*vector));
886     if (vector == (char **) NULL)
887       {
888         for (j=0; j < (ssize_t) number_files; j++)
889           filelist[j]=DestroyString(filelist[j]);
890         filelist=(char **) RelinquishMagickMemory(filelist);
891         return(MagickFalse);
892       }
893     for (j=0; j < (ssize_t) number_files; j++)
894     {
895       option=filelist[j];
896       parameters=ParseCommandOption(MagickCommandOptions,MagickFalse,option);
897       if (parameters > 0)
898         {
899           ssize_t
900             k;
901 
902           /*
903             Do not expand command option parameters.
904           */
905           vector[count++]=ConstantString(option);
906           for (k=0; k < parameters; k++)
907           {
908             j++;
909             if (j == (ssize_t) number_files)
910               break;
911             option=filelist[j];
912             vector[count++]=ConstantString(option);
913           }
914           continue;
915         }
916       (void) CopyMagickString(filename,path,MagickPathExtent);
917       if (*path != '\0')
918         (void) ConcatenateMagickString(filename,DirectorySeparator,
919           MagickPathExtent);
920       if (filelist[j] != (char *) NULL)
921         (void) ConcatenateMagickString(filename,filelist[j],MagickPathExtent);
922       filelist[j]=DestroyString(filelist[j]);
923       if (strlen(filename) >= (MagickPathExtent-1))
924         ThrowFatalException(OptionFatalError,"FilenameTruncated");
925       if (IsPathDirectory(filename) <= 0)
926         {
927           char
928             file_path[MagickPathExtent];
929 
930           *file_path='\0';
931           if (*magick != '\0')
932             {
933               (void) ConcatenateMagickString(file_path,magick,
934                 MagickPathExtent);
935               (void) ConcatenateMagickString(file_path,":",MagickPathExtent);
936             }
937           (void) ConcatenateMagickString(file_path,filename,MagickPathExtent);
938           if (*subimage != '\0')
939             {
940               (void) ConcatenateMagickString(file_path,"[",MagickPathExtent);
941               (void) ConcatenateMagickString(file_path,subimage,
942                 MagickPathExtent);
943               (void) ConcatenateMagickString(file_path,"]",MagickPathExtent);
944             }
945           if (strlen(file_path) >= (MagickPathExtent-1))
946             ThrowFatalException(OptionFatalError,"FilenameTruncated");
947           if (destroy != MagickFalse)
948             {
949               count--;
950               vector[count]=DestroyString(vector[count]);
951               destroy=MagickFalse;
952             }
953           vector[count++]=ConstantString(file_path);
954         }
955     }
956     filelist=(char **) RelinquishMagickMemory(filelist);
957   }
958   vector[count]=(char *) NULL;
959   if (IsEventLogging() != MagickFalse)
960     {
961       char
962         *command_line;
963 
964       command_line=AcquireString(vector[0]);
965       for (i=1; i < count; i++)
966       {
967         (void) ConcatenateString(&command_line," {");
968         (void) ConcatenateString(&command_line,vector[i]);
969         (void) ConcatenateString(&command_line,"}");
970       }
971       (void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
972         "Command line: %s",command_line);
973       command_line=DestroyString(command_line);
974     }
975   *number_arguments=(int) count;
976   *arguments=vector;
977   return(MagickTrue);
978 }
979 
980 /*
981 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
982 %                                                                             %
983 %                                                                             %
984 %                                                                             %
985 %   G e t E x e c u t i o n P a t h                                           %
986 %                                                                             %
987 %                                                                             %
988 %                                                                             %
989 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
990 %
991 %  GetExecutionPath() returns the pathname of the executable that started
992 %  the process.  On success MagickTrue is returned, otherwise MagickFalse.
993 %
994 %  The format of the GetExecutionPath method is:
995 %
996 %      MagickBooleanType GetExecutionPath(char *path,const size_t extent)
997 %
998 %  A description of each parameter follows:
999 %
1000 %    o path: the pathname of the executable that started the process.
1001 %
1002 %    o extent: the maximum extent of the path.
1003 %
1004 */
GetExecutionPath(char * path,const size_t extent)1005 MagickPrivate MagickBooleanType GetExecutionPath(char *path,const size_t extent)
1006 {
1007   char
1008     *directory;
1009 
1010   *path='\0';
1011   directory=getcwd(path,(unsigned long) extent);
1012   (void) directory;
1013 #if defined(MAGICKCORE_HAVE_GETPID) && defined(MAGICKCORE_HAVE_READLINK) && defined(PATH_MAX)
1014   {
1015     char
1016       execution_path[PATH_MAX+1],
1017       link_path[MagickPathExtent];
1018 
1019     ssize_t
1020       count;
1021 
1022     (void) FormatLocaleString(link_path,MagickPathExtent,"/proc/%.20g/exe",
1023       (double) getpid());
1024     count=readlink(link_path,execution_path,PATH_MAX);
1025     if (count == -1)
1026       {
1027         (void) FormatLocaleString(link_path,MagickPathExtent,"/proc/%.20g/file",
1028           (double) getpid());
1029         count=readlink(link_path,execution_path,PATH_MAX);
1030       }
1031     if ((count > 0) && (count <= (ssize_t) PATH_MAX))
1032       {
1033         execution_path[count]='\0';
1034         (void) CopyMagickString(path,execution_path,extent);
1035       }
1036   }
1037 #endif
1038 #if defined(MAGICKCORE_HAVE__NSGETEXECUTABLEPATH)
1039   {
1040     char
1041       executable_path[PATH_MAX << 1],
1042       execution_path[PATH_MAX+1];
1043 
1044     uint32_t
1045       length;
1046 
1047     length=sizeof(executable_path);
1048     if ((_NSGetExecutablePath(executable_path,&length) == 0) &&
1049         (realpath(executable_path,execution_path) != (char *) NULL))
1050       (void) CopyMagickString(path,execution_path,extent);
1051   }
1052 #endif
1053 #if defined(MAGICKCORE_HAVE_GETEXECNAME)
1054   {
1055     const char
1056       *execution_path;
1057 
1058     execution_path=(const char *) getexecname();
1059     if (execution_path != (const char *) NULL)
1060       {
1061         if (*execution_path != *DirectorySeparator)
1062           (void) ConcatenateMagickString(path,DirectorySeparator,extent);
1063         (void) ConcatenateMagickString(path,execution_path,extent);
1064       }
1065   }
1066 #endif
1067 #if defined(MAGICKCORE_WINDOWS_SUPPORT)
1068   NTGetExecutionPath(path,extent);
1069 #endif
1070 #if defined(__GNU__)
1071   {
1072     char
1073       *program_name;
1074 
1075     ssize_t
1076       count;
1077 
1078     count=0;
1079     program_name=program_invocation_name;
1080     if (*program_invocation_name != '/')
1081       {
1082         size_t
1083           extent;
1084 
1085         extent=strlen(directory)+strlen(program_name)+2;
1086         program_name=AcquireQuantumMemory(extent,sizeof(*program_name));
1087         if (program_name == (char *) NULL)
1088           program_name=program_invocation_name;
1089         else
1090           count=FormatLocaleString(program_name,extent,"%s/%s",directory,
1091             program_invocation_name);
1092       }
1093     if (count != -1)
1094       {
1095         char
1096           execution_path[PATH_MAX+1];
1097 
1098         if (realpath(program_name,execution_path) != (char *) NULL)
1099           (void) CopyMagickString(path,execution_path,extent);
1100       }
1101     if (program_name != program_invocation_name)
1102       program_name=(char *) RelinquishMagickMemory(program_name);
1103   }
1104 #endif
1105 #if defined(__OpenBSD__)
1106   {
1107     extern char
1108       *__progname;
1109 
1110     (void) CopyMagickString(path,__progname,extent);
1111   }
1112 #endif
1113   return(IsPathAccessible(path));
1114 }
1115 
1116 /*
1117 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1118 %                                                                             %
1119 %                                                                             %
1120 %                                                                             %
1121 %   G e t M a g i c k P a g e S i z e                                         %
1122 %                                                                             %
1123 %                                                                             %
1124 %                                                                             %
1125 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1126 %
1127 %  GetMagickPageSize() returns the memory page size.
1128 %
1129 %  The format of the GetMagickPageSize method is:
1130 %
1131 %      ssize_t GetMagickPageSize()
1132 %
1133 */
GetMagickPageSize(void)1134 MagickPrivate ssize_t GetMagickPageSize(void)
1135 {
1136   static ssize_t
1137     page_size = -1;
1138 
1139   if (page_size > 0)
1140     return(page_size);
1141 #if defined(MAGICKCORE_HAVE_SYSCONF) && defined(_SC_PAGE_SIZE)
1142   page_size=(ssize_t) sysconf(_SC_PAGE_SIZE);
1143 #elif defined(MAGICKCORE_HAVE_GETPAGESIZE)
1144   page_size=(ssize_t) getpagesize();
1145 #endif
1146   if (page_size <= 0)
1147     page_size=4096;
1148   return(page_size);
1149 }
1150 
1151 /*
1152 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1153 %                                                                             %
1154 %                                                                             %
1155 %                                                                             %
1156 %   G e t P a t h A t t r i b u t e s                                         %
1157 %                                                                             %
1158 %                                                                             %
1159 %                                                                             %
1160 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1161 %
1162 %  GetPathAttributes() returns attributes (e.g. size of file) about a path.
1163 %
1164 %  The path of the GetPathAttributes method is:
1165 %
1166 %      MagickBooleanType GetPathAttributes(const char *path,void *attributes)
1167 %
1168 %  A description of each parameter follows.
1169 %
1170 %   o  path: the file path.
1171 %
1172 %   o  attributes: the path attributes are returned here.
1173 %
1174 */
GetPathAttributes(const char * path,void * attributes)1175 MagickExport MagickBooleanType GetPathAttributes(const char *path,
1176   void *attributes)
1177 {
1178   MagickBooleanType
1179     status;
1180 
1181   if (path == (const char *) NULL)
1182     {
1183       errno=EINVAL;
1184       return(MagickFalse);
1185     }
1186   (void) memset(attributes,0,sizeof(struct stat));
1187   status=stat_utf8(path,(struct stat *) attributes) == 0 ? MagickTrue :
1188     MagickFalse;
1189   return(status);
1190 }
1191 
1192 /*
1193 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1194 %                                                                             %
1195 %                                                                             %
1196 %                                                                             %
1197 %   G e t P a t h C o m p o n e n t                                           %
1198 %                                                                             %
1199 %                                                                             %
1200 %                                                                             %
1201 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1202 %
1203 %  GetPathComponent() returns the parent directory name, filename, basename, or
1204 %  extension of a file path.
1205 %
1206 %  The component string pointed to must have at least MagickPathExtent space
1207 %  for the results to be stored.
1208 %
1209 %  The format of the GetPathComponent function is:
1210 %
1211 %      GetPathComponent(const char *path,PathType type,char *component)
1212 %
1213 %  A description of each parameter follows:
1214 %
1215 %    o path: Specifies a pointer to a character array that contains the
1216 %      file path.
1217 %
1218 %    o type: Specififies which file path component to return.
1219 %
1220 %    o component: the selected file path component is returned here.
1221 %
1222 */
GetPathComponent(const char * path,PathType type,char * component)1223 MagickExport void GetPathComponent(const char *path,PathType type,
1224   char *component)
1225 {
1226   char
1227     *q;
1228 
1229   char
1230     *p;
1231 
1232   size_t
1233     magick_length,
1234     subimage_offset,
1235     subimage_length;
1236 
1237   assert(path != (const char *) NULL);
1238   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",path);
1239   assert(component != (char *) NULL);
1240   if (*path == '\0')
1241     {
1242       *component='\0';
1243       return;
1244     }
1245   (void) CopyMagickString(component,path,MagickPathExtent);
1246   subimage_length=0;
1247   subimage_offset=0;
1248   if (type != SubcanonicalPath)
1249     {
1250       p=component+strlen(component)-1;
1251       if ((strlen(component) > 2) && (*p == ']'))
1252         {
1253           q=strrchr(component,'[');
1254           if ((q != (char *) NULL) && ((q == component) || (*(q-1) != ']')) &&
1255               (IsPathAccessible(path) == MagickFalse))
1256             {
1257               /*
1258                 Look for scene specification (e.g. img0001.pcd[4]).
1259               */
1260               *p='\0';
1261               if ((IsSceneGeometry(q+1,MagickFalse) == MagickFalse) &&
1262                   (IsGeometry(q+1) == MagickFalse))
1263                 *p=']';
1264               else
1265                 {
1266                   subimage_length=(size_t) (p-q);
1267                   subimage_offset=(size_t) (q-component+1);
1268                   *q='\0';
1269                 }
1270             }
1271         }
1272     }
1273   magick_length=0;
1274 #if defined(__OS2__)
1275   if (path[1] != ":")
1276 #endif
1277   for (p=component; *p != '\0'; p++)
1278   {
1279     if ((*p == '%') && (*(p+1) == '['))
1280       {
1281         /*
1282           Skip over %[...].
1283         */
1284         for (p++; (*p != ']') && (*p != '\0'); p++) ;
1285         if (*p == '\0')
1286           break;
1287       }
1288     if ((p != component) && (*p == ':') && (IsPathDirectory(component) < 0) &&
1289         (IsPathAccessible(component) == MagickFalse))
1290       {
1291         /*
1292           Look for image format specification (e.g. ps3:image).
1293         */
1294         *p='\0';
1295         if (IsMagickConflict(component) != MagickFalse)
1296           *p=':';
1297         else
1298           {
1299             magick_length=(size_t) (p-component+1);
1300             for (q=component; *(++p) != '\0'; q++)
1301               *q=(*p);
1302             *q='\0';
1303           }
1304         break;
1305       }
1306   }
1307   p=component;
1308   if (*p != '\0')
1309     for (p=component+strlen(component)-1; p > component; p--)
1310       if (IsBasenameSeparator(*p) != MagickFalse)
1311         break;
1312   switch (type)
1313   {
1314     case MagickPath:
1315     {
1316       if (magick_length != 0)
1317         (void) CopyMagickString(component,path,magick_length);
1318       else
1319         *component='\0';
1320       break;
1321     }
1322     case RootPath:
1323     {
1324       if (*component != '\0')
1325         {
1326           for (p=component+(strlen(component)-1); p > component; p--)
1327           {
1328             if (IsBasenameSeparator(*p) != MagickFalse)
1329               break;
1330             if (*p == '.')
1331               break;
1332           }
1333           if (*p == '.')
1334             *p='\0';
1335           break;
1336         }
1337     }
1338     case HeadPath:
1339     {
1340       *p='\0';
1341       break;
1342     }
1343     case TailPath:
1344     {
1345       if (IsBasenameSeparator(*p) != MagickFalse)
1346         (void) CopyMagickString(component,p+1,MagickPathExtent);
1347       break;
1348     }
1349     case BasePath:
1350     {
1351       if (IsBasenameSeparator(*p) != MagickFalse)
1352         (void) CopyMagickString(component,p+1,MagickPathExtent);
1353       if (*component != '\0')
1354         for (p=component+(strlen(component)-1); p > component; p--)
1355           if (*p == '.')
1356             {
1357               *p='\0';
1358               break;
1359             }
1360       break;
1361     }
1362     case BasePathSansCompressExtension:
1363     {
1364       char
1365         extension[MagickPathExtent];
1366 
1367       /*
1368         Base path sans any compression extension.
1369       */
1370       GetPathComponent(path,ExtensionPath,extension);
1371       if ((LocaleCompare(extension,"bz2") == 0) ||
1372           (LocaleCompare(extension,"gz") == 0) ||
1373           (LocaleCompare(extension,"svgz") == 0) ||
1374           (LocaleCompare(extension,"wmz") == 0) ||
1375           (LocaleCompare(extension,"Z") == 0))
1376         GetPathComponent(path,BasePath,component);
1377       break;
1378     }
1379     case ExtensionPath:
1380     {
1381       if (IsBasenameSeparator(*p) != MagickFalse)
1382         (void) CopyMagickString(component,p+1,MagickPathExtent);
1383       if (*component != '\0')
1384         for (p=component+strlen(component)-1; p > component; p--)
1385           if (*p == '.')
1386             break;
1387       *component='\0';
1388       if (*p == '.')
1389         (void) CopyMagickString(component,p+1,MagickPathExtent);
1390       break;
1391     }
1392     case SubimagePath:
1393     {
1394       *component='\0';
1395       if ((subimage_length != 0) && (magick_length < subimage_offset))
1396         (void) CopyMagickString(component,path+subimage_offset,subimage_length);
1397       break;
1398     }
1399     case SubcanonicalPath:
1400     case CanonicalPath:
1401     case UndefinedPath:
1402       break;
1403   }
1404 }
1405 
1406 /*
1407 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1408 %                                                                             %
1409 %                                                                             %
1410 %                                                                             %
1411 %  G e t P a t h C o m p o n e n t s                                          %
1412 %                                                                             %
1413 %                                                                             %
1414 %                                                                             %
1415 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1416 %
1417 %  GetPathComponents() returns a list of path components.
1418 %
1419 %  The format of the GetPathComponents method is:
1420 %
1421 %      char **GetPathComponents(const char *path,
1422 %        size_t *number_componenets)
1423 %
1424 %  A description of each parameter follows:
1425 %
1426 %    o path:  Specifies the string to segment into a list.
1427 %
1428 %    o number_components:  return the number of components in the list
1429 %
1430 */
GetPathComponents(const char * path,size_t * number_components)1431 MagickPrivate char **GetPathComponents(const char *path,
1432   size_t *number_components)
1433 {
1434   char
1435     **components;
1436 
1437   const char
1438     *p,
1439     *q;
1440 
1441   ssize_t
1442     i;
1443 
1444   if (path == (char *) NULL)
1445     return((char **) NULL);
1446   *number_components=1;
1447   for (p=path; *p != '\0'; p++)
1448     if (IsBasenameSeparator(*p))
1449       (*number_components)++;
1450   components=(char **) AcquireQuantumMemory((size_t) *number_components+1UL,
1451     sizeof(*components));
1452   if (components == (char **) NULL)
1453     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1454   p=path;
1455   for (i=0; i < (ssize_t) *number_components; i++)
1456   {
1457     for (q=p; *q != '\0'; q++)
1458       if (IsBasenameSeparator(*q))
1459         break;
1460     components[i]=(char *) AcquireQuantumMemory((size_t) (q-p)+MagickPathExtent,
1461       sizeof(**components));
1462     if (components[i] == (char *) NULL)
1463       ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1464     (void) CopyMagickString(components[i],p,(size_t) (q-p+1));
1465     p=q+1;
1466   }
1467   components[i]=(char *) NULL;
1468   return(components);
1469 }
1470 
1471 /*
1472 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1473 %                                                                             %
1474 %                                                                             %
1475 %                                                                             %
1476 %  I s P a t h A c c e s s i b l e                                            %
1477 %                                                                             %
1478 %                                                                             %
1479 %                                                                             %
1480 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1481 %
1482 %  IsPathAccessible() returns MagickTrue if the file as defined by the path is
1483 %  accessible.
1484 %
1485 %  The format of the IsPathAccessible method is:
1486 %
1487 %      MagickBooleanType IsPathAccessible(const char *path)
1488 %
1489 %  A description of each parameter follows.
1490 %
1491 %    o path:  Specifies a path to a file.
1492 %
1493 */
IsPathAccessible(const char * path)1494 MagickExport MagickBooleanType IsPathAccessible(const char *path)
1495 {
1496   MagickBooleanType
1497     status;
1498 
1499   struct stat
1500     attributes;
1501 
1502   if ((path == (const char *) NULL) || (*path == '\0'))
1503     return(MagickFalse);
1504   if (LocaleCompare(path,"-") == 0)
1505     return(MagickTrue);
1506   status=GetPathAttributes(path,&attributes);
1507   if (status == MagickFalse)
1508     return(status);
1509   if (S_ISREG(attributes.st_mode) == 0)
1510     return(MagickFalse);
1511   if (access_utf8(path,F_OK) != 0)
1512     return(MagickFalse);
1513   return(MagickTrue);
1514 }
1515 
1516 /*
1517 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1518 %                                                                             %
1519 %                                                                             %
1520 %                                                                             %
1521 +  I s P a t h D i r e c t o r y                                              %
1522 %                                                                             %
1523 %                                                                             %
1524 %                                                                             %
1525 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1526 %
1527 %  IsPathDirectory() returns -1 if the directory does not exist,  1 is returned
1528 %  if the path represents a directory otherwise 0.
1529 %
1530 %  The format of the IsPathDirectory method is:
1531 %
1532 %      int IsPathDirectory(const char *path)
1533 %
1534 %  A description of each parameter follows.
1535 %
1536 %   o  path:  The directory path.
1537 %
1538 */
IsPathDirectory(const char * path)1539 static int IsPathDirectory(const char *path)
1540 {
1541   MagickBooleanType
1542     status;
1543 
1544   struct stat
1545     attributes;
1546 
1547   if ((path == (const char *) NULL) || (*path == '\0'))
1548     return(MagickFalse);
1549   status=GetPathAttributes(path,&attributes);
1550   if (status == MagickFalse)
1551     return(-1);
1552   if (S_ISDIR(attributes.st_mode) == 0)
1553     return(0);
1554   return(1);
1555 }
1556 
1557 /*
1558 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1559 %                                                                             %
1560 %                                                                             %
1561 %                                                                             %
1562 %   L i s t F i l e s                                                         %
1563 %                                                                             %
1564 %                                                                             %
1565 %                                                                             %
1566 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1567 %
1568 %  ListFiles() reads the directory specified and returns a list of filenames
1569 %  contained in the directory sorted in ascending alphabetic order.
1570 %
1571 %  The format of the ListFiles function is:
1572 %
1573 %      char **ListFiles(const char *directory,const char *pattern,
1574 %        ssize_t *number_entries)
1575 %
1576 %  A description of each parameter follows:
1577 %
1578 %    o filelist: Method ListFiles returns a list of filenames contained
1579 %      in the directory.  If the directory specified cannot be read or it is
1580 %      a file a NULL list is returned.
1581 %
1582 %    o directory: Specifies a pointer to a text string containing a directory
1583 %      name.
1584 %
1585 %    o pattern: Specifies a pointer to a text string containing a pattern.
1586 %
1587 %    o number_entries:  This integer returns the number of filenames in the
1588 %      list.
1589 %
1590 */
1591 
1592 #if defined(__cplusplus) || defined(c_plusplus)
1593 extern "C" {
1594 #endif
1595 
FileCompare(const void * x,const void * y)1596 static int FileCompare(const void *x,const void *y)
1597 {
1598   const char
1599     **p,
1600     **q;
1601 
1602   p=(const char **) x;
1603   q=(const char **) y;
1604   return(LocaleCompare(*p,*q));
1605 }
1606 
1607 #if defined(__cplusplus) || defined(c_plusplus)
1608 }
1609 #endif
1610 
ListFiles(const char * directory,const char * pattern,size_t * number_entries)1611 MagickPrivate char **ListFiles(const char *directory,const char *pattern,
1612   size_t *number_entries)
1613 {
1614   char
1615     **filelist;
1616 
1617   DIR
1618     *current_directory;
1619 
1620   struct dirent
1621     *buffer,
1622     *entry;
1623 
1624   size_t
1625     max_entries;
1626 
1627   /*
1628     Open directory.
1629   */
1630   assert(directory != (const char *) NULL);
1631   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",directory);
1632   assert(pattern != (const char *) NULL);
1633   assert(number_entries != (size_t *) NULL);
1634   *number_entries=0;
1635   current_directory=opendir(directory);
1636   if (current_directory == (DIR *) NULL)
1637     return((char **) NULL);
1638   /*
1639     Allocate filelist.
1640   */
1641   max_entries=2048;
1642   filelist=(char **) AcquireQuantumMemory((size_t) max_entries,
1643     sizeof(*filelist));
1644   if (filelist == (char **) NULL)
1645     {
1646       (void) closedir(current_directory);
1647       return((char **) NULL);
1648     }
1649   /*
1650     Save the current and change to the new directory.
1651   */
1652   buffer=(struct dirent *) AcquireMagickMemory(sizeof(*buffer)+FILENAME_MAX+1);
1653   if (buffer == (struct dirent *) NULL)
1654     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1655   while ((MagickReadDirectory(current_directory,buffer,&entry) == 0) &&
1656          (entry != (struct dirent *) NULL))
1657   {
1658     if ((LocaleCompare(entry->d_name,".") == 0) ||
1659         (LocaleCompare(entry->d_name,"..") == 0))
1660       continue;
1661     if ((IsPathDirectory(entry->d_name) > 0) ||
1662 #if defined(MAGICKCORE_WINDOWS_SUPPORT)
1663         (GlobExpression(entry->d_name,pattern,MagickTrue) != MagickFalse))
1664 #else
1665         (GlobExpression(entry->d_name,pattern,MagickFalse) != MagickFalse))
1666 #endif
1667       {
1668         if (*number_entries >= max_entries)
1669           {
1670             /*
1671               Extend the file list.
1672             */
1673             max_entries<<=1;
1674             filelist=(char **) ResizeQuantumMemory(filelist,(size_t)
1675               max_entries,sizeof(*filelist));
1676             if (filelist == (char **) NULL)
1677               break;
1678           }
1679 #if defined(vms)
1680         {
1681           char
1682             *p;
1683 
1684           p=strchr(entry->d_name,';');
1685           if (p)
1686             *p='\0';
1687           if (*number_entries > 0)
1688             if (LocaleCompare(entry->d_name,filelist[*number_entries-1]) == 0)
1689               continue;
1690         }
1691 #endif
1692         filelist[*number_entries]=(char *) AcquireString(entry->d_name);
1693         (*number_entries)++;
1694       }
1695   }
1696   buffer=(struct dirent *) RelinquishMagickMemory(buffer);
1697   (void) closedir(current_directory);
1698   if (filelist == (char **) NULL)
1699     return((char **) NULL);
1700   /*
1701     Sort filelist in ascending order.
1702   */
1703   qsort((void *) filelist,(size_t) *number_entries,sizeof(*filelist),
1704     FileCompare);
1705   return(filelist);
1706 }
1707 
1708 /*
1709 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1710 %                                                                             %
1711 %                                                                             %
1712 %                                                                             %
1713 %   M a g i c k D e l a y                                                     %
1714 %                                                                             %
1715 %                                                                             %
1716 %                                                                             %
1717 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1718 %
1719 %  MagickDelay() suspends program execution for the number of milliseconds
1720 %  specified.
1721 %
1722 %  The format of the Delay method is:
1723 %
1724 %      void MagickDelay(const MagickSizeType milliseconds)
1725 %
1726 %  A description of each parameter follows:
1727 %
1728 %    o milliseconds: Specifies the number of milliseconds to delay before
1729 %      returning.
1730 %
1731 */
MagickDelay(const MagickSizeType milliseconds)1732 MagickExport void MagickDelay(const MagickSizeType milliseconds)
1733 {
1734   if (milliseconds == 0)
1735     return;
1736 #if defined(MAGICKCORE_HAVE_NANOSLEEP)
1737   {
1738     struct timespec
1739       timer;
1740 
1741     timer.tv_sec=(time_t) (milliseconds/1000);
1742     timer.tv_nsec=(milliseconds % 1000)*1000*1000;
1743     (void) nanosleep(&timer,(struct timespec *) NULL);
1744   }
1745 #elif defined(MAGICKCORE_HAVE_USLEEP)
1746   usleep(1000*milliseconds);
1747 #elif defined(MAGICKCORE_HAVE_SELECT)
1748   {
1749     struct timeval
1750       timer;
1751 
1752     timer.tv_sec=(long) milliseconds/1000;
1753     timer.tv_usec=(long) (milliseconds % 1000)*1000;
1754     (void) select(0,(XFD_SET *) NULL,(XFD_SET *) NULL,(XFD_SET *) NULL,&timer);
1755   }
1756 #elif defined(MAGICKCORE_HAVE_POLL)
1757   (void) poll((struct pollfd *) NULL,0,(int) milliseconds);
1758 #elif defined(MAGICKCORE_WINDOWS_SUPPORT)
1759   Sleep((long) milliseconds);
1760 #elif defined(vms)
1761   {
1762     float
1763       timer;
1764 
1765     timer=milliseconds/1000.0;
1766     lib$wait(&timer);
1767   }
1768 #elif defined(__BEOS__)
1769   snooze(1000*milliseconds);
1770 #else
1771   {
1772     clock_t
1773       time_end;
1774 
1775     time_end=clock()+milliseconds*CLOCKS_PER_SEC/1000;
1776     while (clock() < time_end)
1777     {
1778     }
1779   }
1780 #endif
1781 }
1782 
1783 /*
1784 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1785 %                                                                             %
1786 %                                                                             %
1787 %                                                                             %
1788 %  M u l t i l i n e C e n s u s                                              %
1789 %                                                                             %
1790 %                                                                             %
1791 %                                                                             %
1792 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1793 %
1794 %  MultilineCensus() returns the number of lines within a label.  A line is
1795 %  represented by a \n character.
1796 %
1797 %  The format of the MultilineCenus method is:
1798 %
1799 %      size_t MultilineCensus(const char *label)
1800 %
1801 %  A description of each parameter follows.
1802 %
1803 %   o  label:  This character string is the label.
1804 %
1805 */
MultilineCensus(const char * label)1806 MagickExport size_t MultilineCensus(const char *label)
1807 {
1808   size_t
1809     number_lines;
1810 
1811   /*
1812     Determine the number of lines within this label.
1813   */
1814   if (label == (char *) NULL)
1815     return(0);
1816   for (number_lines=1; *label != '\0'; label++)
1817     if (*label == '\n')
1818       number_lines++;
1819   return(number_lines);
1820 }
1821 
1822 /*
1823 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1824 %                                                                             %
1825 %                                                                             %
1826 %                                                                             %
1827 %   S h r e d F i l e                                                         %
1828 %                                                                             %
1829 %                                                                             %
1830 %                                                                             %
1831 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1832 %
1833 %  ShredFile() overwrites the specified file with zeros or random data and then
1834 %  removes it.  The overwrite is optional and is only required to help keep
1835 %  the contents of the file private.  On the first pass, the file is zeroed.
1836 %  For subsequent passes, random data is written.
1837 %
1838 %  The format of the ShredFile method is:
1839 %
1840 %      MagickBooleanType ShredFile(const char *path)
1841 %
1842 %  A description of each parameter follows.
1843 %
1844 %    o path:  Specifies a path to a file.
1845 %
1846 */
ShredFile(const char * path)1847 MagickPrivate MagickBooleanType ShredFile(const char *path)
1848 {
1849   char
1850     *passes;
1851 
1852   int
1853     file,
1854     status;
1855 
1856   MagickSizeType
1857     length;
1858 
1859   ssize_t
1860     i;
1861 
1862   size_t
1863     quantum;
1864 
1865   struct stat
1866     file_stats;
1867 
1868   if ((path == (const char *) NULL) || (*path == '\0'))
1869     return(MagickFalse);
1870   passes=GetPolicyValue("system:shred");
1871   if (passes == (char *) NULL)
1872     passes=GetEnvironmentValue("MAGICK_SHRED_PASSES");
1873   if (passes == (char *) NULL)
1874     {
1875       /*
1876         Don't shred the file, just remove it.
1877       */
1878       status=remove_utf8(path);
1879       if (status == -1)
1880         {
1881           (void) LogMagickEvent(ExceptionEvent,GetMagickModule(),
1882             "Failed to remove: %s",path);
1883           return(MagickFalse);
1884         }
1885       return(MagickTrue);
1886     }
1887   file=open_utf8(path,O_WRONLY | O_EXCL | O_BINARY,S_MODE);
1888   if (file == -1)
1889     {
1890       /*
1891         Don't shred the file, just remove it.
1892       */
1893       passes=DestroyString(passes);
1894       status=remove_utf8(path);
1895       if (status == -1)
1896         (void) LogMagickEvent(ExceptionEvent,GetMagickModule(),
1897           "Failed to remove: %s",path);
1898       return(MagickFalse);
1899     }
1900   /*
1901     Shred the file.
1902   */
1903   quantum=(size_t) MagickMaxBufferExtent;
1904   if ((fstat(file,&file_stats) == 0) && (file_stats.st_size > 0))
1905     quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent);
1906   length=(MagickSizeType) file_stats.st_size;
1907   for (i=0; i < (ssize_t) StringToInteger(passes); i++)
1908   {
1909     RandomInfo
1910       *random_info;
1911 
1912     MagickOffsetType
1913       j;
1914 
1915     ssize_t
1916       count;
1917 
1918     if (lseek(file,0,SEEK_SET) < 0)
1919       break;
1920     random_info=AcquireRandomInfo();
1921     for (j=0; j < (MagickOffsetType) length; j+=count)
1922     {
1923       StringInfo
1924         *key;
1925 
1926       key=GetRandomKey(random_info,quantum);
1927       if (i == 0)
1928         ResetStringInfo(key);  /* zero on first pass */
1929       count=write(file,GetStringInfoDatum(key),(size_t)
1930         MagickMin((MagickSizeType) quantum,length-j));
1931       key=DestroyStringInfo(key);
1932       if (count <= 0)
1933         {
1934           count=0;
1935           if (errno != EINTR)
1936             break;
1937         }
1938     }
1939     random_info=DestroyRandomInfo(random_info);
1940     if (j < (MagickOffsetType) length)
1941       break;
1942   }
1943   status=close(file);
1944   status=remove_utf8(path);
1945   if (status != -1)
1946     status=StringToInteger(passes);
1947   passes=DestroyString(passes);
1948   return((status == -1 || i < (ssize_t) status) ? MagickFalse : MagickTrue);
1949 }
1950