Imported Upstream version 4.0.18
[platform/upstream/mtools.git] / mainloop.c
1 /*  Copyright 1997-2002,2005-2009 Alain Knaff.
2  *  This file is part of mtools.
3  *
4  *  Mtools is free software: you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation, either version 3 of the License, or
7  *  (at your option) any later version.
8  *
9  *  Mtools is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License
15  *  along with Mtools.  If not, see <http://www.gnu.org/licenses/>.
16  *
17  * mainloop.c
18  * Iterating over all the command line parameters, and matching patterns
19  * where needed
20  */
21
22 #include "sysincludes.h"
23 #include "msdos.h"
24 #include "mtools.h"
25 #include "vfat.h"
26 #include "fs.h"
27 #include "mainloop.h"
28 #include "plain_io.h"
29 #include "file.h"
30 #include "file_name.h"
31
32
33 /* Fix the info in the MCWD file to be a proper directory name.
34  * Always has a leading separator.  Never has a trailing separator
35  * (unless it is the path itself).  */
36
37 static const char *fix_mcwd(char *ans)
38 {
39         FILE *fp;
40         char *s;
41         char buf[MAX_PATH];
42
43         fp = open_mcwd("r");
44         if(!fp || !fgets(buf, MAX_PATH, fp)) {
45                 if(fp)
46                         fclose(fp);
47                 ans[0] = get_default_drive();
48                 strcpy(ans+1, ":/");
49                 return ans;
50         }
51
52         buf[strlen(buf) -1] = '\0';
53         fclose(fp);
54                                         /* drive letter present? */
55         s = buf;
56         if (buf[0] && buf[1] == ':') {
57                 strncpy(ans, buf, 2);
58                 ans[2] = '\0';
59                 s = &buf[2];
60         } else {
61                 ans[0] = get_default_drive();
62                 strcpy(ans+1, ":");
63         }
64                         /* add a leading separator */
65         if (*s != '/' && *s != '\\') {
66                 strcat(ans, "/");
67                 strcat(ans, s);
68         } else
69                 strcat(ans, s);
70
71 #if 0
72                                         /* translate to upper case */
73         for (s = ans; *s; ++s) {
74                 *s = toupper(*s);
75                 if (*s == '\\')
76                         *s = '/';
77         }
78 #endif
79                                         /* if only drive, colon, & separator */
80         if (strlen(ans) == 3)
81                 return(ans);
82                                         /* zap the trailing separator */
83         if (*--s == '/')
84                 *s = '\0';
85         return ans;
86 }
87
88 int unix_dir_loop(Stream_t *Stream, MainParam_t *mp); 
89 int unix_loop(UNUSED(Stream_t *Stream), MainParam_t *mp, char *arg,
90               int follow_dir_link);
91
92 static int _unix_loop(Stream_t *Dir, MainParam_t *mp,
93                       const char *filename UNUSEDP)
94 {
95         return unix_dir_loop(Dir, mp);
96 }
97
98 int unix_loop(UNUSED(Stream_t *Stream), MainParam_t *mp,
99               char *arg, int follow_dir_link)
100 {
101         int ret;
102         int isdir;
103         int unixNameLength;
104
105         mp->File = NULL;
106         mp->direntry = NULL;
107         unixNameLength = strlen(arg);
108         if(unixNameLength > 1 && arg[unixNameLength-1] == '/') {
109             /* names ending in slash, and having at least two characters */
110             char *name = strdup(arg);
111             name[unixNameLength-1]='\0';
112             mp->unixSourceName = name;
113         } else {
114             mp->unixSourceName = arg;
115         }
116         /*      mp->dir.attr = ATTR_ARCHIVE;*/
117         mp->loop = _unix_loop;
118         if((mp->lookupflags & DO_OPEN)){
119                 mp->File = SimpleFileOpen(0, 0, arg, O_RDONLY, 0, 0, 0, 0);
120                 if(!mp->File){
121                         perror(arg);
122 #if 0
123                         tmp = _basename(arg);
124                         strncpy(mp->filename, tmp, VBUFSIZE);
125                         mp->filename[VBUFSIZE-1] = '\0';
126 #endif
127                         return ERROR_ONE;
128                 }
129                 GET_DATA(mp->File, 0, 0, &isdir, 0);
130                 if(isdir) {
131 #if !defined(__EMX__) && !defined(OS_mingw32msvc)
132                         struct MT_STAT buf;
133 #endif
134
135                         FREE(&mp->File);
136 #if !defined(__EMX__) && !defined(OS_mingw32msvc)
137                         if(!follow_dir_link &&
138                            MT_LSTAT(arg, &buf) == 0 &&
139                            S_ISLNK(buf.st_mode)) {
140                                 /* skip links to directories in order to avoid
141                                  * infinite loops */
142                                 fprintf(stderr,
143                                         "skipping directory symlink %s\n",
144                                         arg);
145                                 return 0;                               
146                         }
147 #endif
148                         if(! (mp->lookupflags & ACCEPT_DIR))
149                                 return 0;
150                         mp->File = OpenDir(arg);
151                 }
152         }
153
154         if(isdir)
155                 ret = mp->dirCallback(0, mp);
156         else
157                 ret = mp->unixcallback(mp);
158         FREE(&mp->File);
159         return ret;
160 }
161
162
163 int isSpecial(const char *name)
164 {
165         if(name[0] == '\0')
166                 return 1;
167         if(!strcmp(name,"."))
168                 return 1;
169         if(!strcmp(name,".."))
170                 return 1;
171         return 0;                       
172 }
173
174 #ifdef HAVE_WCHAR_H
175 int isSpecialW(const wchar_t *name)
176 {
177         if(name[0] == '\0')
178                 return 1;
179         if(!wcscmp(name,L"."))
180                 return 1;
181         if(!wcscmp(name,L".."))
182                 return 1;
183         return 0;                       
184 }
185 #endif
186
187 static int checkForDot(int lookupflags, const wchar_t *name)
188 {
189         return (lookupflags & NO_DOTS) && isSpecialW(name);
190 }
191
192
193 typedef struct lookupState_t {
194         Stream_t *container;
195         int nbContainers;
196         Stream_t *Dir;
197         int nbDirs;
198         const char *filename;
199 } lookupState_t;
200
201 static int isUniqueTarget(const char *name)
202 {
203         return name && strcmp(name, "-");
204 }
205
206 static int handle_leaf(direntry_t *direntry, MainParam_t *mp,
207                        lookupState_t *lookupState)
208 {
209         Stream_t *MyFile=0;
210         int ret;
211
212         if(got_signal)
213                 return ERROR_ONE;
214         if(lookupState) {
215                 /* we are looking for a "target" file */
216                 switch(lookupState->nbDirs) {
217                         case 0: /* no directory yet, open it */
218                                 lookupState->Dir = OpenFileByDirentry(direntry);
219                                 lookupState->nbDirs++;
220                                 /* dump the container, we have
221                                  * better now */
222                                 FREE(&lookupState->container);
223                                 return 0;
224                         case 1: /* we have already a directory */
225                                 FREE(&lookupState->Dir);
226                                 fprintf(stderr,"Ambigous\n");
227                                 return STOP_NOW | ERROR_ONE;
228                         default:
229                                 return STOP_NOW | ERROR_ONE;
230                 }
231         }
232
233         mp->direntry = direntry;
234         if(IS_DIR(direntry)) {
235                 if(mp->lookupflags & (DO_OPEN | DO_OPEN_DIRS))
236                         MyFile = mp->File = OpenFileByDirentry(direntry);
237                 ret = mp->dirCallback(direntry, mp);
238         } else {
239                 if(mp->lookupflags & DO_OPEN)
240                         MyFile = mp->File = OpenFileByDirentry(direntry);
241                 ret = mp->callback(direntry, mp);
242         }
243         FREE(&MyFile);
244         if(isUniqueTarget(mp->targetName))
245                 ret |= STOP_NOW;
246         return ret;
247 }
248
249 static int _dos_loop(Stream_t *Dir, MainParam_t *mp, const char *filename)
250 {       
251         Stream_t *MyFile=0;
252         direntry_t entry;
253         int ret;
254         int r;
255
256         ret = 0;
257         r=0;
258         initializeDirentry(&entry, Dir);
259         while(!got_signal &&
260               (r=vfat_lookup(&entry, filename, -1,
261                              mp->lookupflags, mp->shortname,
262                              mp->longname)) == 0 ){
263                 mp->File = NULL;
264                 if(!checkForDot(mp->lookupflags,entry.name)) {
265                         MyFile = 0;
266                         if((mp->lookupflags & DO_OPEN) ||
267                            (IS_DIR(&entry) &&
268                             (mp->lookupflags & DO_OPEN_DIRS))) {
269                                 MyFile = mp->File = OpenFileByDirentry(&entry);
270                         }
271                         if(got_signal)
272                                 break;
273                         mp->direntry = &entry;
274                         if(IS_DIR(&entry))
275                                 ret |= mp->dirCallback(&entry,mp);
276                         else
277                                 ret |= mp->callback(&entry, mp);
278                         FREE(&MyFile);
279                 }
280                 if (fat_error(Dir))
281                         ret |= ERROR_ONE;
282                 if(mp->fast_quit && (ret & ERROR_ONE))
283                         break;
284         }
285         if (r == -2)
286             return ERROR_ONE;
287         if(got_signal)
288                 ret |= ERROR_ONE;
289         return ret;
290 }
291
292 static int recurs_dos_loop(MainParam_t *mp, const char *filename0,
293                            const char *filename1,
294                            lookupState_t *lookupState)
295 {
296         /* Dir is de-allocated by the same entity which allocated it */
297         const char *ptr;
298         direntry_t entry;
299         int length;
300         int lookupflags;
301         int ret;
302         int have_one;
303         int doing_mcwd;
304         int r;
305
306         while(1) {
307                 /* strip dots and / */
308                 if(!strncmp(filename0,"./", 2)) {
309                         filename0 += 2;
310                         continue;
311                 }
312                 if(!strcmp(filename0,".") && filename1) {
313                         filename0 ++;
314                         continue;
315                 }
316                 if(filename0[0] == '/') {
317                         filename0++;
318                         continue;
319                 }
320                 if(!filename0[0]) {
321                         if(!filename1)
322                                 break;
323                         filename0 = filename1;
324                         filename1 = 0;
325                         continue;
326                 }
327                 break;
328         }
329
330         if(!strncmp(filename0,"../", 3) ||
331            (!strcmp(filename0, "..") && filename1)) {
332                 /* up one level */
333                 mp->File = getDirentry(mp->File)->Dir;
334                 return recurs_dos_loop(mp, filename0+2, filename1, lookupState);
335         }
336
337         doing_mcwd = !!filename1;
338
339         ptr = strchr(filename0, '/');
340         if(!ptr) {                      
341                 length = strlen(filename0);             
342                 ptr = filename1;
343                 filename1 = 0;
344         } else {
345                 length = ptr - filename0;
346                 ptr++;
347         }
348         if(!ptr) {
349                 if(mp->lookupflags & OPEN_PARENT) {
350                         mp->targetName = filename0;
351                         ret = handle_leaf(getDirentry(mp->File), mp,
352                                           lookupState);
353                         mp->targetName = 0;
354                         return ret;
355                 }
356                 
357                 if(!strcmp(filename0, ".") || !filename0[0]) {
358                         return handle_leaf(getDirentry(mp->File),
359                                            mp, lookupState);
360                 }
361
362                 if(!strcmp(filename0, "..")) {
363                         return handle_leaf(getParent(getDirentry(mp->File)), mp,
364                                            lookupState);
365                 }
366
367                 lookupflags = mp->lookupflags;
368                 
369                 if(lookupState) {
370                         lookupState->filename = filename0;
371                         if(lookupState->nbContainers + lookupState->nbDirs > 0){
372                                 /* we have already one target, don't bother
373                                  * with this one. */
374                                 FREE(&lookupState->container);
375                         } else {
376                                 /* no match yet.  Remember this container for
377                                  * later use */
378                                 lookupState->container = COPY(mp->File);
379                         }
380                         lookupState->nbContainers++;
381                 }
382         } else
383                 lookupflags = ACCEPT_DIR | DO_OPEN | NO_DOTS;
384
385         ret = 0;
386         r = 0;
387         have_one = 0;
388         initializeDirentry(&entry, mp->File);
389         while(!(ret & STOP_NOW) &&
390               !got_signal &&
391               (r=vfat_lookup(&entry, filename0, length,
392                              lookupflags | NO_MSG,
393                              mp->shortname, mp->longname)) == 0 ){
394                 if(checkForDot(lookupflags, entry.name))
395                         /* while following the path, ignore the
396                          * special entries if they were not
397                          * explicitly given */
398                         continue;
399                 have_one = 1;
400                 if(ptr) {
401                         Stream_t *SubDir;
402                         SubDir = mp->File = OpenFileByDirentry(&entry);
403                         ret |= recurs_dos_loop(mp, ptr, filename1, lookupState);
404                         FREE(&SubDir);
405                 } else {
406                         ret |= handle_leaf(&entry, mp, lookupState);
407                         if(isUniqueTarget(mp->targetName))
408                                 return ret | STOP_NOW;
409                 }
410                 if(doing_mcwd)
411                         break;
412         }
413         if (r == -2)
414                 return ERROR_ONE;
415         if(got_signal)
416                 return ret | ERROR_ONE;
417         if(doing_mcwd && !have_one)
418                 return NO_CWD;
419         return ret;
420 }
421
422 static int common_dos_loop(MainParam_t *mp, const char *pathname,
423                            lookupState_t *lookupState, int open_mode)
424
425 {
426         Stream_t *RootDir;
427         const char *cwd;
428         char drive;
429
430         int ret;
431         mp->loop = _dos_loop;
432         
433         drive='\0';
434         cwd = "";
435         if(*pathname && pathname[1] == ':') {
436                 drive = toupper(*pathname);
437                 pathname += 2;
438                 if(mp->mcwd[0] == drive)
439                         cwd = mp->mcwd+2;
440         } else if(mp->mcwd[0]) {
441                 drive = mp->mcwd[0];
442                 cwd = mp->mcwd+2;
443         } else {
444                 drive = get_default_drive();
445         }
446
447         if(*pathname=='/') /* absolute path name */
448                 cwd = "";
449
450         RootDir = mp->File = open_root_dir(drive, open_mode, NULL);
451         if(!mp->File)
452                 return ERROR_ONE;
453
454         ret = recurs_dos_loop(mp, cwd, pathname, lookupState);
455         if(ret & NO_CWD) {
456                 /* no CWD */
457                 *mp->mcwd = '\0';
458                 unlink_mcwd();
459                 ret = recurs_dos_loop(mp, "", pathname, lookupState);
460         }
461         FREE(&RootDir);
462         return ret;
463 }
464
465 static int dos_loop(MainParam_t *mp, const char *arg)
466 {
467         return common_dos_loop(mp, arg, 0, mp->openflags);
468 }
469
470
471 static int dos_target_lookup(MainParam_t *mp, const char *arg)
472 {
473         lookupState_t lookupState;
474         int ret;
475         int lookupflags;
476
477         lookupState.nbDirs = 0;
478         lookupState.Dir = 0;
479         lookupState.nbContainers = 0;
480         lookupState.container = 0;
481
482         lookupflags = mp->lookupflags;
483         mp->lookupflags = DO_OPEN | ACCEPT_DIR;
484         ret = common_dos_loop(mp, arg, &lookupState, O_RDWR);
485         mp->lookupflags = lookupflags;
486         if(ret & ERROR_ONE)
487                 return ret;
488
489         if(lookupState.nbDirs) {
490                 mp->targetName = 0;
491                 mp->targetDir = lookupState.Dir;
492                 FREE(&lookupState.container); /* container no longer needed */
493                 return ret;
494         }
495
496         switch(lookupState.nbContainers) {
497                 case 0:
498                         /* no match */
499                         fprintf(stderr,"%s: no match for target\n", arg);
500                         return MISSED_ONE;
501                 case 1:
502                         mp->targetName = strdup(lookupState.filename);
503                         mp->targetDir = lookupState.container;
504                         return ret;
505                 default:
506                         /* too much */
507                         fprintf(stderr, "Ambigous %s\n", arg);
508                         return ERROR_ONE;                       
509         }
510 }
511
512 static int unix_target_lookup(MainParam_t *mp, const char *arg)
513 {
514         char *ptr;
515         mp->unixTarget = strdup(arg);
516         /* try complete filename */
517         if(access(mp->unixTarget, F_OK) == 0)
518                 return GOT_ONE;
519         ptr = strrchr(mp->unixTarget, '/');
520         if(!ptr) {
521                 mp->targetName = mp->unixTarget;
522                 mp->unixTarget = strdup(".");
523                 return GOT_ONE;
524         } else {
525                 *ptr = '\0';
526                 mp->targetName = ptr+1;
527                 return GOT_ONE;
528         }
529 }
530
531 int target_lookup(MainParam_t *mp, const char *arg)
532 {
533         if((mp->lookupflags & NO_UNIX) || (arg[0] && arg[1] == ':' ))
534                 return dos_target_lookup(mp, arg);
535         else
536                 return unix_target_lookup(mp, arg);
537 }
538
539 int main_loop(MainParam_t *mp, char **argv, int argc)
540 {
541         int i;
542         int ret, Bret;
543         
544         Bret = 0;
545
546         if(argc != 1 && mp->targetName) {
547                 fprintf(stderr,
548                         "Several file names given, but last argument (%s) not a directory\n", mp->targetName);
549         }
550
551         for (i = 0; i < argc; i++) {
552                 if ( got_signal )
553                         break;
554                 mp->originalArg = argv[i];
555                 mp->basenameHasWildcard = strpbrk(_basename(mp->originalArg),
556                                                   "*[?") != 0;
557                 if (mp->unixcallback && (!argv[i][0]
558 #ifdef OS_mingw32msvc
559 /* On Windows, support only the command-line image drive. */
560                                          || argv[i][0] != ':'
561 #endif
562                                          || argv[i][1] != ':' ))
563                         ret = unix_loop(0, mp, argv[i], 1);
564                 else
565                         ret = dos_loop(mp, argv[i]);
566                 
567                 if (! (ret & (GOT_ONE | ERROR_ONE)) ) {
568                         /* one argument was unmatched */
569                         fprintf(stderr, "%s: File \"%s\" not found\n",
570                                 progname, argv[i]);
571                         ret |= ERROR_ONE;
572                 }
573                 Bret |= ret;
574                 if(mp->fast_quit && (Bret & (MISSED_ONE | ERROR_ONE)))
575                         break;
576         }
577         FREE(&mp->targetDir);
578         if(Bret & ERROR_ONE)
579                 return 1;
580         if ((Bret & GOT_ONE) && ( Bret & MISSED_ONE))
581                 return 2;
582         if (Bret & MISSED_ONE)
583                 return 1;
584         return 0;
585 }
586
587 static int dispatchToFile(direntry_t *entry, MainParam_t *mp)
588 {
589         if(entry)
590                 return mp->callback(entry, mp);
591         else
592                 return mp->unixcallback(mp);
593 }
594
595
596 void init_mp(MainParam_t *mp)
597 {
598         fix_mcwd(mp->mcwd);
599         mp->openflags = O_RDONLY;
600         mp->targetName = 0;
601         mp->targetDir = 0;
602         mp->unixTarget = 0;
603         mp->dirCallback = dispatchToFile;
604         mp->unixcallback = NULL;
605         mp->shortname = mp->longname = 0;
606         mp->File = 0;
607         mp->fast_quit = 0;
608 }
609
610 const char *mpGetBasename(MainParam_t *mp)
611 {
612         if(mp->direntry) {
613                 wchar_to_native(mp->direntry->name, mp->targetBuffer,
614                                 MAX_VNAMELEN+1);
615                 return mp->targetBuffer;
616         } else
617                 return _basename(mp->unixSourceName);
618 }
619
620 void mpPrintFilename(FILE *fp, MainParam_t *mp)
621 {
622         if(mp->direntry)
623                 fprintPwd(fp, mp->direntry, 0);
624         else
625                 fprintf(fp,"%s",mp->originalArg);
626 }
627
628 const char *mpPickTargetName(MainParam_t *mp)
629 {
630         /* picks the target name: either the one explicitly given by the
631          * user, or the same as the source */
632         if(mp->targetName)
633                 return mp->targetName;
634         else
635                 return mpGetBasename(mp);
636 }
637
638 char *mpBuildUnixFilename(MainParam_t *mp)
639 {
640         const char *target;
641         char *ret;
642         char *tmp;
643
644         target = mpPickTargetName(mp);
645         ret = malloc(strlen(mp->unixTarget) + 2 + strlen(target));
646         if(!ret)
647                 return 0;
648         strcpy(ret, mp->unixTarget);
649         if(*target) {
650 #if 1 /* fix for 'mcopy -n x:file existingfile' -- H. Lermen 980816 */
651                 if(!mp->targetName && !mp->targetDir) {
652                         struct MT_STAT buf;
653                         if (!MT_STAT(ret, &buf) && !S_ISDIR(buf.st_mode))
654                                 return ret;
655                 }
656 #endif
657                 strcat(ret, "/");
658                 if(!strcmp(target, ".")) {
659                   target="DOT";
660                 } else if(!strcmp(target, "..")) {
661                   target="DOTDOT";
662                 }
663                 while( (tmp=strchr(target, '/')) ) {
664                   strncat(ret, target, tmp-target);
665                   strcat(ret, "\\");
666                   target=tmp+1;
667                 }
668                 strcat(ret, target);
669         }
670         return ret;
671 }