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