- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.cpp
More file actions
Latest commit
628 lines (535 loc) · 15.9 KB
/
Copy pathshell.cpp
File metadata and controls
628 lines (535 loc) · 15.9 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
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
#include<cstdlib>
#include<iostream>
#include<map>
#include<sstream>
#include<string>
#include<vector>
//#include <locale.h>
#include<readline/readline.h>
#include<readline/history.h>
#include"builtins.h"
// Potentially useful #includes (either here or in builtins.h):
// #include <dirent.h>
// #include <errno.h>
// #include <fcntl.h>
// #include <signal.h>
#include<sys/errno.h>
// #include <sys/param.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
usingnamespacestd;
map<string,string> aliases;
// The characters that readline will use to delimit words
constchar* constWORD_DELIMITERS = "\t\n\"\\'`@><=;|&{(";
// An external reference to the execution environment
externchar** environ;
// Define 'command' as a type for built-in commands
typedefint (*command)(vector<string>&);
// A mapping of internal commands to their corresponding functions
map<string, command> builtins;
// Variables local to the shell
map<string, string> localvars;
HIST_ENTRY **the_history_list;
// Handles external commands, redirects, and pipes.
intexecute_external_command(vector<string>& tokens) {
string command=tokens[0];
bool bkgrnd=false;
char* args[tokens.size()+1];
char* envpath=getenv("PATH");
char* path=(char*)(malloc(sizeof(char)*1024));
strcpy(path,envpath);
char delim=':';
while(path!=NULL){
char* filetotest=strsep(&path,&delim);
string file=filetotest;
file.append("/");
file.append(command);
if(access(file.c_str(),F_OK)==0){
args[0]=(char*)(malloc(file.length()*sizeof(char)));
strcpy(args[0],file.c_str());
for(unsignedint i=1;i<tokens.size();i++){
if(tokens[i]=="&"){
bkgrnd=true;
continue;
}
args[i]=(char*)(malloc(tokens[i].length()*sizeof(char)));
strcpy(args[i],tokens[i].c_str());
}
if (bkgrnd)
{
args[tokens.size()-1]=NULL;
FILE* fp=fopen("/dev/null","w");
dup2(fileno(fp),1);
close(fileno(fp));
}
else{
args[tokens.size()]=NULL;
}
int cpid=fork();
switch(cpid){
case -1:
//Error
perror("ERROR: could not fork\n");
return -1;
case0:
//child
execvp(args[0],args);
perror("exec failure");
return -1;
default:
//parent
int status=0;
if (!bkgrnd)
{
wait(&status);
}
return status;
}
}
}
fprintf(stderr, "%s: Command not found\n",command.c_str());
return1;
}
// Return a string representing the prompt to display to the user. It needs to
// include the current working directory and should also use the return value to
// indicate the result (success or failure) of the last command.
string get_prompt(int return_value) {
string prompt="";
if(return_value!=0){
prompt="X ";
}
prompt+=pwd()+"> ";
return prompt;
}
// Return one of the matches, or NULL if there are no more.
char* pop_match(vector<string>& matches) {
if (matches.size() > 0) {
constchar* match = matches.back().c_str();
// Delete the last element
matches.pop_back();
// We need to return a copy, because readline deallocates when done
char* copy = (char*) malloc(strlen(match) + 1);
strcpy(copy, match);
return copy;
}
// No more matches
returnNULL;
}
boolstartsWith(string word,string init){
return word.substr(0, init.size())==init;
}
boolexists(string str,string delim){
string::size_type loc=str.find(delim, 0);
return loc!=string::npos;
}
//Split a str by char into a vector
vector<string> split(string str, char delim){
stringstream ss(str);
string item;
vector<string> retObj;
while(getline(ss, item, delim)){
if(item != "") retObj.push_back(item);
}
return retObj;
}
// Generates environment variables for readline completion. This function will
// be called multiple times by readline and will return a single cstring each
// time.
char* environment_completion_generator(constchar* text, int state) {
// A list of all the matches;
// Must be static because this function is called repeatedly
static vector<string> matches;
// If this is the first time called, construct the matches list with
// all possible matches
if (state == 0) {
for(unsignedint i=0;i<sizeof(environ);i++){
vector<string> toks=split(string(environ[i]),'=');
string var = toks[0];
if(startsWith("$" + var, string(text))){
matches.push_back("$" + var);
}
}
for (map<string, string>::iterator it = localvars.begin(); it != localvars.end(); it++) {
if (startsWith("$" + (it->first), string(text))) {
matches.push_back("$" + string(it->first));
}
}
}
// Return a single match (one for each time the function is called)
returnpop_match(matches);
}
// Generates commands for readline completion. This function will be called
// multiple times by readline and will return a single cstring each time.
char* command_completion_generator(constchar* text, int state) {
// A list of all the matches;
// Must be static because this function is called repeatedly
static vector<string> matches;
// If this is the first time called, construct the matches list with
// all possible matches
if (state == 0) {
for(map<string, command>::iterator it = builtins.begin(); it != builtins.end(); ++it){
if(startsWith(it->first, string(text))) matches.push_back(it->first);
}
string path = string(getenv("PATH"));
vector<string> paths = split(path, ':');
for(unsignedint i = 0; i < paths.size(); ++i){
//cout << paths[i] << endl;
DIR* curDir = opendir(paths[i].c_str());
if(curDir){
structdirent *pDirent;
while ((pDirent = readdir(curDir)) != NULL) {
if(startsWith(pDirent->d_name, string(text))) matches.push_back(string(pDirent->d_name));
}
}
else{
perror("Cannot open dir");
}
closedir(curDir);
}
}
// Return a single match (one for each time the function is called)
returnpop_match(matches);
}
// This is the function we registered as rl_attempted_completion_function. It
// attempts to complete with a command, variable name, or filename.
char** word_completion(constchar* text, int start, int end) {
char** matches = NULL;
if (start == 0) {
rl_completion_append_character = '';
matches = rl_completion_matches(text, command_completion_generator);
} elseif (text[0] == '$') {
rl_completion_append_character = '';
matches = rl_completion_matches(text, environment_completion_generator);
} else {
rl_completion_append_character = '\0';
// We get directory matches for free (thanks, readline!)
}
return matches;
}
// Transform a C-style string into a C++ vector of string tokens, delimited by
// whitespace.
vector<string> tokenize(constchar* line) {
vector<string> tokens;
string token;
// istringstream allows us to treat the string like a stream
istringstream token_stream(line);
while (token_stream >> token) {
tokens.push_back(token);
}
// Search for quotation marks, which are explicitly disallowed
for (size_t i = 0; i < tokens.size(); i++) {
if (tokens[i].find_first_of("\"'`") != string::npos) {
cerr << "\", ', and ` characters are not allowed." << endl;
tokens.clear();
}
}
return tokens;
}
char* detokenize(const vector<string> tokens){
string temp=""; //shut up
for(unsignedint i=0;i<tokens.size();i++){
temp+=tokens[i];
if(i!=tokens.size()-1){
temp+="";
}
}
char* final=(char*)(malloc(temp.length()*sizeof(char)));
strcpy(final,temp.c_str());
returnfinal;
}
char* detokenize(const vector<string> tokens,constint index, const string replace){
char temp[1024];
for(int i=0;i<index;i++){
strcat(temp,tokens[i].c_str());
strcat(temp,"");
}
strcat(temp,replace.c_str());
strcat(temp,"");
for(unsignedint j=index+1;j<tokens.size();j++){
strcat(temp,tokens[j].c_str());
if(j!=tokens.size()-1){
strcat(temp,"");
}
}
char* final=temp;
returnfinal;
}
intexecute_line(vector<string>&,map<string,command>&);
intpipeit(vector<string> tokens,unsignedint index){
vector<string> firstline;
vector<string> secondline;
for(unsignedint i=0;i<tokens.size();i++){
if(i==index){
continue;
}
elseif(i<index){
firstline.push_back(tokens[i]);
}
else{
secondline.push_back(tokens[i]);
}
}
//redirect from a file
if(tokens[index]=="<"){
if(secondline.size()!=1){
fprintf(stderr,"ERROR: expected exactly one file descriptor as pipe input\n");
return -1;
}
elseif(access(secondline[0].c_str(),R_OK | F_OK)!=0){
perror("myshell:");
return -1;
}
char* fname=(char*)(malloc(sizeof(char)*secondline[0].length()-1));
strcpy(fname,secondline[0].c_str());
constchar mode='r';
constchar* modeptr=&mode;
FILE* fp=fopen(fname,modeptr);
int stdIn=dup(0);
dup2(fileno(fp),0);
close(fileno(fp));
int return_value=execute_line(firstline,builtins);
dup2(stdIn,0);
close(stdIn);
return return_value;
}
//redirect to a file
elseif(tokens[index]==">"){
if(secondline.size()!=1){
fprintf(stderr,"ERROR: expected exactly one file descriptor as pipe output\n");
return -1;
}
char* fname=(char*)(malloc(sizeof(char)*secondline[0].length()-1));
strcpy(fname,secondline[0].c_str());
constchar mode='w';
constchar* modeptr=&mode;
FILE* fp=fopen(fname,modeptr);
int stdOut=dup(1);
dup2(fileno(fp),1);
close(fileno(fp));
int return_value=execute_line(firstline,builtins);
dup2(stdOut,1);
close(stdOut);
return return_value;
}
//append to a file
elseif(tokens[index]==">>"){
if(secondline.size()!=1){
fprintf(stderr,"ERROR: expected exactly one file descriptor as pipe output\n");
return -1;
}
char* fname=(char*)(malloc(sizeof(char)*secondline[0].length()-1));
strcpy(fname,secondline[0].c_str());
constchar mode='a';
constchar* modeptr=&mode;
FILE* fp=fopen(fname,modeptr);
int stdOut=dup(1);
dup2(fileno(fp),1);
close(fileno(fp));
int return_value=execute_line(firstline,builtins);
dup2(stdOut,1);
close(stdOut);
return return_value;
}
//command piping
elseif(tokens[index]=="|"){
if(secondline.size()==0||firstline.size()==0){
fprintf(stderr, "ERROR, expected at least one command at both ends of pipe\n");
}
int pip[2];
if(pipe(pip)<0){
perror("pipe failure");
return -1;
}
int parentstatus=0;
int childstatus=0;
switch(fork()){
case -1:
{
close(pip[0]);
close(pip[1]);
perror("fork failure");
return -1;
}
case0:
{
//child
close(pip[1]);
int stdIn=dup(0);
dup2(pip[0],0);
close(pip[0]);
execute_line(secondline,builtins);
dup2(stdIn,0);
close(stdIn);
break;
}
default:
{
//parent
close(pip[0]);
int stdOut=dup(1);
dup2(pip[1],1);
close(pip[1]);
parentstatus=execute_line(firstline,builtins);
dup2(stdOut,1);
close(stdOut);
int status;
wait(&status);
childstatus=status;
break;
}
}
if(childstatus!=0){
return childstatus;
}
elseif(parentstatus!=0){
return parentstatus;
}
return0;
}
return0;
}
// Executes a line of input by either calling execute_external_command or
// directly invoking the built-in command.
intexecute_line(vector<string>& tokens, map<string, command>& builtins) {
int return_value = 0;
if (tokens.size() != 0) {
//replaces aliases with their values before executing
for(unsignedint i=0;i<tokens.size();i++){
map<string, string>::iterator alias=aliases.find(tokens[i]);
if(alias!=aliases.end()){
tokens[i]=aliases[tokens[i]];
}
}
while(true){
bool replaced=false;
//replaces bangs with commands
for(unsignedint i=0;i<tokens.size();i++){
if(tokens[i][0]=='!'&&tokens[i][1]=='!'){
HIST_ENTRY* lastCMD=previous_history();
char* newTokens=detokenize(tokens,i,lastCMD->line);
tokens=tokenize(newTokens);
history_set_pos(history_length-1);
replaced=true;
break;
}
elseif(tokens[i][0]=='!'){
string number=tokens[i].substr(1,tokens[i].length()-1);
int offset=history_length-atoi(number.c_str());
history_set_pos(offset);
HIST_ENTRY* lastcmd=current_history();
char* newtokens=detokenize(tokens,i,lastcmd->line);
tokens=tokenize(newtokens);
history_set_pos(history_length-1);
replaced=true;
break;
}
}
if(!replaced){
break;
}
}
bool pipe=false;
unsignedint index;
for(unsignedint i=0;i<tokens.size();i++){
if(tokens[i]=="|"||tokens[i]=="<"||tokens[i]==">"||tokens[i]==">>"){
pipe=true;
index=i;
break;
}
if(pipe)break;
}
if(pipe){
returnpipeit(tokens,index);
}
map<string, command>::iterator cmd = builtins.find(tokens[0]);\
if (cmd == builtins.end()) {
return_value = execute_external_command(tokens);
}
else{
return_value = ((*cmd->second)(tokens));
}
}
return return_value;
}
// Substitutes any tokens that start with a $ with their appropriate value, or
// with an empty string if no match is found.
voidvariable_substitution(vector<string>& tokens) {
vector<string>::iterator token;
for (token = tokens.begin(); token != tokens.end(); ++token) {
if (token->at(0) == '$') {
string var_name = token->substr(1);
if (getenv(var_name.c_str()) != NULL) {
*token = getenv(var_name.c_str());
} elseif (localvars.find(var_name) != localvars.end()) {
*token = localvars.find(var_name)->second;
} else {
*token = "";
}
}
}
}
// Examines each token and sets an env variable for any that are in the form
// of key=value.
voidlocal_variable_assignment(vector<string>& tokens) {
vector<string>::iterator token = tokens.begin();
while (token != tokens.end()) {
string::size_type eq_pos = token->find("=");
// If there is an equal sign in the token, assume the token is var=value
if (eq_pos != string::npos) {
string name = token->substr(0, eq_pos);
string value = token->substr(eq_pos + 1);
localvars[name] = value;
token = tokens.erase(token);
} else {
++token;
}
}
}
// The main program
intmain() {
// Populate the map of available built-in functions
builtins["ls"] = &com_ls;
builtins["cd"] = &com_cd;
builtins["pwd"] = &com_pwd;
builtins["alias"] = &com_alias;
builtins["unalias"] = &com_unalias;
builtins["echo"] = &com_echo;
builtins["exit"] = &com_exit;
builtins["history"] = &com_history;
// Specify the characters that readline uses to delimit words
rl_basic_word_break_characters = (char *) WORD_DELIMITERS;
// Tell the completer that we want to try completion first
rl_attempted_completion_function = word_completion;
// The return value of the last command executed
int return_value = 0;
// Loop for multiple successive commands
while (true) {
// Get the prompt to show, based on the return value of the last command
string prompt = get_prompt(return_value);
// Read a line of input from the user
char* line = readline(prompt.c_str());
// If the pointer is null, then an EOF has been received (ctrl-d)
if (!line) {
break;
}
// If the command is non-empty, attempt to execute it
if (line[0]) {
// Add this command to readline's history
add_history(line);
// Break the raw input line into tokens
vector<string> tokens = tokenize(line);
// Handle local variable declarations
if(tokens[0]!="alias"){
local_variable_assignment(tokens);
}
// Substitute variable references
variable_substitution(tokens);
// Execute the line
return_value = execute_line(tokens, builtins);
}
// Free the memory for the input string
free(line);
}
return0;
}