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