post
poster: psYchotic
description: SimpleShell - school assigment
language: C
[download]
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
/******************************************************************************
 * The MIT License
 *
 * Copyright (c) 2010 Stefan 'psYchotic' Zwanenburg
 *
 * 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.
 *****************************************************************************/

#define _GNU_SOURCE
#include <errno.h>
#include <pwd.h>
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

/**
 * Counts the number of spaces in a string.
 * @param input the string to check for spaces
 * @return the number of spaces in the input string
 */
int count_spaces(char *input) {
    int spaces = 0;
    char *offset = input;
    while ((offset = strchr(offset, ' ')) != NULL) {
        spaces++;
        offset++;
    }

    return spaces;
}

/**
 * Splits the input into an array of words.
 * Note that the allocated memory for the returned array
 * may exceed what is required in order to store all words.
 * This does not in any way pose a problem.
 * Every element in the returned array should be freed,
 * along with the array itself.
 * @param input the string to be split into words
 * @return an array of words
 */
char **split_input(char *input) {
    int words = count_spaces(input) + 1;
    int i = 0;
    char *single_word;
    char **split = malloc(sizeof(char *) * (words+1));

    single_word = strtok(input, " ");
    do {
        split[i++] = strdup(single_word);
    } while ((single_word = strtok(NULL, " ")) != NULL);

    split[i] = NULL;

    return split;
}

/**
 * Exits the shell.
 * @return non-zero on success (no arguments were passed), zero otherwise.
 */
int exit_cmd(char **argv) {
    if (argv[0] != NULL) {
        fprintf(stderr, "The 'exit' builtin does not take any arguments.\n");
        return 0;
    } else {
        return 1;
    }
}

/**
 * Sends a signal to a list of PIDs.
 * In this implementation, the SIGTERM (15) signal is sent. If an error
 * occurs whilst trying to send said signal, a message is printed on stderr.
 * Inversely, when sending the signal succeeds, a message is printed on stdout
 * to notify the user.
 * @return always zero
 */
int kill_cmd(char **argv) {
    int i;
    pid_t pid;
    if (argv[0] == NULL) {
        printf("The 'kill' builtin takes at least one argument (a PID).\n");
    } else {
        for (i = 0; argv[i] != NULL; i++) {
            if (sscanf(argv[i], "%d", &pid)) {
                if (kill(pid, SIGTERM)) {
                    fprintf(stderr, "Couldn't kill the process with PID %d: %s\n", pid, strerror(errno));
                } else {
                    fprintf(stderr, "Killed (or sent signal %d) to PID %d.\n", SIGTERM, pid);
                }
            } else {
                printf("%s is not a valid PID. Skipping.\n", argv[i]);
            }
        }
    }

    return 0;
}

/**
 * Changes the current working directory.
 * Note that the actual changing of the current working directory may fail,
 * in which case an error is printed on stderr. This command takes a single
 * argument: the directory to change to.
 * @return always zero
 */
int cd_cmd(char **argv) {
    char *todir;
    if (argv[0] == NULL) {
        struct passwd *passwd = getpwuid(getuid());
        if (passwd == NULL) {
            fprintf(stderr, "Could not get the current user's home directory: %s\n", strerror(errno));
        } else {
            todir = passwd->pw_dir;
        }
    } else if (argv[1] == NULL) {
        todir = argv[0];
    } else {
        fprintf(stderr, "The 'cd' builtin takes at most one argument (the directory to move to).\n");
        return 0;
    }

    if (chdir(todir)) {
        fprintf(stderr, "Could not change the current working directory to '%s': %s.\n", todir, strerror(errno));
    }

    return 0;
}


/**
 * Handles a line of input.
 * This function handles a line of input, which may
 * result in two things:
 *  - a builtin command is executed
 *  - the process forks and launches the application
 *      specified in the input string
 * @param input a string representing a single line of input
 * @return zero to indicate the main program should continue,
 *  non-zero otherwise.
 */
int handle_input(char *input) {
    int return_value = 0;
    pid_t pid;
    char **argv;
    int wait_status;
    int i;
    if (input == NULL) {
        printf("exit\n");
        return_value = 1;
    } else if (input[0] == '\0') {
        /* do nothing */
    } else {
        argv = split_input(input);
        if (history_length == 0 || history_search_pos(input, 1, 0) == -1) {
            add_history(input);
        }
        free(input);
        if (!strcmp(argv[0], "exit")) {
            return_value = exit_cmd(&argv[1]);
        } else if(!strcmp(argv[0], "kill")) {
            return_value = kill_cmd(&argv[1]);
        } else if (!strcmp(argv[0], "cd")) {
            return_value = cd_cmd(&argv[1]);
        } else {
            pid = fork();
            if (pid == 0) {
                if (execvp(argv[0], argv)) {
                    fprintf(stderr, "Could not execute '%s': %s\n", argv[0], strerror(errno));
                }
                return_value = 1;
            } else {
                while (!waitpid(pid, &wait_status, 0) && WIFEXITED(wait_status));
                for (i = 0; argv[i] != NULL; i++) {
                    free(argv[i]);
                }
                free(argv);
            }
        }
    }

    return return_value;
}

/**
 * Reads a line of input from stdin.
 * This function is mainly here for modularity,
 * meaning that if I need or want to change the way
 * I get input, I would do it here once.
 * @param prompt the prompt string to display
 * @return a string containing a line of input
 */
char *get_input(char *prompt) {
    char *line;
    char *cwd;
    char *local_prompt;
    if (prompt == NULL) {
        cwd = get_current_dir_name();
        if (cwd == NULL) {
            cwd = "?";
        }

        struct passwd *passwd = getpwuid(getuid());
        char *username = "?";
        if (passwd != NULL) {
            username = passwd->pw_name;
        }

        local_prompt = malloc(sizeof(char) * (strlen(cwd) + strlen(username) + 4));
        local_prompt[0] = '\0';
        strcat(local_prompt, username);
        strcat(local_prompt, "@");
        if (passwd != NULL && strstr(cwd, passwd->pw_dir) != NULL) {
            strcat(local_prompt, "~");
            strcat(local_prompt, cwd+strlen(passwd->pw_dir));
        } else {
            strcat(local_prompt, cwd);
        }
        strcat(local_prompt, "$ ");
    }

    line = readline(local_prompt);

    if (prompt == NULL) {
        if (strcmp(cwd, "?")) {
            free(cwd);
        }
        free(local_prompt);
    }

    return line;
}

/**
 * Prints help.
 * @param the name of the current program.
 */
void print_usage(char *progname) {
    printf("Usage: %s [OPTIONS]\n", progname);
    printf("  Options:\n");
    printf("    -p <prompt>     The prompt to be displayed\n");
    printf("    -h              Display this help\n");
}

int main(int argc, char **argv) {
    char *prompt = NULL;
    char *input;
    char option;
    while ((option = getopt(argc, argv, ":hp:")) != -1) {
        switch(option) {
            case 'h':
                print_usage(argv[0]);
                exit(EXIT_SUCCESS);
                break;
            case 'p':
                prompt = optarg;
                break;
            case ':':
                printf("Missing argument for option '%c'.\n", optopt);
                print_usage(argv[0]);
                exit(EXIT_FAILURE);
                break;
            case '?':
                printf("Unknown option '%c'.\n", optopt);
                print_usage(argv[0]);
                exit(EXIT_FAILURE);
            default:
                print_usage(argv[0]);
                exit(EXIT_SUCCESS);
                break;
        }
    }

    using_history();

    do {
        input = get_input(prompt);
    } while (!handle_input(input));

    return 0;
}