1 /* c_chdirlist.c
2  *
3  * Copyright (c) 1996-2005 Mike Gleason, NcFTP Software.
4  * All rights reserved.
5  *
6  */
7 
8 #include "syshdrs.h"
9 #ifdef PRAGMA_HDRSTOP
10 #	pragma hdrstop
11 #endif
12 
13 #if (defined(WIN32) || defined(_WINDOWS)) && !defined(__CYGWIN__)
14 #define _CRT_SECURE_NO_WARNINGS 1
15 #endif
16 
17 int
FTPChdirList(FTPCIPtr cip,FTPLineListPtr const cdlist,char * const newCwd,const size_t newCwdSize,int flags)18 FTPChdirList(FTPCIPtr cip, FTPLineListPtr const cdlist, char *const newCwd, const size_t newCwdSize, int flags)
19 {
20 	size_t len;
21 	char *cdstr;
22 	FTPLinePtr lp;
23 	int lastSubDir;
24 	int mkd, pwd;
25 	int result;
26 
27 	/* Retain backwards compatibility with earlier library versions. */
28 	if (flags == kChdirOnly)
29 		flags = kChdirFullPath;
30 
31 	if ((flags & kChdirFullPath) != 0) {
32 		len = 0;
33 		for (lp = cdlist->first; lp != NULL; lp = lp->next) {
34 			len += strlen(lp->line);
35 			len++;	/* account for delimiting slash */
36 		}
37 		cdstr = malloc(len + 1);
38 		if (cdstr == NULL)
39 			return (cip->errNo = kErrMallocFailed);
40 		cdstr[0] = '\0';
41 		for (lp = cdlist->first; lp != NULL; lp = lp->next) {
42 			strcat(cdstr, lp->line);
43 			if (lp->next != NULL)
44 				strcat(cdstr, "/");
45 		}
46 		if (FTPChdir3(cip, cdstr, newCwd, newCwdSize, (flags & ~kChdirOneSubdirAtATime)) == kNoErr) {
47 			free(cdstr);
48 			return (kNoErr);
49 		}
50 		free(cdstr);
51 	}
52 
53 	if ((flags & kChdirOneSubdirAtATime) != 0) {
54 		mkd = (flags & kChdirAndMkdir);
55 		pwd = (flags & kChdirAndGetCWD);
56 		lastSubDir = 0;
57 		result = kNoErr;
58 
59 		for (lp = cdlist->first; lp != NULL; lp = lp->next) {
60 			if (lp->next == NULL)
61 				lastSubDir = 1;
62 
63 			if (strcmp(lp->line, ".") == 0) {
64 				result = 0;
65 				if ((lastSubDir != 0) && (pwd != 0))
66 					result = FTPGetCWD(cip, newCwd, newCwdSize);
67 			} else if ((lastSubDir != 0) && (pwd != 0)) {
68 				result = FTPChdirAndGetCWD(cip, (*lp->line != '\0') ? lp->line : "/", newCwd, newCwdSize);
69 			} else {
70 				result = FTPChdir(cip, (*lp->line != '\0') ? lp->line : "/");
71 			}
72 			if (result < 0) {
73 				if ((mkd != 0) && (*lp->line != '\0')) {
74 					if (FTPCmd(cip, "MKD %s", lp->line) == 2) {
75 						result = FTPChdir(cip, lp->line);
76 					} else {
77 						/* couldn't change nor create */
78 						cip->errNo = result;
79 					}
80 				} else {
81 					cip->errNo = result;
82 				}
83 			}
84 			if (result != kNoErr)
85 				break;
86 		}
87 		return (result);
88 	}
89 
90 	return (kErrBadParameter);
91 }	/* FTPChdirList */
92