-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkhol.c
423 lines (344 loc) · 11.5 KB
/
khol.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
/*
* khol (খোল) - A minimalistic shell written in C
*
* Copyright (C) 2017 Sanket Dasgupta
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wait.h>
#include <readline/readline.h>
#include <readline/history.h>
#include "constants.h"
char *history_path = NULL;
int khol_cd(char **args);
int khol_help(char **args);
int khol_history(char **args);
int khol_exit(char **args);
/* Function pointers that correspond to the buitins */
int (*builtin_func[]) (char**) = {
&khol_cd,
&khol_help,
&khol_history,
&khol_exit
};
/* Returns the number of builtin commands available for khol */
int num_builtins() {
return sizeof(builtins) / sizeof(char *);
}
/*
* Function that implements the khol builtin "cd", to change directories
*
* The command "cd" needs an argument to change the directory.
*
* If a argument is not provided, khol raises an warning.
*
*/
int khol_cd(char **args) {
if(args[1] == NULL) {
fprintf(stderr, YELLOW "khol: expected argument to `cd`\n" RESET);
} else {
if(chdir(args[1]) != 0) {
fprintf(stderr, RED "khol: %s\n" RESET, strerror(errno));
}
}
return 1;
}
/* Function that shows the help message */
int khol_help(char **args) {
int i;
printf(BOLD"\nkhol: A minimalistic shell written in C."
"\nCopyright (C) 2017 Sanket Dasgupta\n\n"RESET
"Builtin commands:\n"
"cd - Change dicrectory\n"
"history - Show history from ~/.khol_history\n"
"exit - Exit this shell"
"help - Show this help\n\n"
);
return 1;
}
int khol_exit(char **args)
{
return 0;
}
void khol_exit_on_SIGINT(int signal) {
exit(0);
}
/*
* Function that is responsible for launching and handling processes.
*
* @args: The argument list provided to the shell. This argument list will
* be used to launch and execute the child process.
* @fd: The file descriptor to be passed, in case of a redirection operator
* being passed to the shell.
* @options: A list of options being implemented to handle background processing
* and redirection. The options are defined in constants.h
*/
int launch(char **args, int fd, int options) {
int khol_bg = (options & KHOL_BG) ? 1 : 0;
int khol_stdout = (options & KHOL_STDOUT) ? 1 : 0;
int khol_stderr = (options & KHOL_STDERR) ? 1 : 0;
int khol_stdin = (options & KHOL_STDIN) ? 1 : 0;
pid_t pid, wpid;
int status;
if( (pid = fork()) == 0 ) {
// child process
if(fd > 2) {
if(khol_stdout && dup2(fd, STDOUT_FILENO) == -1 ) {
fprintf(stderr, RED "khol: Error duplicating stream: %s\n" RESET, strerror(errno));
return 1;
}
if(khol_stderr && dup2(fd, STDERR_FILENO) == -1 ) {
fprintf(stderr, RED "khol: Error duplicating stream: %s\n" RESET, strerror(errno));
return 1;
}
if(khol_stdin && dup2(fd, STDIN_FILENO) == -1 ) {
fprintf(stderr, RED "khol: Error duplicating stream: %s\n" RESET, strerror(errno));
return 1;
}
close(fd);
}
if( execvp(args[0], args) == -1 ) {
fprintf(stderr, RED "khol: %s\n" RESET, strerror(errno));
}
exit(EXIT_FAILURE);
} else if (pid < 0) {
fprintf(stderr, RED "khol: %s\n" RESET, strerror(errno));
} else {
// ignore SIGINT in parent process when child process is launched
signal(SIGINT, SIG_IGN);
do {
if( !khol_bg ) {
wpid = waitpid(pid, &status, WUNTRACED);
}
else {
printf(YELLOW "[bg][%d] - %s\n" RESET, pid, args[0]);
}
} while ( !WIFEXITED(status) && !WIFSIGNALED(status) );
}
return 1;
}
/* Function that shows the khol history file along with line numbers
*
* Uses the 'cat' tool with '-n' argument to display line numbers
*/
int khol_history(char **args) {
char *history_args[4] = {"cat", "-n", history_path, NULL};
return launch(history_args, STDOUT_FILENO, KHOL_FG);
}
int pipe_launch(char** arg1, char** arg2) {
int fd[2], pid;
pipe(fd);
int stdin_copy = dup(STDIN_FILENO);
if( (pid = fork()) == 0 ) {
close(STDOUT_FILENO);
dup(fd[1]);
close(fd[0]);
launch(arg1, STDOUT_FILENO, KHOL_FG);
exit(EXIT_FAILURE);
}
else if (pid > 0){
close(STDIN_FILENO);
dup(fd[0]);
close(fd[1]);
launch(arg2, STDOUT_FILENO, KHOL_FG);
dup2(stdin_copy, STDIN_FILENO);
return 1;
}
}
/* Function responsible for parsing the arguments */
int execute(char **args) {
int i;
if(args[0] == NULL) {
return 1;
}
i = 0;
while(args[i]) {
i++;
}
/* launch process in background */
if( !strcmp("&", args[--i]) ) {
args[i] = NULL;
return launch(args, STDOUT_FILENO, KHOL_BG);
}
for(i = 0; i < num_builtins(); i++) {
if ( !strcmp(args[0], builtins[i]) ) {
return (*builtin_func[i])(args);
}
}
int j = 0;
while(args[j] != NULL) {
// for `>` operator for redirection (stdout)
if( !strcmp(">", args[j]) ) {
int fd = fileno(fopen(args[j+1], "w+"));
args[j] = NULL;
return launch(args, fd, KHOL_FG);
}
// for `>>` operator for redirection (stdout with append)
else if( !strcmp(">>", args[j]) ) {
int fd = fileno(fopen(args[j+1], "a+"));
args[j] = NULL;
return launch(args, fd, KHOL_FG | KHOL_STDOUT);
}
// for `2>` operator for redirection (stderr)
else if( !strcmp("2>", args[j]) ) {
int fd = fileno(fopen(args[j+1], "w+"));
args[j] = NULL;
return launch(args, fd, KHOL_FG | KHOL_STDERR);
}
// for `>&` operator for redirection (stdout and stderr)
else if( !strcmp(">&", args[j]) ) {
int fd = fileno(fopen(args[j+1], "w+"));
args[j] = NULL;
return launch(args, fd, KHOL_FG | KHOL_STDERR | KHOL_STDOUT);
}
// for `<` operator for redirection (stdin)
else if( !strcmp("<", args[j]) ) {
int fd = fileno(fopen(args[j+1], "r"));
args[j] = NULL;
return launch(args, fd, KHOL_FG | KHOL_STDIN);
}
// for piping
else if( !strcmp("|", args[j]) ) {
char** arg2;
int i = 0;
args[j] = NULL;
arg2 = &args[j+1];
return pipe_launch(args, arg2);
}
j++;
}
return launch(args, STDOUT_FILENO, KHOL_FG);
}
/* Function that splits the line based on delimeters defined in constants.h */
char **split_line(char *line) {
char **tokens = malloc(sizeof(char*) * TOKEN_BUFSIZE);
char *token;
int bufsize_copy = TOKEN_BUFSIZE;
int pos = 0;
if(!tokens) {
fprintf(stderr, RED "khol: Memory allocation failed." RESET);
exit(EXIT_FAILURE);
}
token = strtok(line, TOKEN_DELIMS);
while(token != NULL) {
tokens[pos] = token;
pos++;
if(pos >= bufsize_copy) {
bufsize_copy = bufsize_copy * 2;
tokens = realloc(tokens, sizeof(char*) * bufsize_copy);
if(!tokens) {
fprintf(stderr, RED "khol: Memory allocation failed." RESET);
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, TOKEN_DELIMS);
}
tokens[pos] = NULL;
return tokens;
}
/* Function that returns the prompt */
char *get_prompt(void) {
char *prompt, tempbuf[PATH_MAX];
size_t prompt_len = sizeof(char) * PROMPT_MAXSIZE;
prompt = malloc(prompt_len);
if( getcwd( tempbuf, sizeof(tempbuf) ) != NULL ) {
snprintf(prompt, prompt_len, "%s > ", tempbuf);
return prompt;
}
else {
free(prompt);
return NULL;
}
}
/* The main loop of the shell */
void main_loop(void) {
signal(SIGINT, khol_exit_on_SIGINT);
char *line;
char **args;
int status, index;
// get prompt
char *prompt;
char *homedir = getenv("HOME");
size_t history_path_len = sizeof(char) * PATH_MAX;
history_path = malloc(history_path_len);
snprintf(history_path, history_path_len, "%s/%s", homedir, HISTFILE);
// read from history file
read_history(history_path);
do {
// use GNU's readline() function
if( (prompt = get_prompt()) == NULL) {
status = 0;
fprintf(stderr, RED "khol: Failed to get prompt.\n" RESET);
}
line = readline(prompt);
// add to history for future use
add_history(line);
// EOF
if(!line) {
status = 0;
}
else {
// write to history file
write_history(history_path);
char* history_copy;
if(line[0] == '!' && line[1] == '-') {
if(sscanf(line, "!-%d", &index) != EOF) {
HIST_ENTRY* hist_entry = history_get(history_length - index);
history_copy = malloc(strlen(hist_entry->line)+1);
strcpy(history_copy, hist_entry->line);
args = split_line(history_copy);
}
else
fprintf(stderr, RED "khol: Expected digit after '!-' for history recollection.\n." RESET);
}
else if(line[0] == '!' ) {
if(sscanf(line, "!-%d", &index) != EOF) {
HIST_ENTRY* hist_entry = history_get(index);
history_copy = malloc(strlen(hist_entry->line)+1);
strcpy(history_copy, hist_entry->line);
args = split_line(history_copy);
free(history_copy);
}
else
fprintf(stderr, RED "khol: Expected digit after '!' for history recollection.\n" RESET);
}
else {
args = split_line(line);
}
if(args) {
status = execute(args);
free(args);
}
else {
status = 1;
}
}
free(prompt);
free(line);
} while ( status );
free(history_path);
}
int main(int argc, char* argv[]) {
main_loop();
return EXIT_SUCCESS;
}