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) && ((q == component) || (*(q-1) != ']')) &&
1280 (IsPathAccessible(path) == MagickFalse))
1281 {
1282 /*
1283 Look for scene specification (e.g. img0001.pcd[4]).
1284 */
1285 *p='\0';
1286 if ((IsSceneGeometry(q+1,MagickFalse) == MagickFalse) &&
1287 (IsGeometry(q+1) == MagickFalse))
1288 *p=']';
1289 else
1290 {
1291 subimage_length=(size_t) (p-q);
1292 subimage_offset=(size_t) (q-component+1);
1293 *q='\0';
1294 }
1295 }
1296 }
1297 }
1298 magick_length=0;
1299#if defined(__OS2__)
1300 if (path[1] != ":")
1301#endif
1302 for (p=component; *p != '\0'; p++)
1303 {
1304 if ((*p == '%') && (*(p+1) == '['))
1305 {
1306 /*
1307 Skip over %[...].
1308 */
1309 for (p++; (*p != ']') && (*p != '\0'); p++) ;
1310 if (*p == '\0')
1311 break;
1312 }
1313 if ((p != component) && (*p == ':') && (IsPathDirectory(component) < 0) &&
1314 (IsPathAccessible(component) == MagickFalse))
1315 {
1316 /*
1317 Look for image format specification (e.g. ps3:image).
1318 */
1319 *p='\0';
1320 if (IsMagickConflict(component) != MagickFalse)
1321 *p=':';
1322 else
1323 {
1324 magick_length=(size_t) (p-component+1);
1325 for (q=component; *(++p) != '\0'; q++)
1326 *q=(*p);
1327 *q='\0';
1328 }
1329 break;
1330 }
1331 }
1332 p=component;
1333 if (*p != '\0')
1334 for (p=component+strlen(component)-1; p > component; p--)
1335 if (IsBasenameSeparator(*p) != MagickFalse)
1336 break;
1337 switch (type)
1338 {
1339 case MagickPath:
1340 {
1341 if (magick_length != 0)
1342 (void) CopyMagickString(component,path,magick_length);
1343 else
1344 *component='\0';
1345 break;
1346 }
1347 case RootPath:
1348 {
1349 if (*component != '\0')
1350 {
1351 for (p=component+(strlen(component)-1); p > component; p--)
1352 {
1353 if (IsBasenameSeparator(*p) != MagickFalse)
1354 break;
1355 if (*p == '.')
1356 break;
1357 }
1358 if (*p == '.')
1359 *p='\0';
1360 break;
1361 }
1362 magick_fallthrough;
1363 }
1364 case HeadPath:
1365 {
1366 *p='\0';
1367 break;
1368 }
1369 case TailPath:
1370 {
1371 if (IsBasenameSeparator(*p) != MagickFalse)
1372 (void) CopyMagickString(component,p+1,MagickPathExtent);
1373 break;
1374 }
1375 case BasePath:
1376 {
1377 if (IsBasenameSeparator(*p) != MagickFalse)
1378 (void) CopyMagickString(component,p+1,MagickPathExtent);
1379 if (*component != '\0')
1380 for (p=component+(strlen(component)-1); p > component; p--)
1381 if (*p == '.')
1382 {
1383 *p='\0';
1384 break;
1385 }
1386 break;
1387 }
1388 case BasePathSansCompressExtension:
1389 {
1390 char
1391 extension[MagickPathExtent];
1392
1393 /*
1394 Base path sans any compression extension.
1395 */
1396 GetPathComponent(path,ExtensionPath,extension);
1397 if ((LocaleCompare(extension,"bz2") == 0) ||
1398 (LocaleCompare(extension,"gz") == 0) ||
1399 (LocaleCompare(extension,"svgz") == 0) ||
1400 (LocaleCompare(extension,"wmz") == 0) ||
1401 (LocaleCompare(extension,"Z") == 0))
1402 GetPathComponent(path,BasePath,component);
1403 break;
1404 }
1405 case ExtensionPath:
1406 {
1407 if (IsBasenameSeparator(*p) != MagickFalse)
1408 (void) CopyMagickString(component,p+1,MagickPathExtent);
1409 if (*component != '\0')
1410 for (p=component+strlen(component)-1; p > component; p--)
1411 if (*p == '.')
1412 break;
1413 *component='\0';
1414 if (*p == '.')
1415 (void) CopyMagickString(component,p+1,MagickPathExtent);
1416 break;
1417 }
1418 case SubimagePath:
1419 {
1420 *component='\0';
1421 if ((subimage_length != 0) && (magick_length < subimage_offset))
1422 (void) CopyMagickString(component,path+subimage_offset,subimage_length);
1423 break;
1424 }
1425 case SubcanonicalPath:
1426 case CanonicalPath:
1427 case UndefinedPath:
1428 break;
1429 }
1430}
1431␌
1432/*
1433%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1434% %
1435% %
1436% %
1437% G e t P a t h C o m p o n e n t s %
1438% %
1439% %
1440% %
1441%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1442%
1443% GetPathComponents() returns a list of path components.
1444%
1445% The format of the GetPathComponents method is:
1446%
1447% char **GetPathComponents(const char *path,
1448% size_t *number_components)
1449%
1450% A description of each parameter follows:
1451%
1452% o path: Specifies the string to segment into a list.
1453%
1454% o number_components: return the number of components in the list
1455%
1456*/
1457MagickPrivate char **GetPathComponents(const char *path,
1458 size_t *number_components)
1459{
1460 char
1461 **components;
1462
1463 const char
1464 *p,
1465 *q;
1466
1467 ssize_t
1468 i;
1469
1470 if (path == (char *) NULL)
1471 return((char **) NULL);
1472 *number_components=1;
1473 for (p=path; *p != '\0'; p++)
1474 if (IsBasenameSeparator(*p))
1475 (*number_components)++;
1476 components=(char **) AcquireQuantumMemory((size_t) *number_components+1UL,
1477 sizeof(*components));
1478 if (components == (char **) NULL)
1479 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1480 p=path;
1481 for (i=0; i < (ssize_t) *number_components; i++)
1482 {
1483 for (q=p; *q != '\0'; q++)
1484 if (IsBasenameSeparator(*q))
1485 break;
1486 components[i]=(char *) AcquireQuantumMemory((size_t) (q-p)+MagickPathExtent,
1487 sizeof(**components));
1488 if (components[i] == (char *) NULL)
1489 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1490 (void) CopyMagickString(components[i],p,(size_t) (q-p+1));
1491 p=q+1;
1492 }
1493 components[i]=(char *) NULL;
1494 return(components);
1495}
1496␌
1497/*
1498%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1499% %
1500% %
1501% %
1502% G e t P a t h T e m p l a t e %
1503% %
1504% %
1505% %
1506%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1507%
1508% GetPathTemplate() constructs a template for a temporary filename.
1509%
1510% The format of the GetPathComponent function is:
1511%
1512% MagickBooleanType GetPathComponent(const char *path)
1513%
1514% A description of each parameter follows:
1515%
1516% o path: Specifies a pointer to a character array populated with the
1517% file path template.
1518%
1519%
1520*/
1521MagickExport MagickBooleanType GetPathTemplate(char *path)
1522{
1523 char
1524 *directory,
1525 *value;
1526
1528 *exception;
1529
1530 MagickBooleanType
1531 status;
1532
1533 struct stat
1534 attributes;
1535
1536 (void) FormatLocaleString(path,MagickPathExtent,"magick-"
1537 MagickPathTemplate);
1538 exception=AcquireExceptionInfo();
1539 directory=(char *) GetImageRegistry(StringRegistryType,"temporary-path",
1540 exception);
1541 exception=DestroyExceptionInfo(exception);
1542 if (directory == (char *) NULL)
1543 directory=GetEnvironmentValue("MAGICK_TEMPORARY_PATH");
1544 if (directory == (char *) NULL)
1545 directory=GetEnvironmentValue("MAGICK_TMPDIR");
1546 if (directory == (char *) NULL)
1547 directory=GetEnvironmentValue("TMPDIR");
1548#if defined(MAGICKCORE_WINDOWS_SUPPORT) || defined(__OS2__) || defined(__CYGWIN__)
1549 if (directory == (char *) NULL)
1550 directory=GetEnvironmentValue("TMP");
1551 if (directory == (char *) NULL)
1552 directory=GetEnvironmentValue("TEMP");
1553#endif
1554#if defined(__VMS)
1555 if (directory == (char *) NULL)
1556 directory=GetEnvironmentValue("MTMPDIR");
1557#endif
1558#if defined(P_tmpdir)
1559 if (directory == (char *) NULL)
1560 directory=ConstantString(P_tmpdir);
1561#endif
1562 if (directory == (char *) NULL)
1563 return(MagickFalse);
1564 value=GetPolicyValue("resource:temporary-path");
1565 if (value != (char *) NULL)
1566 {
1567 (void) CloneString(&directory,value);
1568 value=DestroyString(value);
1569 }
1570 if (strlen(directory) > (MagickPathExtent-25))
1571 {
1572 directory=DestroyString(directory);
1573 return(MagickFalse);
1574 }
1575 status=GetPathAttributes(directory,&attributes);
1576 if ((status == MagickFalse) || !S_ISDIR(attributes.st_mode))
1577 {
1578 directory=DestroyString(directory);
1579 return(MagickFalse);
1580 }
1581 if (directory[strlen(directory)-1] == *DirectorySeparator)
1582 (void) FormatLocaleString(path,MagickPathExtent,"%smagick-"
1583 MagickPathTemplate,directory);
1584 else
1585 (void) FormatLocaleString(path,MagickPathExtent,
1586 "%s%smagick-" MagickPathTemplate,directory,DirectorySeparator);
1587 directory=DestroyString(directory);
1588#if defined(MAGICKCORE_WINDOWS_SUPPORT)
1589 {
1590 char
1591 *p;
1592
1593 /*
1594 Ghostscript does not like backslashes so we need to replace them. The
1595 forward slash also works under Windows.
1596 */
1597 for (p=(path[1] == *DirectorySeparator ? path+2 : path); *p != '\0'; p++)
1598 if (*p == *DirectorySeparator)
1599 *p='/';
1600 }
1601#endif
1602 return(MagickTrue);
1603}
1604␌
1605/*
1606%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1607% %
1608% %
1609% %
1610% I s P a t h A c c e s s i b l e %
1611% %
1612% %
1613% %
1614%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1615%
1616% IsPathAccessible() returns MagickTrue if the file as defined by the path is
1617% accessible.
1618%
1619% The format of the IsPathAccessible method is:
1620%
1621% MagickBooleanType IsPathAccessible(const char *path)
1622%
1623% A description of each parameter follows.
1624%
1625% o path: Specifies a path to a file.
1626%
1627*/
1628MagickExport MagickBooleanType IsPathAccessible(const char *path)
1629{
1630 MagickBooleanType
1631 status;
1632
1633 struct stat
1634 attributes;
1635
1636 if ((path == (const char *) NULL) || (*path == '\0'))
1637 return(MagickFalse);
1638 if (LocaleCompare(path,"-") == 0)
1639 return(MagickTrue);
1640 status=GetPathAttributes(path,&attributes);
1641 if (status == MagickFalse)
1642 return(status);
1643 if (S_ISREG(attributes.st_mode) == 0)
1644 return(MagickFalse);
1645 if (access_utf8(path,F_OK) != 0)
1646 return(MagickFalse);
1647 return(MagickTrue);
1648}
1649␌
1650/*
1651%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1652% %
1653% %
1654% %
1655+ I s P a t h D i r e c t o r y %
1656% %
1657% %
1658% %
1659%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1660%
1661% IsPathDirectory() returns -1 if the directory does not exist, 1 is returned
1662% if the path represents a directory otherwise 0.
1663%
1664% The format of the IsPathDirectory method is:
1665%
1666% int IsPathDirectory(const char *path)
1667%
1668% A description of each parameter follows.
1669%
1670% o path: The directory path.
1671%
1672*/
1673static int IsPathDirectory(const char *path)
1674{
1675 MagickBooleanType
1676 status;
1677
1678 struct stat
1679 attributes;
1680
1681 if ((path == (const char *) NULL) || (*path == '\0'))
1682 return(MagickFalse);
1683 status=GetPathAttributes(path,&attributes);
1684 if (status == MagickFalse)
1685 return(-1);
1686 if (S_ISDIR(attributes.st_mode) == 0)
1687 return(0);
1688 return(1);
1689}
1690␌
1691/*
1692%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1693% %
1694% %
1695% %
1696% L i s t F i l e s %
1697% %
1698% %
1699% %
1700%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1701%
1702% ListFiles() reads the directory specified and returns a list of filenames
1703% contained in the directory sorted in ascending alphabetic order.
1704%
1705% The format of the ListFiles function is:
1706%
1707% char **ListFiles(const char *directory,const char *pattern,
1708% ssize_t *number_entries)
1709%
1710% A description of each parameter follows:
1711%
1712% o filelist: Method ListFiles returns a list of filenames contained
1713% in the directory. If the directory specified cannot be read or it is
1714% a file a NULL list is returned.
1715%
1716% o directory: Specifies a pointer to a text string containing a directory
1717% name.
1718%
1719% o pattern: Specifies a pointer to a text string containing a pattern.
1720%
1721% o number_entries: This integer returns the number of filenames in the
1722% list.
1723%
1724*/
1725
1726#if defined(__cplusplus) || defined(c_plusplus)
1727extern "C" {
1728#endif
1729
1730static int FileCompare(const void *x,const void *y)
1731{
1732 const char
1733 **p,
1734 **q;
1735
1736 p=(const char **) x;
1737 q=(const char **) y;
1738 return(LocaleCompare(*p,*q));
1739}
1740
1741#if defined(__cplusplus) || defined(c_plusplus)
1742}
1743#endif
1744
1745MagickPrivate char **ListFiles(const char *directory,const char *pattern,
1746 size_t *number_entries)
1747{
1748 char
1749 **filelist;
1750
1751 DIR
1752 *current_directory;
1753
1754 struct dirent
1755 *buffer,
1756 *entry;
1757
1758 size_t
1759 max_entries;
1760
1761 /*
1762 Open directory.
1763 */
1764 assert(directory != (const char *) NULL);
1765 assert(pattern != (const char *) NULL);
1766 assert(number_entries != (size_t *) NULL);
1767 if (IsEventLogging() != MagickFalse)
1768 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",directory);
1769 *number_entries=0;
1770 current_directory=opendir(directory);
1771 if (current_directory == (DIR *) NULL)
1772 return((char **) NULL);
1773 /*
1774 Allocate filelist.
1775 */
1776 max_entries=2048;
1777 filelist=(char **) AcquireQuantumMemory((size_t) max_entries,
1778 sizeof(*filelist));
1779 if (filelist == (char **) NULL)
1780 {
1781 (void) closedir(current_directory);
1782 return((char **) NULL);
1783 }
1784 /*
1785 Save the current and change to the new directory.
1786 */
1787 buffer=(struct dirent *) AcquireMagickMemory(sizeof(*buffer)+FILENAME_MAX+1);
1788 if (buffer == (struct dirent *) NULL)
1789 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1790 while ((MagickReadDirectory(current_directory,buffer,&entry) == 0) &&
1791 (entry != (struct dirent *) NULL))
1792 {
1793 if ((LocaleCompare(entry->d_name,".") == 0) ||
1794 (LocaleCompare(entry->d_name,"..") == 0))
1795 continue;
1796 if ((IsPathDirectory(entry->d_name) > 0) ||
1797#if defined(MAGICKCORE_WINDOWS_SUPPORT)
1798 (GlobExpression(entry->d_name,pattern,MagickTrue) != MagickFalse))
1799#else
1800 (GlobExpression(entry->d_name,pattern,MagickFalse) != MagickFalse))
1801#endif
1802 {
1803 if (*number_entries >= max_entries)
1804 {
1805 /*
1806 Extend the file list.
1807 */
1808 max_entries<<=1;
1809 filelist=(char **) ResizeQuantumMemory(filelist,(size_t)
1810 max_entries,sizeof(*filelist));
1811 if (filelist == (char **) NULL)
1812 break;
1813 }
1814#if defined(vms)
1815 {
1816 char
1817 *p;
1818
1819 p=strchr(entry->d_name,';');
1820 if (p)
1821 *p='\0';
1822 if (*number_entries > 0)
1823 if (LocaleCompare(entry->d_name,filelist[*number_entries-1]) == 0)
1824 continue;
1825 }
1826#endif
1827 filelist[*number_entries]=(char *) AcquireString(entry->d_name);
1828 (*number_entries)++;
1829 }
1830 }
1831 buffer=(struct dirent *) RelinquishMagickMemory(buffer);
1832 (void) closedir(current_directory);
1833 if (filelist == (char **) NULL)
1834 return((char **) NULL);
1835 /*
1836 Sort filelist in ascending order.
1837 */
1838 qsort((void *) filelist,(size_t) *number_entries,sizeof(*filelist),
1839 FileCompare);
1840 return(filelist);
1841}
1842␌
1843/*
1844%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1845% %
1846% %
1847% %
1848% M a g i c k D e l a y %
1849% %
1850% %
1851% %
1852%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1853%
1854% MagickDelay() suspends program execution for the number of milliseconds
1855% specified.
1856%
1857% The format of the Delay method is:
1858%
1859% void MagickDelay(const MagickSizeType milliseconds)
1860%
1861% A description of each parameter follows:
1862%
1863% o milliseconds: Specifies the number of milliseconds to delay before
1864% returning.
1865%
1866*/
1867MagickExport void MagickDelay(const MagickSizeType milliseconds)
1868{
1869 if (milliseconds == 0)
1870 return;
1871#if defined(MAGICKCORE_HAVE_NANOSLEEP)
1872 {
1873 struct timespec
1874 timer;
1875
1876 timer.tv_sec=(time_t) (milliseconds/1000);
1877 timer.tv_nsec=(time_t) ((milliseconds % 1000)*1000*1000);
1878 (void) nanosleep(&timer,(struct timespec *) NULL);
1879 }
1880#elif defined(MAGICKCORE_HAVE_USLEEP)
1881 usleep(1000*milliseconds);
1882#elif defined(MAGICKCORE_HAVE_SELECT)
1883 {
1884 struct timeval
1885 timer;
1886
1887 timer.tv_sec=(long) milliseconds/1000;
1888 timer.tv_usec=(long) (milliseconds % 1000)*1000;
1889 (void) select(0,(XFD_SET *) NULL,(XFD_SET *) NULL,(XFD_SET *) NULL,&timer);
1890 }
1891#elif defined(MAGICKCORE_HAVE_POLL)
1892 (void) poll((struct pollfd *) NULL,0,(int) milliseconds);
1893#elif defined(MAGICKCORE_WINDOWS_SUPPORT)
1894 Sleep((long) milliseconds);
1895#elif defined(vms)
1896 {
1897 float
1898 timer;
1899
1900 timer=milliseconds/1000.0;
1901 lib$wait(&timer);
1902 }
1903#elif defined(__BEOS__)
1904 snooze(1000*milliseconds);
1905#else
1906 {
1907 clock_t
1908 time_end;
1909
1910 time_end=clock()+milliseconds*CLOCKS_PER_SEC/1000;
1911 while (clock() < time_end)
1912 {
1913 }
1914 }
1915#endif
1916}
1917␌
1918/*
1919%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1920% %
1921% %
1922% %
1923% M u l t i l i n e C e n s u s %
1924% %
1925% %
1926% %
1927%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1928%
1929% MultilineCensus() returns the number of lines within a label. A line is
1930% represented by a \n character.
1931%
1932% The format of the MultilineCensus method is:
1933%
1934% size_t MultilineCensus(const char *label)
1935%
1936% A description of each parameter follows.
1937%
1938% o label: This character string is the label.
1939%
1940*/
1941MagickExport size_t MultilineCensus(const char *label)
1942{
1943 size_t
1944 number_lines;
1945
1946 /*
1947 Determine the number of lines within this label.
1948 */
1949 if (label == (char *) NULL)
1950 return(0);
1951 for (number_lines=1; *label != '\0'; label++)
1952 if (*label == '\n')
1953 number_lines++;
1954 return(number_lines);
1955}
1956␌
1957/*
1958%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1959% %
1960% %
1961% %
1962% S h r e d F i l e %
1963% %
1964% %
1965% %
1966%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1967%
1968% ShredFile() overwrites the specified file with random data. The overwrite is
1969% optional and is only required to help keep the contents of the file private.
1970%
1971% The format of the ShredFile method is:
1972%
1973% MagickBooleanType ShredFile(const char *path)
1974%
1975% A description of each parameter follows.
1976%
1977% o path: Specifies a path to a file.
1978%
1979*/
1980MagickPrivate MagickBooleanType ShredFile(const char *path)
1981{
1982 int
1983 file,
1984 status;
1985
1986 MagickSizeType
1987 length;
1988
1990 *random_info;
1991
1992 size_t
1993 quantum;
1994
1995 ssize_t
1996 i;
1997
1998 static ssize_t
1999 passes = -1;
2000
2002 *key;
2003
2004 struct stat
2005 file_stats;
2006
2007 if ((path == (const char *) NULL) || (*path == '\0'))
2008 return(MagickFalse);
2009 if (passes == -1)
2010 {
2011 char
2012 *property;
2013
2014 passes=0;
2015 property=GetEnvironmentValue("MAGICK_SHRED_PASSES");
2016 if (property != (char *) NULL)
2017 {
2018 passes=(ssize_t) StringToInteger(property);
2019 property=DestroyString(property);
2020 }
2021 property=GetPolicyValue("system:shred");
2022 if (property != (char *) NULL)
2023 {
2024 passes=(ssize_t) StringToInteger(property);
2025 property=DestroyString(property);
2026 }
2027 }
2028 if (passes == 0)
2029 return(MagickTrue);
2030 /*
2031 Shred the file.
2032 */
2033 file=open_utf8(path,O_WRONLY | O_EXCL | O_BINARY,S_MODE);
2034 if (file == -1)
2035 return(MagickFalse);
2036 quantum=(size_t) MagickMinBufferExtent;
2037 if ((fstat(file,&file_stats) == 0) && (file_stats.st_size > 0))
2038 quantum=(size_t) MagickMin(file_stats.st_size,MagickMinBufferExtent);
2039 length=(MagickSizeType) file_stats.st_size;
2040 random_info=AcquireRandomInfo();
2041 key=GetRandomKey(random_info,quantum);
2042 for (i=0; i < passes; i++)
2043 {
2044 MagickOffsetType
2045 j;
2046
2047 ssize_t
2048 count;
2049
2050 if (lseek(file,0,SEEK_SET) < 0)
2051 break;
2052 for (j=0; j < (MagickOffsetType) length; j+=count)
2053 {
2054 if (i != 0)
2055 SetRandomKey(random_info,quantum,GetStringInfoDatum(key));
2056 count=write(file,GetStringInfoDatum(key),(size_t)
2057 MagickMin((MagickOffsetType) quantum,(MagickOffsetType) length-j));
2058 if (count <= 0)
2059 {
2060 count=0;
2061 if (errno != EINTR)
2062 break;
2063 }
2064 }
2065 if (j < (MagickOffsetType) length)
2066 break;
2067 }
2068 key=DestroyStringInfo(key);
2069 random_info=DestroyRandomInfo(random_info);
2070 status=close_utf8(file);
2071 return((status == -1 || i < passes) ? MagickFalse : MagickTrue);
2072}