-
Notifications
You must be signed in to change notification settings - Fork 1
/
tash.c
548 lines (471 loc) · 15.1 KB
/
tash.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
/**
* @brief: tash.c
*
* @paragraph: Description - This is an implementation of a user-made shell. We are calling it tash (TexAs-SHell). Feel free to play around with it. This is a project developed toward the requirements of Project-1 in the course CS 5348 : Operating Systems Concepts.
*
* @authors: Shreyans Patel (SSP210009), Karan Jariwala (KHJ200000).
*/
//Include supporting file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include<sys/wait.h>
#include<fcntl.h>
//Definitions.
#define ERROR_MSG "An error has occurred\n" //The one and only error message of the program.
#define DEFAULT_PATH "/bin" //Path variable.
#define DEFAULT_CMD_BUF_SIZE 1024 //Size of command buffer.
//Global Variables.
char* gPath = NULL; //Global path variable.
/**
* @brief: modifyPath.
* @details: This is used to modify (set/update) the path variable.
* @param: iPath (Input) - The paths to set for the path variable.
* @return none.
*/
void modifyPath(char* iPath);
/**
* @brief: printErrorMsg.
* @details: This function is used to print the one and only error message.
* @return none.
* @note: tTemp in this function is used to avoid compilation errors since we need to use the return value of write(). This is because of the compilation instructions being passed. Unused variables are considered errors in this case.
*/
void printErrorMsg(void);
/**
* @brief: initTash.
* @details: Initialization of tash program. It decides the mode of runtime i.e Interactive or Batch Mode.
* @param: iArgc (Input) - The number of input arguments passed while executing "./tash". "./tash" counts too.
* @param: iArgv (Input) - Array of arguments.
* @return int.
*/
void initTash(int iArgc, char** iArgv);
/**
* @brief: initInteractive.
* @details: Initialize interactive mode of tash.
* @return none.
*/
void initInteractive(void);
/**
* @brief: initBatch.
* @details: Initialize batch mode of tash.
* @param: iArgv (Input) - Array of argument strings.
* @return none.
*/
void initBatch(char* iArgv);
/**
* @brief: parseAndDispatch.
* @details: This command parses the data received to a proper format to dispatch for execution.
* @param: iLineBuffer (Input) - The data to parse (Commands in improper format).
* @return none.
*/
void parseAndDispatch(char * iLineBuffer);
/**
* @brief: dispatchCmd.
* @details: This command sends the command for execution after validation if command exists in path.
* @param: iCmdArr (Input) - The data to dispatch for execution.
* @return none.
*/
void dispatchCmd(const char **iCmdArr);
/**
* @brief: executeCmd.
* @details: This command executes the command by forking.
* @param: iPath (Input) - Path for the command source.
* @param: iCmdArr (Input) - Command to execute.
* @return none.
*/
void executeCmd(char *iPath,char **iCmdArr);
/**
* @brief: prepareSingleStrPath.
* @details: This command prepares a single string from an array of individual strings.
* @param: iArr (Input) - Array with the seperate strings.
* @return char * - Pointer to the combines single string.
*/
char * prepareSingleStrPath(const char** iArr);
/**
* @brief: modifyPath.
* @details: This is used to modify (set/update) the path variable.
* @param: iPath (Input) - The paths to set for the path variable.
* @return none.
*/
void modifyPath(char* iPath)
{
if(NULL == iPath)
{
printErrorMsg();
exit(0);
}
//This is required for overwriting the path variable.
if(NULL != gPath)
{
free(gPath);
gPath = NULL;
}
gPath = strdup(iPath);
}
/**
* @brief: printErrorMsg.
* @details: This function is used to print the one and only error message.
* @return none.
* @note: tTemp in this function is used to avoid compilation errors since we need to use the return value of write(). This is because of the compilation instructions being passed. Unused variables are considered errors in this case.
*/
void printErrorMsg(void)
{
int tTemp = 0;
tTemp = write(STDERR_FILENO,ERROR_MSG,strlen(ERROR_MSG));
tTemp++;
}
/**
* @brief: initTash.
* @details: Initialization of tash program. It decides the mode of runtime i.e Interactive or Batch Mode.
* @param: iArgc (Input) - The number of input arguments passed while executing "./tash". "./tash" counts too.
* @param: iArgv (Input) - Array of arguments.
* @return int.
*/
void initTash(int iArgc, char** iArgv)
{
if(1 == iArgc)
{
initInteractive(); //Start tash in interactive mode.
}
else if(2 == iArgc)
{
initBatch(iArgv[iArgc-1]); //Start tash in batch mode.
}
else
{
printErrorMsg(); //Invalid mode, show error. This is for more than one argument to ""./tash".
exit(1);
}
}
/**
* @brief: initInteractive.
* @details: Initialize interactive mode of tash.
* @return none.
*/
void initInteractive(void)
{
char *tLineBuffer = NULL;
size_t tLineBufferSize = 0;
//If there was no redirection in input, then it must be interactive mode of operation. Then print prompt.
if(1 == isatty(STDIN_FILENO))
{
printf("tash> ");
}
while ((tLineBufferSize = getline(&tLineBuffer, &tLineBufferSize, stdin) != -1))
{
parseAndDispatch(tLineBuffer);
//If there was no redirection in input, then it must be interactive mode of operation. Then print prompt.
if(1 == isatty(STDIN_FILENO))
{
printf("tash> ");
}
}
}
/**
* @brief: initBatch.
* @details: Initialize batch mode of tash.
* @param: iArgv (Input) - Array of argument strings.
* @return none.
*/
void initBatch(char* iArgv)
{
//Validation before accessing. For safety.
if(NULL == iArgv)
{
printErrorMsg();
return;
}
FILE *tFileHandler = NULL;
char *tLineBuffer = NULL;
size_t tLineBufferSize = 0;
//Open the file.
tFileHandler = fopen(iArgv,"r");
//Opening the file failed.
if(NULL == tFileHandler)
{
printErrorMsg();
return;
}
//Read file line by line until end of file.
while(1)
{
tLineBufferSize = getline(&tLineBuffer,&tLineBufferSize,tFileHandler);
//If end of file is reached or if read failed.
if(EOF == tLineBufferSize)
{
break;
}
//Send data for processing.
parseAndDispatch(tLineBuffer);
}
//Close the file.
fclose(tFileHandler);
}
/**
* @brief: parseAndDispatch.
* @details: This command parses the data received to a proper format to dispatch for execution.
* @param: iLineBuffer (Input) - The data to parse (Commands in improper format).
* @return none.
*/
void parseAndDispatch(char * iLineBuffer)
{
//Validation before using the data.
if((NULL == iLineBuffer))
{
printErrorMsg();
return;
}
const char *tCmdArr[DEFAULT_CMD_BUF_SIZE];
size_t tCmdArrIdx = 0;
//Tokenization process related variables.
char *tSpaceToken = NULL;
char *tSaveSpaceToken = NULL;
char *tAmpersandToken = NULL;
char *tSaveAmpersandToken = NULL;
char *tRedirectToken = NULL;
char *tSaveRedirectToken = NULL;
const char tSpaces[] = " \t\r\n\v\f"; //Delimiters
const char tAmpersand[] = "&"; //Delimiters
const char tRedirect[] = ">"; //Delimiters
char *tValidateRedirectionStr = strdup(iLineBuffer);
//This is to validate if there is no command on the left of "&". Then it is an error.
if((NULL != strstr(tValidateRedirectionStr,"&")) && (0 == strcmp(strtok(tValidateRedirectionStr,tSpaces),"&")))
{
printErrorMsg();
return;
}
//Tokenization for &.
for(tAmpersandToken = strtok_r(iLineBuffer, tAmpersand, &tSaveAmpersandToken);
tAmpersandToken != NULL;
tAmpersandToken = strtok_r(NULL, tAmpersand, &tSaveAmpersandToken))
{
//Tokenization for whitspaces.
for(tSpaceToken = strtok_r(tAmpersandToken, tSpaces, &tSaveSpaceToken);
tSpaceToken != NULL;
tSpaceToken=strtok_r(NULL, tSpaces, &tSaveSpaceToken))
{
if((NULL != strstr(tSpaceToken,">")) && (0 != strcmp(tSpaceToken,">")))
{
tRedirectToken = strtok_r(tSpaceToken, tRedirect, &tSaveRedirectToken);
tCmdArr[tCmdArrIdx] = strdup(tRedirectToken);
tCmdArrIdx++;
tCmdArr[tCmdArrIdx] = strdup(">");
tCmdArrIdx++;
tRedirectToken = strtok_r(NULL, tRedirect, &tSaveRedirectToken);
tCmdArr[tCmdArrIdx] = strdup(tRedirectToken);
tCmdArrIdx++;
break;
}
tCmdArr[tCmdArrIdx] = strdup(tSpaceToken);
tCmdArrIdx++;
}
tCmdArr[tCmdArrIdx] = NULL;
dispatchCmd(tCmdArr);
tCmdArrIdx = 0;
}
}
/**
* @brief: dispatchCmd.
* @details: This command sends the command for execution after validation if command exists in path.
* @param: iCmdArr (Input) - The data to dispatch for execution.
* @return none.
*/
void dispatchCmd(const char **iCmdArr)
{
if(NULL == iCmdArr[0])
{
return;
}
//Built-in Command - exit.
if(0 == strcmp("exit",iCmdArr[0]))
{
if(NULL != iCmdArr[1])
{
printErrorMsg();
return;
}
exit(0);
}
//Built-in Command - path.
if(0 == strcmp("path",iCmdArr[0]))
{
char *tPath = NULL;
tPath = prepareSingleStrPath(iCmdArr);
if(NULL == tPath)
{
return;
}
modifyPath(tPath);
return;
}
////Built-in Command - cd.
if(0 == strcmp("cd",iCmdArr[0]))
{
if((NULL != iCmdArr[2]) || (-1 == chdir(iCmdArr[1])))
{
printErrorMsg();
}
return;
}
int tIsCmdFound = -1; //To check if the path variable has the command user is trying to execute.
char *tFinalPath = NULL;
char *tCmdPath = strdup(gPath);
char *tSpaceToken = NULL;
char *tSaveSpaceToken = NULL;
const char tSpaces[] = " \t\r\n\v\f"; //Delimiters
//Tokenization for Spaces.
for(tSpaceToken = strtok_r(tCmdPath, tSpaces, &tSaveSpaceToken); tSpaceToken != NULL; tSpaceToken = strtok_r(NULL, tSpaces, &tSaveSpaceToken))
{
tFinalPath = (char *) malloc((sizeof(tSpaceToken) + sizeof(iCmdArr[0]) + 2) * sizeof(char *));
strcpy(tFinalPath,tSpaceToken);
strcat(tFinalPath,"/");
strcat(tFinalPath,iCmdArr[0]);
tIsCmdFound = access(tFinalPath, X_OK);
//If command is present at the given path, execute it.
if(0 == tIsCmdFound)
{
executeCmd(tFinalPath,(char**)iCmdArr);
break;
}
}
//Command not found in the path. Show error.
if(-1 == tIsCmdFound)
{
printErrorMsg();
}
}
/**
* @brief: executeCmd.
* @details: This command executes the command by forking.
* @param: iPath (Input) - Path for the command source.
* @param: iCmdArr (Input) - Command to execute.
* @return none.
*/
void executeCmd(char *iPath,char **iCmdArr)
{
pid_t tPid, tWaitPid;
int tStatus;
tPid = fork();
//Forking failed, give error and return.
if(tPid < 0)
{
printErrorMsg();
exit(0);
}
//Child Loop.
else if(0 == tPid)
{
int tIndex = 0;
int tRedirectionCnt = 0;
int tRedirectionFileNameIdx = 0;
//Check if output is to be redirected.
while(NULL != iCmdArr[tIndex])
{
//If two or more ">" in an argument, it is an error.
if(NULL != strstr(iCmdArr[tIndex],">>"))
{
printErrorMsg();
return;
}
//If one ">" is found, redirection is possible, do the needed validations.
if (0 == strcmp(iCmdArr[tIndex],">"))
{
tRedirectionCnt++;
tRedirectionFileNameIdx = tIndex + 1;
if((NULL == iCmdArr[tIndex + 1]) || (NULL != iCmdArr[tIndex + 2]))
{
printErrorMsg();
return;
}
}
tIndex++;
}
//More than one redirection symbol used.
if(1 < tRedirectionCnt)
{
printErrorMsg();
return;
}
//Valid redirection, prepare the output file name from next argument.
else if(1 == tRedirectionCnt)
{
char *tOutputPath = NULL;
tOutputPath = strdup(iCmdArr[tRedirectionFileNameIdx]);
close(STDOUT_FILENO);
open(tOutputPath, O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU);
iCmdArr[tRedirectionFileNameIdx-1] = NULL;
iCmdArr[tRedirectionFileNameIdx] = NULL;
}
//Execv failed.
if(-1 == execv(iPath,iCmdArr))
{
printErrorMsg();
return;
}
}
//Parent Process.
else
{
do
{
tWaitPid = waitpid(tPid, &tStatus, WUNTRACED);
}
while (!WIFEXITED(tStatus) && !WIFSIGNALED(tStatus));
tWaitPid++;
}
}
/**
* @brief: prepareSingleStrPath.
* @details: This command prepares a single string from an array of individual strings.
* @param: iArr (Input) - Array with the seperate strings.
* @return char * - Pointer to the combines single string.
*/
char * prepareSingleStrPath(const char** iArr)
{
//Validation if array passed is null.
if (iArr == NULL)
{
return NULL;
}
int tLoopIndex = 1; //Loop index for array. It starts from 1 since the 0th index will have path command.
int tCount = 0; //Used to count the number of elements for setting as paths.
char *tResult = NULL; //Result string which is a combination of all element strings.
int tTotalLength = 0; //Length of the result string.
//Iterate through the array to count as well as get the total length required for final string including spaces and NULL termination.
while (iArr[tLoopIndex] != NULL)
{
tTotalLength += (strlen(iArr[tLoopIndex]) + 1); //Consider space after everypath that is entered so +1.
tLoopIndex++;
}
//Update the count variable.
tCount = tLoopIndex;
//Allocate required memory to the final string.
tResult = malloc(tTotalLength * sizeof(char *));
//Memory allocation failed.
if (tResult == NULL)
{
return NULL;
}
//Concatenate the individual elements of the array to form the final string.
for (tLoopIndex = 1; tLoopIndex < tCount; tLoopIndex++)
{
strcat(tResult, iArr[tLoopIndex]);
strcat(tResult, " ");
}
return tResult;
}
/**
* @brief: main.
* @details: The main function of tash. This is the file that is to be compiled and executed.
* @param: iArgc (Input) - The number of input arguments passed while executing "./tash". "./tash" counts too.
* @param: iArgv (Input) - Array of argument strings.
* @return int.
*/
int main(int iArgc, char** iArgv)
{
modifyPath(DEFAULT_PATH); //Set path variable to default "/bin".
initTash(iArgc,iArgv); //Initialize tash and derive operation mode.
//Exit Shell
return 0;
}