-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
467 lines (390 loc) · 12.4 KB
/
main.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
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <string.h>
#include <unistd.h>
#include <sys/errno.h>
#include <sys/fcntl.h>
#include "list.h"
#include "builtin.h"
#include "main.h"
int main_pid;
generic_list background_jobs;
generic_list env_variables;
/*
* Helper functions (signal handling, freeing memory, printing, iterating
*/
void SIGINT_handler(int signal_number) {
printf("\n[%d] Signal: %d\n", getpid(), signal_number);
if(signal_number == 18 && getpid() != main_pid) {
kill(getpid(), SIGSTOP);
}
}
void free_string(void *data) {
free(*(char **)data);
}
void free_input_redirect(void *data) {
free(*(struct _input_redirect **)data);
}
void free_bck_job(void *data) {
free(*(struct _background_job_struct **)data);
}
void free_env_var(void *data) {
free(*(struct _kvp **)data);
}
void print_input_redirect(InputRedirect* redirect) {
printf("Type: %d, file: %s\n", redirect->TYPE, redirect->file);
}
void print_args(char** args) {
int _iter = 0;
while(args[_iter]) {
printf("[%d]: %s\n", _iter, args[_iter]);
_iter++;
}
}
int num_or_args(char** args) {
int _iter = 0;
while(args[_iter]) {
_iter++;
}
return _iter;
}
int chain_length(Command* cmd) {
int _iter = 0;
Command* tmp = cmd;
while(tmp) {
_iter++;
tmp = tmp->next;
}
return _iter;
}
bool iterate_string(void *data) {
printf("%s ", *(char **)data);
return TRUE;
}
bool iterate_redirect(void *data) {
print_input_redirect(*(InputRedirect **)data);
return TRUE;
}
void redir(generic_list redirects) {
FILE* fd;
int i = 0;
listNode* _tmp = redirects.head;
while(_tmp) {
InputRedirect* _redir = *(InputRedirect **) _tmp->data;
char* mode = (_redir->TYPE == 0) ? "r" : ((_redir->TYPE == 1) ? "w+" : "a");
print_input_redirect(_redir);
printf("Opening file (%s): %s\n", mode, _redir->file);
fd = fopen(_redir->file, mode);
if (fd == NULL) {
perror("Error");
} else {
printf("File opened!\n");
if (_redir->TYPE > 0) dup2(fileno(fd), 1);
else dup2(fileno(fd), STDIN_FILENO);
fclose(fd);
}
_tmp = _tmp->next;
i++;
}
}
char** list_to_args(generic_list string_list) {
int _list_size = list_size(&string_list), _iter = 0;
char** _args = (char**) calloc((size_t) _list_size + 1, sizeof(char*));
listNode* elem = string_list.head;
while(elem != NULL) {
_args[_iter] = *(char **) elem->data;
elem = elem->next;
_iter++;
}
_args[_list_size] = 0;
return _args;
}
void print_command(Command* cmd) {
printf("\nExec: %s\nArguments (%d): ", cmd->command, list_size(&cmd->arguments));
list_for_each(&cmd->arguments, iterate_string);
printf("\nRedirects (%d): \n", list_size(&cmd->redirect));
list_for_each(&cmd->redirect, iterate_redirect);
printf("Is background? %d\n", cmd->is_background);
printf("-----------------\n");
if(cmd->next) print_command(cmd->next);
}
size_t get_words_count(char *line) {
size_t _iter = 0, _cnt = 0;
while(line[_iter]) {
if (line[_iter] == ' ') _cnt++;
_iter++;
}
return _iter;
}
char** isolate_words_from_stream(char *line) {
int _iter = 0;
char * _part;
char ** _words = (char**) calloc(get_words_count(line), sizeof(char*));
_part = strtok (line, " ");
while (_part != NULL) {
_words[_iter] = _part;
_part = strtok (NULL, " ");
_iter++;
}
return _words;
}
/*
* Background jobs
*/
void add_background_job(char* name, pid_t pid) {
BackgroundJob* bck_job = (BackgroundJob*) malloc(sizeof(BackgroundJob));
bck_job->command = name;
bck_job->job_pid = pid;
list_append(&background_jobs, &bck_job);
}
generic_list get_bck_jobs() {
return background_jobs;
}
void check_bck_jobs(bool print_all_statuses) {
int _status, _wait_stat, _iter = 0;
BackgroundJob* _bckjb;
listNode* _elem = background_jobs.head;
while(_elem != NULL) {
_bckjb = *(BackgroundJob**) _elem->data;
_wait_stat = waitpid(_bckjb->job_pid, &_status, WNOHANG);
if(_wait_stat == _bckjb->job_pid) {
printf("[%d] %d \t\tExited (%d), Signal: %d\n", _iter, _bckjb->job_pid, WEXITSTATUS(_status), WTERMSIG(_bckjb->job_pid));
_iter++;
} else if (_wait_stat == 0){
if(print_all_statuses) printf("[%d] %d \t\t%s - Running...\n", _iter, _bckjb->job_pid, _bckjb->command);
_iter++;
}
_elem = _elem->next;
}
}
/*
* Environment Variables
*/
void change_or_set_env_var(char* key, char* value) {
bool _found = FALSE;
EnvVariable* _cur;
listNode* elem = env_variables.head;
while(elem != NULL) {
_cur = *(EnvVariable **) (elem->data);
if(strcmp(_cur->key, key) == 0) {
_found = TRUE;
_cur->value = strdup(value);
}
elem = elem->next;
}
if(!_found) {
_cur = (EnvVariable*) malloc(sizeof(EnvVariable));
_cur->key = key;
_cur->value = value;
list_append(&env_variables, &_cur);
}
}
void print_env_vars() {
EnvVariable* _cur;
printf("%d\n",list_size(&env_variables));
list_head(&env_variables, &_cur, FALSE);
listNode* elem = env_variables.head;
while(elem != NULL) {
_cur = (*(EnvVariable **) elem->data);
printf("%s:%s\n", _cur->key, _cur->value);
elem = elem->next;
}
}
char* get_env_var(char* key) {
EnvVariable* _cur;
listNode* elem = env_variables.head;
while(elem != NULL) {
_cur = *(EnvVariable **) (elem->data);
if(strcmp(_cur->key, key) == 0) {
return strdup(_cur->value);
}
elem = elem->next;
}
return NULL;
}
/*
* Core functions (parsing, executing)
*/
Command* assemble_commands(char ** _parts) {
int _iter = 0, last_end = 0;
bool _input_redirect_file = FALSE;
Command* _current_command;
Command* _cmds_list_head = (Command*) malloc(sizeof(Command));
InputRedirect* _inputRedirect = (InputRedirect*) malloc(sizeof(InputRedirect));
_current_command = _cmds_list_head;
_current_command->next = NULL;
list_new(&_current_command->arguments, sizeof(char*), free_string);
list_new(&_current_command->redirect, sizeof(InputRedirect*), free_input_redirect);
while (_parts[_iter]) {
// Check if it's the beginning of the redirect object
if (_parts[_iter][0] == '<') {
_input_redirect_file = TRUE;
_inputRedirect->TYPE = 0;
} else if (_parts[_iter][0] == '>') {
_input_redirect_file = TRUE;
if(_parts[_iter][1] && _parts[_iter][1] == '>') _inputRedirect->TYPE = 2;
else _inputRedirect->TYPE = 1;
}
// If predecessor was redirect, second part must be a file
else if(_input_redirect_file) {
char *tmp = strdup(_parts[_iter]);
_input_redirect_file = FALSE;
_inputRedirect->file = tmp;
list_append(&_current_command->redirect, &_inputRedirect);
_inputRedirect = (InputRedirect*) malloc(sizeof(InputRedirect));
last_end = _iter + 1;
}
// Stream - it's end of current command, create new one and assign pointer
else if(_parts[_iter][0] == '|') {
Command* _new_command = (Command*) malloc(sizeof(Command));
_current_command->next = _new_command;
_current_command = _new_command;
list_new(&_current_command->arguments, sizeof(char*), free_string);
list_new(&_current_command->redirect, sizeof(InputRedirect*), free_input_redirect);
last_end = _iter + 1;
}
// & - announces it's background command
else if(_parts[_iter][0] == '&') {
_current_command->is_background = TRUE;
}
// Base command
else if(_iter == last_end) {
_current_command->command = strdup(_parts[_iter]);
}
// Else it's just command supplier
else {
char* tmp = strdup(_parts[_iter]);
list_append(&_current_command->arguments, &tmp);
}
_iter++;
}
return _cmds_list_head;
}
int spawn_proc (int in, int out, Command* cmd) {
pid_t pid;
int status = 0;
list_prepend(&cmd->arguments, &cmd->command);
if ((pid = fork ()) == 0) {
if (in != 0) {
dup2 (in, 0);
close (in);
}
if (out != 1) {
dup2 (out, 1);
close (out);
}
redir(cmd->redirect);
execvp (cmd->command, (char * const *) list_to_args(cmd->arguments));
exit(errno);
}
waitpid(pid, &status, WCONTINUED);
return pid;
}
int fork_pipes (Command *cmd) {
int i, n = chain_length(cmd), in = 0, fd [2];
pid_t last_pid;
Command* tmp = cmd;
for (i = 0; i < n - 1; i++) {
pipe (fd);
/* f [1] is the write end of the pipe, we carry `in` from the prev iteration. */
spawn_proc (in, fd [1], tmp);
/* No need for the write end of the pipe, the child will write here. */
close (fd [1]);
/* Keep the read end of the pipe, the next child will read from there. */
in = fd [0];
tmp = tmp->next;
}
int status = 0;
list_prepend(&tmp->arguments, &tmp->command);
if((last_pid = fork()) == 0) {
if (in != 0 && n > 1) {
printf("Reading from previous...");
dup2 (in, 0);
} // Read from previous job
redir(tmp->redirect);
execvp (tmp->command, list_to_args(tmp->arguments));
exit(errno);
}
else {
int _option = tmp->is_background ? WNOHANG : WCONTINUED;
if(tmp->is_background) {
add_background_job(tmp->command, last_pid);
printf("%d\n", last_pid);
}
waitpid(last_pid, &status, _option);
free(cmd);
return status;
}
}
void execute_command(Command* cmd) {
int builtin_num = -1, chld_status = 0;
char str[15];
// Check if entered command isn't already implemented
builtin_num = is_builtin(cmd->command);
if (builtin_num > -1) {
chld_status = (*builtin_func[builtin_num]) (list_to_args(cmd->arguments));
} else {
// Check if it's get env variable related command
if(cmd->command[0] == '$' && cmd->command[1]) {
char* key = cmd->command;
key++;
char* value = get_env_var(key);
if(value != NULL) {
printf("%s\n", value);
} else {
printf("(null)\n");
}
}
// If command has '=' sign, we're assuming it's env variable change
else if(strchr(cmd->command, '=') != NULL) {
const char breaking[2] = "=";
char* key = strtok(cmd->command, breaking);
char* value = strtok(cmd->command, breaking);
change_or_set_env_var(key , value);
}
// Else we assume it's command to be execvp'ed
else {
chld_status = fork_pipes(cmd);
}
}
chld_status = chld_status >> 8;
printf("S: %d\n", chld_status);
sprintf(str, "%d", chld_status);
change_or_set_env_var("?", str);
}
int main(int argc, char** argv) {
Command *cmd;
main_pid = getpid();
list_new(&background_jobs, sizeof(BackgroundJob*), free_bck_job);
list_new(&env_variables, sizeof(EnvVariable*), free_env_var);
change_or_set_env_var("?", "0");
if(argc >= 2) {
int i = 0;
char** arguments = (char**) calloc(sizeof(char*), (size_t) argc);
for(i = 0; i < argc - 1; i++) {
arguments[i] = argv[i + 1];
}
arguments[argc] = 0;
cmd = assemble_commands(arguments);
execute_command(cmd);
} else {
char* line;
signal(SIGINT, SIGINT_handler);
signal(SIGTSTP, SIGINT_handler);
signal(SIGCONT, SIGINT_handler);
while((line = readline("sh $ ")) != NULL) {
if(*line) {
add_history(line);
check_bck_jobs(FALSE);
cmd = assemble_commands(isolate_words_from_stream(line));
free(line);
execute_command(cmd);
}
}
printf("\nInterpreter closed.\n");
exit(0);
}
}