/
myshell.c
410 lines (357 loc) · 8.99 KB
/
myshell.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/*
UNI: ab3599
myshell
COMS 4118 OS Homework 1
*/
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include "linkedlist.c"
//#include <>
const char *SUPPORTED_COMMANDS[] = {"cd", "exit", "path"};
const char *SPECIAL_CHARS[] = {" ", "<", ">", "2>", "|"}; //strings used as delims for tokenizer calls
struct node *pathlist = NULL;
void removeNewLineChar(char *consoleinput)
{
int length = strlen(consoleinput);
if (consoleinput[length-1] == '\n')
{
consoleinput[length-1] = '\0';
}
}
void removeWhiteSpaces(char *consoleinput)
{
int length = strlen(consoleinput);
int i=0;
while(consoleinput[length-1] == ' ') //remove whitespaces after input
{
consoleinput[length-1] = '\0';
length = strlen(consoleinput);
}
int spaces = 0; //remove whitespaces before input
for(i=0;consoleinput[i]==' ';i++,spaces++);
for(i=0;i<=strlen(consoleinput);i++)
{
consoleinput[i] = consoleinput[i+spaces];
}
}
void readCommand(char *consoleinput)
{
consoleinput = fgets(consoleinput, 256, stdin);
}
char *parseDir(char * consoleinput) //returns first arg after command, using whitespace as delimiter
{
char *token = (char *)strtok(consoleinput, SPECIAL_CHARS[0]);
token = (char *)strtok(NULL, SPECIAL_CHARS[0]);
//printf("\npath given to cd:%s", token);
return token;
}
int runChangeDir(char *consoleinput)
{
int result =0;
if(strlen(consoleinput)<=3)
{
printf("cd error: no path specified.");
}
else
{
char *pathname = parseDir(consoleinput);
result = chdir(pathname);
}
return (result==0)?0:errno;
}
void getCurrentDir(char * cwd)
{
getcwd(cwd, 256);
}
int runPath(char *consoleinput)
{
if(strlen(consoleinput) == 4) //path without any args
{
if(pathlist!=NULL)
{
printList(pathlist);
}
else
{
printf("[path variable not set]");
}
}
else //path with args
{
char *args = strndup(consoleinput+4, strlen(consoleinput)-4); //remove "path" from input
removeWhiteSpaces(args);
char *newpath = strndup(args+1, strlen(args)-1); //remove + or - from input
removeWhiteSpaces(newpath);
if(args[0]=='+')
{
//add to linkedlist
printf("\nAdding new path:[%s]\n", newpath);
pathlist = addNode(pathlist, newpath);
printList(pathlist);
return 0;
}
else if(args[0]=='-')
{
//remove from linkedlist
printf("\nDeleting path:[%s]\n", newpath);
pathlist = deleteNode(pathlist, newpath);
printList(pathlist);
return 0;
}
else
{
free(args);
free(newpath);
return 22;
}
free(newpath);
free(args);
}
return 12;
}
void executeCommand(char **argv)
{
int child_pid = fork();
//int child_status;
if(child_pid < 0)
{
//errno = 3;
perror("fork error:");
}
else if(child_pid == 0) //fork success
{
if(execv(argv[0], argv) == -1)
{
perror("Bad command or filename:");
}
}
// else //fork success, parent
// {
// child_pid = waitpid(child_pid, &child_status, 0);
// if(child_pid < 0)
// {
// perror("waitpid error:");
// }
// }
}
char ** parseArgv(char * consoleinput, const char *delim)
{
/*parse into an array of pointers that point to null terminated strings
-first pointer points to command
-followed by pointers to other arguments
-last element points to NULL
*/
char ** argv = (char **)malloc( (strlen(consoleinput)) * sizeof(char*) ); //we can never have more char *'s than length of input
assert(argv!=NULL);
//memset(argv, 0, sizeof(char*)*strlen(consoleinput));
char* curToken = strtok(consoleinput, delim);
int argcount = 1;
//printf("\nDelimiter: [%s]", delim);
for (argcount = 1; curToken != NULL; argcount++)
{
//printf("\nToken picked:%s", curToken);
argv[argcount-1] = strdup(curToken);
removeWhiteSpaces(argv[argcount-1]);
curToken = strtok(NULL, delim);
//printf("\nargv[%d] : [%s]", argcount-1, argv[argcount-1]);
}
argv[argcount-1] = NULL; //argcount is arguments given + 1
//printf("\nNULL at argv[%d] : [%s]", argcount-1, argv[argcount]);
argv = (char**) realloc(argv, (argcount) * sizeof(char*));
free(curToken);
return argv;
}
int findPath(char **argv)
{
char *cmdfile = argv[0];
struct stat st;
if(stat(cmdfile,&st) == 0) //command file found in current dir
{
return 0;
}
else //search pathlist for command file
{
struct node *pathnode = pathlist;
char *filename = argv[0];
while(pathnode!=NULL) //traverse pathlist
{
char *filepath = strdup(pathnode->elem);
if(filepath[strlen(filepath)-1] != '/')
{
filepath = realloc(filepath, strlen(filepath)+strlen(filename)+2);
strcat(filepath, "/");
}
else
{
filepath = realloc(filepath, strlen(filepath)+strlen(filename)+1);
}
strcat(filepath, filename); //filepath represents full path to command file now
//printf("\nFile Path being evaluated:[%s]", filepath);
if(stat(filepath,&st) == 0) //command file found at current path
{
argv[0] = realloc(argv[0], strlen(filepath)+1);
argv[0] = strdup(filepath);
//printf("\nFile found at path:[%s]", argv[0]);
free(filepath);
return 0;
}
free(filepath);
return 0;
}
}
return 1;
}
int main(int argc, char **argv)
{
while(1) //shell runs till user enters exit
{
char * cwd = malloc(256); //find current working directory for prompt
assert(cwd != NULL);
getCurrentDir(cwd);
printf("\nMyShell:%s$ ", cwd); //print shell prompt
free(cwd);
char *consoleinput = malloc(256);
assert(consoleinput != NULL);
//TO DO: Change buffer size to variable
readCommand(consoleinput); //accept input
removeNewLineChar(consoleinput); //remove '\n' character from input
removeWhiteSpaces(consoleinput); //remove all spaces before and after command
if(strncmp(consoleinput, SUPPORTED_COMMANDS[1], 4) == 0) //exit
{
free(consoleinput);
printf("\nMyShell Terminated\n");
return 0;
}
else if(strncmp(consoleinput, SUPPORTED_COMMANDS[0], 2) == 0) //cd
{
int result = runChangeDir(consoleinput);
if(result!=0)
{
perror("cd error:");
}
}
else if(strncmp(consoleinput, SUPPORTED_COMMANDS[2], 4) == 0) //path
{
int result = runPath(consoleinput);
if(result!=0)
{
errno = result;
perror("path error:");
}
}
else
{
//handle pipes
char **commands = parseArgv(consoleinput, SPECIAL_CHARS[4]); //input destoyed
int numcommands = 0;
while( commands[numcommands]!=NULL )
{
numcommands++;
}
//printf("\nNumber of commands:[%d]", numcommands);
const int numpipes = 2*(numcommands-1);
//printf("\nNumber of pipe file descriptors:[%d]", numpipes);
/*read and write ends of pipes stay apart by 3
-increment open pipe indexes by 2 after every command
-close all pipes
*/
int pipefds[numpipes];
int i=0;
for(i=0; i<numpipes;i=i+2)
{
pipe(pipefds+i);
}
//printf("\npipe() call successful");
// for(i=0;i<numpipes;i++)
// {
// printf("[%d]", pipefds[i]);
// }
int pipe_w = 1;
int pipe_r = pipe_w - 3;
int curcommand = 0;
while(curcommand < numcommands)
{
//printf("\nCommand number:[%d]", curcommand);
//printf("\ninside pipe loop for command [%s]", commands[curcommand]);
//Parse Command and Arguments into formatneeded by execv
char **argv = parseArgv(commands[curcommand], SPECIAL_CHARS[0]);
//printf("\nCurrent Command:[%s]", argv[0]);
if(findPath(argv) == 0)
{
//executeCommand(argv);
int child_pid = fork();
//int child_status;
if(child_pid < 0)
{
//errno = 3;
perror("fork error:");
}
else if(child_pid == 0) //fork success
{
if(pipe_w < numpipes)
{
//open write end
//printf("\nWrite pipe:[%d] to stdout", pipefds[pipe_w]);
if(dup2(pipefds[pipe_w], 1) < 0)
{
perror("pipe write-end error: ");
}
}
if((pipe_r >= 0)&&(pipe_r < numpipes))
{
//open read end
//printf("\nRead pipe:[%d] to stdin", pipefds[pipe_r]);
if(dup2(pipefds[pipe_r], 0) < 0)
{
perror("pipe read-end error: ");
}
}
for(i=0;i<numpipes;i++) //close off all pipes
{
//printf("\nclosing all pipes");
close(pipefds[i]);
}
if(execv(argv[0], argv) == -1)
{
perror("Bad command or filename:");
exit(0);
//TODO: child hangs here
}
//fflush(stdin);
}
}
else
{
printf("\nBad command or filename");
//TODO: ForkBomb occuring here
//exit(0);
}
free(argv);
//printf("\nIncrementing pipe ends, moving to next command.");
curcommand++;
pipe_w = pipe_w + 2;
pipe_r = pipe_r + 2;
}
//int i=0;
for(i=0;i<numpipes;i++) //close off all pipes
{
//printf("\nclosing all pipes");
close(pipefds[i]);
}
int status;
for(i=0;i<numcommands;i++)
{
wait(&status);
}
free(commands);
}
free(consoleinput);
}
freeList(pathlist);
}