-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.c
More file actions
374 lines (311 loc) · 11.7 KB
/
Copy pathshell.c
File metadata and controls
374 lines (311 loc) · 11.7 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pwd.h>
#pragma clang diagnostic push
#pragma ide diagnostic ignored "UnusedImportStatement"
#include <sys/types.h>
#include <sys/wait.h>
#pragma clang diagnostic pop
/*
* By 6602
* All questions answered
*/
#define BUFFER_SIZE 1000
#define MAX_ARGS 40
#define MAX_ARG_LENGTH 100
#define PROGRAM_NAME "mash"
#define TOKEN_DELIMETER " \t\r\n\a"
#define PROMPT "\e[1;31mMASH >\033[0m "
typedef struct statement {
char *argv[MAX_ARGS];
int argc;
FILE *input_redir;
FILE *output_redir;
FILE *output_err_redir;
char terminator;
struct statement *next;
} statement;
/**
* Create empty statement node
* @return pointer to empty statement
*/
statement *createStatement() {
statement *temp;
temp = malloc(sizeof(statement));
temp->next = NULL;
temp->input_redir = NULL;
temp->output_redir = NULL;
temp->output_err_redir = NULL;
temp->argc = 0;
temp->terminator = 0;
return temp;
}
/**
* Add to statement argv
* @param c position in argv
* @param statement current statement
* @param text text to add
*/
void addToArgV(statement *statement, char *text) {
statement->argv[statement->argc] = malloc(sizeof(char *));
strcpy(statement->argv[statement->argc], text);
(statement->argc)++;
}
/**
* Check if current characters is end of command list
* @param token containing break point
* @return token the value of the character broken on
*/
char isCommandBreak(char *token) {
if (token[0] == ';' || token[strlen(token) - 1] == ';') {
return ';';
} else if (token[0] == '&' || token[strlen(token) - 1] == '&') {
return '&';
} else if (token[0] == '|' || token[strlen(token) - 1] == '|') {
return '|';
} else {
return 0;
}
}
/**
* Reads a line from the console and returns a character array.
* @param sz the size of the buffer to read
* @return the entered line
*/
char *read_line(char *buf, size_t sz) {
fgets(buf, sz, stdin);
size_t ln = strlen(buf) - 1;
if (feof(stdin)) {
exit(EXIT_SUCCESS); // Exit when CTRL-D is received
}
if (*buf && buf[ln] == '\n') {
buf[ln] = '\0'; // Replace new line with null terminator
} else {
buf[ln + 1] = '\0'; // Add null terminator
}
if (strlen(buf) == 0) { // Return null if the string is empty after manipulation
return NULL;
} else {
return buf;
}
}
/**
* Creates a new pipe in memory and assign two file handlers to read and write to it.
* @param readable a pointer to the readable end of the pipe
* @param writable a pointer to the writeable end of the pipe
* @return the status (always 0)
*/
int fpipe(FILE **readable, FILE **writable) {
int fd[2];
pipe(fd);
*readable = fdopen(fd[0], "r");
*writable = fdopen(fd[1], "w");
return 0;
}
/**
* Prints a simple help message
*/
void printHelp() {
printf("MASH - The Matt Again Shell\n\n");
printf("Built-Ins: cd, exit, help\n");
}
/**
* Tokenises a string by the space delimiter and adds a null value to array
* @param buf a pointer to the string
* @param statement a pointer to the output statement array
* @param max the maximum length of each parameter
*/
void split_statements(char *buf, statement *statement, size_t max) {
char *token = strtok(buf, TOKEN_DELIMETER); // Break on any new line, tab, space, or return
while (token != NULL) {
char commandBroken = isCommandBreak(token);
if (strlen(token) > 0 && commandBroken) {
if (commandBroken == ';') {
if (token[0] == ';') {
statement->argv[statement->argc] = 0;
} else {
token[strlen(token) - 1] = 0;
addToArgV(statement, token);
}
}
if (strlen(token) != 1 && commandBroken == '&') {
token[strlen(token) - 1] = 0;
addToArgV(statement, token);
}
statement->argv[statement->argc] = 0;
statement->terminator = commandBroken;
statement->next = createStatement(); // Creates and initialises new statement
if (commandBroken == '|') {
FILE *readable;
FILE *writable;
fpipe(&readable, &writable); // Creates new pipe to handle | case
statement->output_redir = writable;
statement = statement->next;
statement->input_redir = readable;
} else {
statement = statement->next;
}
} else if (strcmp(token, "\"\"") == 0) { // Ignore `""`
addToArgV(statement, "");
} else if (strlen(token) == 1 && token[0] == '>') {
token = strtok(NULL, TOKEN_DELIMETER);
statement->output_redir = fopen(token, "w");
} else if (strlen(token) == 2 && token[0] == '>' && token[1] == '>') {
token = strtok(NULL, TOKEN_DELIMETER);
statement->output_redir = fopen(token, "a"); // Open (and create) file in append mode
} else if (strlen(token) == 2 && token[0] == '2' && token[1] == '>') {
token = strtok(NULL, TOKEN_DELIMETER);
statement->output_err_redir = fopen(token, "w");// Open (and create) file in append mode
} else if (strlen(token) == 1 && token[0] == '<') {
token = strtok(NULL, TOKEN_DELIMETER);
statement->input_redir = fopen(token, "r");
} else if (token[0] == '\"') { // Case: on an opening speech mark
char *comb = malloc(max); // Allocate a space for the concatenated strings
token++; // Ignore the opening mark
if (strchr(token, '"')) {
strcpy(comb, token);
} else {
while (token != NULL && !strchr(token, '"')) {
strcat(comb, token); // Add the string to 'comb'
token = strtok(NULL, TOKEN_DELIMETER); // Move to next token
if (token != NULL) {
strcat(comb, " "); // Add space to parameters
if (strchr(token, '"')) {
strcat(comb, token); // Add the string to 'comb'
}
}
}
}
// HANDLE "a edge case
char *atSpeechMark = strchr(comb, '"');
if (atSpeechMark == NULL) {
comb[strlen(comb)] = '\0';
addToArgV(statement, comb);
} else {
*atSpeechMark = 0; // Convert speech mark to null character
statement->argv[statement->argc] = malloc(sizeof(char *));
addToArgV(statement, comb);
char *v = (atSpeechMark + 1);
if (*v != '\0') {
atSpeechMark++;
addToArgV(statement, atSpeechMark);
}
}
} else {
addToArgV(statement, token);
}
token = strtok(NULL, TOKEN_DELIMETER); // Move to next token
}
statement->argv[statement->argc] = 0; // Null terminate final statements, final array item
statement->next = NULL; // Sets the next statement to null (indicating the final statement)
free(token); // Free memory used by the string
}
/**
* Executes the given array of commands in a subprocess
* @param stmt the statments representing a command
*/
void execute_statement(statement *stmt) {
char **split = stmt->argv;
int stdoutCopy = 0;
int stderrCopy = 0;
int stdinCopy = 0;
if (stmt->output_redir) {
stdoutCopy = dup(STDOUT_FILENO);
int outputFile = fileno(stmt->output_redir);
if (dup2(outputFile, STDOUT_FILENO) < 0) return;
close(outputFile);
}
if (stmt->output_err_redir) {
stderrCopy = dup(STDERR_FILENO);
int outputFile = fileno(stmt->output_err_redir);
if (dup2(outputFile, STDERR_FILENO) < 0) return;
close(outputFile);
}
if (stmt->input_redir) {
stdinCopy = dup(STDIN_FILENO);
int inputFile = fileno(stmt->input_redir);
if (dup2(inputFile, STDIN_FILENO) < 0) return;
close(inputFile);
}
pid_t pid = fork();
if (pid == 0) {
execvp(split[0], split); // Execute and look in PATH for binaries
if (errno) {
perror(PROGRAM_NAME); // Show error from subprocess
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
} else {
waitpid(pid, NULL,
(stmt->terminator == '&') ? WNOHANG : 0); // Wait for subprocess to finish
if (stmt->terminator == '&') {
printf("[%d]\n", pid);
}
if (stmt->output_redir) {
if (dup2(stdoutCopy, STDOUT_FILENO) < 0) return;
close(stdoutCopy);
}
if (stmt->output_err_redir) {
if (dup2(stderrCopy, STDERR_FILENO) < 0) return;
close(stderrCopy);
}
if (stmt->input_redir) {
if (dup2(stdinCopy, STDIN_FILENO) < 0) return;
close(stdinCopy);
}
}
}
int main(int argc, char *argv[]) {
size_t inputBufferSize = sizeof(char) * BUFFER_SIZE;
if (argc > 1) {
statement *newStatement = createStatement();
memcpy(newStatement->argv, argv, sizeof(statement));
newStatement->argc = argc;
execute_statement(newStatement);
free(newStatement);
}
while (&free) {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("%s %s", cwd, PROMPT); // Show prompt with path
} else {
printf("%s", PROMPT); // Show prompt without path
}
char *buf = malloc(inputBufferSize);
read_line(buf, inputBufferSize);
statement *temp = createStatement();
split_statements(buf, temp, MAX_ARG_LENGTH); // Split arguments
while (temp != NULL) {
if (temp->argv[0] != NULL) {
if (strncmp(temp->argv[0], "exit", 4) == 0) { // On `exit`, exit
printf("Exiting...\n");
return EXIT_SUCCESS;
} else if (strncmp(temp->argv[0], "cd", 2) == 0) { // On `cd`, change directory
if (temp->argv[1] != NULL) {
if (chdir(temp->argv[1]) != 0) {
perror(PROGRAM_NAME);
}
} else {
chdir(getpwuid(getuid())->pw_dir);
}
} else if (strncmp(temp->argv[0], "help", 4) == 0) { // On `help`, show help
printHelp();
} else {
execute_statement(temp); // Otherwise, perform standard execute_statement
}
}
struct statement *oldtemp = temp;
temp = temp->next;
char ** oldCommandStrings = oldtemp->argv;
size_t i = 0;
for( i = 0; i < oldtemp->argc; i++) {
free(oldCommandStrings[i]); // Free pointers in argv
}
free(oldtemp);
}
}
return EXIT_FAILURE;
}