├── .gitattributes ├── .gitignore ├── logo.txt ├── .travis.yml ├── alias.h ├── .jsh_travis_test_script.sh ├── jsh-completion.h ├── jsh-parse.h ├── jsh-colors.h ├── README.md ├── jsh-common.h ├── CHANGELOG.md ├── mini-grep.c ├── CONTRIBUTING.md ├── jsh-man.1 ├── Makefile ├── jsh-common.c ├── alias.c ├── jsh-completion.c ├── installer.sh ├── jsh-parse.c ├── jsh.c └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | # override the auto-detected language for some C files that github classifies as C++ 2 | jsh-colors.h linguist-language=C 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled object files 2 | *.o 3 | # the linked binary 4 | jsh 5 | # gedit backup files 6 | *~ 7 | 8 | .fuse_hidden* 9 | 10 | # the man page generated by the Makefile 11 | jsh.1 12 | -------------------------------------------------------------------------------- /logo.txt: -------------------------------------------------------------------------------- 1 | _ __ 2 | (_)__ / / 3 | / (_- /dev/null 2>&1 10 | - echo "source ./.jsh_travis_test_script.sh" | ./jsh --nodebug --norc 11 | 12 | # disable all email notifications 13 | # notifications: 14 | # email: false 15 | -------------------------------------------------------------------------------- /alias.h: -------------------------------------------------------------------------------- 1 | /* This file is part of jsh. 2 | * 3 | * jsh: A basic UNIX shell implementation in C 4 | * Copyright (C) 2014 Jo Van Bulck 5 | * 6 | * jsh is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * jsh is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with jsh. If not, see . 18 | */ 19 | 20 | #ifndef ALIAS_H_INCLUDED 21 | #define ALIAS_H_INCLUDED 22 | /* ^^ these are the include guards */ 23 | 24 | #include "jsh-common.h" 25 | #include "jsh-parse.h" 26 | 27 | int alias(char*, char*); 28 | int unalias(char* key); 29 | int printaliases(); 30 | char *resolvealiases(char*); 31 | bool alias_exists(char*); 32 | char **get_all_alias_keys(unsigned int*, bool); 33 | #endif //ALIAS_H_INCLUDED 34 | -------------------------------------------------------------------------------- /.jsh_travis_test_script.sh: -------------------------------------------------------------------------------- 1 | ## a file containing some test commands to be executed by jsh each time 2 | ## Travis CI triggers a new build 3 | 4 | echo -e "\\n\\033[1;36m----------- START OF JSH_TRAVIS_TEST_SCRIPT -----------\\033[0m\\n" 5 | 6 | echo Hi I am running jsh --version : 7 | echo "--------------------------" 8 | ./jsh --version 9 | echo -e "--------------------------\\n" 10 | 11 | alias grep "grep --color=auto -i" 12 | alias ll ls\ -lh # some inline comment 13 | echo -e "this is the output of alias:\\n--------------------------" ; alias 14 | echo -e "--------------------------\\n" 15 | 16 | echo "this is the output of \"ll | grep alias\"" && ll | grep alias 17 | 18 | echo -e "\\nthis is the output of \"ll | grep alias | wc\"" && ll | grep alias | wc 19 | 20 | echo -e "\\nnow triggering some error messages: " 21 | 22 | # a long comment: loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong 23 | 24 | some_none_existing_command 25 | 26 | echo -e "\\n\\033[1;36m----------- END OF JSH_TRAVIS_TEST_SCRIPT -----------\\033[0m\\n" 27 | -------------------------------------------------------------------------------- /jsh-completion.h: -------------------------------------------------------------------------------- 1 | /* This file is part of jsh. 2 | * 3 | * jsh: A basic UNIX shell implementation in C 4 | * Copyright (C) 2014 Jo Van Bulck 5 | * 6 | * jsh is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * jsh is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with jsh. If not, see . 18 | */ 19 | 20 | #ifndef COMPL_H_INCLUDED 21 | #define COMPL_H_INCLUDED 22 | /* ^^ these are the include guards */ 23 | 24 | #include "jsh-common.h" 25 | #include "jsh-parse.h" 26 | #include "alias.h" 27 | #include // GNU readline: http://cnswww.cns.cwru.edu/php/chet/readline/rltop.html 28 | 29 | extern const char *built_ins[]; 30 | extern const size_t nb_built_ins; 31 | 32 | /* 33 | * jsh_completion: a custom GNU readline completion function for jsh command completion. 34 | * This function is called by readline; if the result is non-NULL, readline wont perform 35 | * the default file completion. 36 | * @arg: from the readline manual: "start and end are indices in rl_line_buffer defining 37 | * the boundaries of text, which is a character string." 38 | * @return: an array of strings with the possible completions or NULL of no completions. 39 | */ 40 | char** jsh_command_completion(const char*, int, int); 41 | 42 | #endif //jsh-completion.h 43 | -------------------------------------------------------------------------------- /jsh-parse.h: -------------------------------------------------------------------------------- 1 | /* This file is part of jsh. 2 | * 3 | * jsh: A basic UNIX shell implementation in C 4 | * Copyright (C) 2014 Jo Van Bulck 5 | * 6 | * jsh is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * jsh is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with jsh. If not, see . 18 | */ 19 | 20 | #ifndef PARSE_H_INCLUDED 21 | #define PARSE_H_INCLUDED 22 | /* ^^ these are the include guards */ 23 | 24 | #include "jsh-common.h" 25 | #include "alias.h" 26 | 27 | struct comd { 28 | char **cmd; // NULL-terminated array of pointers to the command's name and its arguments 29 | int length; // the length of the **cmd array: cmd[length] = NULL 30 | char *inf; // name of the file for redirecting stdin or NULL 31 | char *outf; // name of the file for redirecting stdout or NULL 32 | char *errf; // name of the file for redirecting stderr or NULL 33 | int append_out; // whether or not stdout should append to the file, if redirected 34 | struct comd *next; // pointer to the next comd in the pipeline or NULL if no next 35 | }; 36 | typedef struct comd comd; 37 | 38 | /** 39 | * TODO also take aliases etc into account 40 | */ 41 | int parse_from_file(char *line); 42 | 43 | /* 44 | * parseexpr: parses the '\0' terminated expr string recursivly, according to the 'expr' grammar. 45 | * returns exit status (EXIT_SUCCESS || !EXIT_SUCCESS) of executed expression 46 | */ 47 | int parseexpr(char*); 48 | 49 | /* 50 | * is_valid_cmd: returns whether or not an occurence of a cmd string is valid in a given 51 | * context string. An cmd is valid iff it occurs as a comd in the grammar. 52 | * 53 | * @param cmd: the command string to be checked 54 | * @param context: the context string where the command occurs 55 | * @param i: the index in the context string where the command occurs: context+i equals cmd 56 | */ 57 | bool is_valid_cmd(const char*, const char*, int); 58 | 59 | #endif // jsh-parse.h 60 | -------------------------------------------------------------------------------- /jsh-colors.h: -------------------------------------------------------------------------------- 1 | /* This file is part of jsh. 2 | * 3 | * jsh: A basic UNIX shell implementation in C 4 | * Copyright (C) 2014 Jo Van Bulck 5 | * 6 | * jsh is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * jsh is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with jsh. If not, see . 18 | */ 19 | 20 | #ifndef JSH_COLORS_H_INCLUDED 21 | #define JSH_COLORS_H_INCLUDED 22 | 23 | // surround non-printing escape sequences with '\x01' and '\x02' for GNU readline lib 24 | // see e.g. http://bugs.python.org/issue20359 25 | 26 | // ANSI escape foreground color codes (see https://en.wikipedia.org/wiki/ANSI_escape_code) 27 | #define BLACK_FG "\x01\033[30m\x02" 28 | #define RED_FG "\x01\033[31m\x02" 29 | #define GREEN_FG "\x01\033[32m\x02" 30 | #define YELLOW_FG "\x01\033[33m\x02" 31 | #define BLUE_FG "\x01\033[34m\x02" 32 | #define MAGENTA_FG "\x01\033[35m\x02" 33 | #define CYAN_FG "\x01\033[36m\x02" 34 | #define WHITE_FG "\x01\033[37m\x02" 35 | #define RESET_FG "\x01\033[39m\x02" 36 | 37 | // ANSI escape background color codes 38 | #define BLACK_BG "\x01\033[40m\x02" 39 | #define RED_BG "\x01\033[41m\x02" 40 | #define GREEN_BG "\x01\033[42m\x02" 41 | #define YELLOW_BG "\x01\033[43m\x02" 42 | #define BLUE_BG "\x01\033[44m\x02" 43 | #define MAGENTA_BG "\x01\033[45m\x02" 44 | #define CYAN_BG "\x01\033[46m\x02" 45 | #define WHITE_BG "\x01\033[47m\x02" 46 | #define RESET_BG "\x01\033[49m\x02" 47 | 48 | // ANSI escape style color codes 49 | #define COLOR_RESET_ALL "\x01\033[0m\x02" // back to defaults 50 | #define COLOR_BOLD "\x01\033[1m\x02" // implemented as 'bright' on some terminals 51 | #define COLOR_RESET_BOLD "\x01\033[22m\x02" 52 | 53 | // (the following are not widely supported) 54 | #define COLOR_DIM "\x01\033[2m\x02" 55 | #define COLOR_UNDERLINE "\x01\033[3m\x02" 56 | #define COLOR_BLINK "\x01\033[4m\x02" 57 | #define COLOR_REVERSE "\x01\033[7m\x02" 58 | 59 | #endif // JSH_COLORS_H_INCLUDED 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ``` 3 | _ __ 4 | (_)__ / / 5 | / (_- `jsh` is a UNIX command interpreter (shell) that executes commands read from the standard input or from a file. `jsh` implements a subset of the `sh` language grammar and is intended to be POSIX-conformant. 15 | 16 | > `jsh` is written 'just for fun' and is not intented to be a full competitor to advanced UNIX shells such as `bash` and `zsh`. `jsh` is free software and you are welcome to collaborate on the github page or to redistribute jsh under the conditions of the GNU General Public License. 17 | 18 | ## Find out more 19 | 20 | | [About](https://github.com/jovanbulck/jsh/wiki/About) | [Installation guide](https://github.com/jovanbulck/jsh/wiki/Compiling-and-running) | [Configuration](https://github.com/jovanbulck/jsh/wiki/Sample-configuration-files) | [Manual](https://github.com/jovanbulck/jsh/wiki/Manual) | [Contributing](https://github.com/jovanbulck/jsh/blob/master/CONTRIBUTING.md) | 21 | |----|----------|----------|---------|---------| 22 | | [
](https://github.com/jovanbulck/jsh/wiki/About) | [
](https://github.com/jovanbulck/jsh/wiki/Compiling-and-running) | [
](https://github.com/jovanbulck/jsh/wiki/Sample-configuration-files) | [
](https://github.com/jovanbulck/jsh/wiki/Manual) | [
](https://github.com/jovanbulck/jsh/blob/master/CONTRIBUTING.md) | 23 | | Introducing the shell | Step-by-step guide to build `jsh`for your own system | Configuring the shell for your own use | Online text version of the latest `man jsh` | Info for developers | 24 | *(open source icons by Open Iconic — www.useiconic.com/open)* 25 | 26 | ## Get it! 27 | 28 | Download logo 30 | 31 | [This page](https://github.com/jovanbulck/jsh/releases/latest) provides pre-built binaries for all official `jsh` releases. To build `jsh` yourself, clone this respository, `cd` into it and execute `make`. See [the wiki page](https://github.com/jovanbulck/jsh/wiki/Compiling-and-running) for more info and dependencies overview. 32 | -------------------------------------------------------------------------------- /jsh-common.h: -------------------------------------------------------------------------------- 1 | /* This file is part of jsh. 2 | * 3 | * jsh: A basic UNIX shell implementation in C 4 | * Copyright (C) 2014 Jo Van Bulck 5 | * 6 | * jsh is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * jsh is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with jsh. If not, see . 18 | */ 19 | 20 | #ifndef JSH_COMMON_H_INCLUDED 21 | #define JSH_COMMON_H_INCLUDED 22 | /* ^^ these are the include guards */ 23 | 24 | // ########## common includes ########## 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | // ########## common macro definitions ######### 39 | #define ASSERT true // whether or not to include the assert statements in the pre-compilation phase 40 | #define MAX_FILE_LINE_LENGTH 200 // the max nb of chars per line in a file to parse 41 | 42 | #define REDIRECT_STR(fd1, fd2) \ 43 | if (dup2(fd1, fd2) < 0) { \ 44 | printerrno("Redirecting stream %d to %d failed", fd2, fd1); \ 45 | exit(EXIT_FAILURE); \ 46 | } 47 | 48 | #define CHK_ERR(cond, cmd) \ 49 | if (cond == -1) { \ 50 | printerrno("%s", cmd); \ 51 | return EXIT_FAILURE; \ 52 | } 53 | 54 | // hackhackhack: '\n' seems to be needed in tty 55 | #define RESTORE_COLOR(stream) \ 56 | if (IS_INTERACTIVE && COLOR) \ 57 | fprintf(stream, "%s\n", NONE); \ 58 | else \ 59 | fprintf(stream, "\n"); \ 60 | 61 | /* 62 | * A function that prints the provided '\0' terminated string verbatim on stdout, without 63 | * appending a newline '\n' character. 64 | * @note: inline function implementations should be in header 65 | * see (http://stackoverflow.com/questions/26503235/c-inline-funtion-and-gcc) 66 | */ 67 | static inline int puts_verbatim(const char *s) { 68 | return fputs(s, stdout); 69 | } 70 | 71 | // ######### linux tty color codes ######## 72 | #define RESET 0 73 | #define BRIGHT 1 74 | #define DIM 2 75 | #define UNDERLINE 3 76 | #define BLINK 4 77 | #define REVERSE 7 78 | #define HIDDEN 8 79 | 80 | #define BLACK 0 81 | #define RED 1 82 | #define GREEN 2 83 | #define YELLOW 3 84 | #define BLUE 4 85 | #define MAGENTA 5 86 | #define CYAN 6 87 | #define WHITE 7 88 | 89 | #define NONE "\033[0m" // to flush the previous property 90 | 91 | // common global variables 92 | extern bool DEBUG; 93 | extern bool COLOR; 94 | extern bool I_AM_FORK; // whether or not the current process is a fork, i.e. child process 95 | extern bool IS_INTERACTIVE; 96 | extern bool WAITING_FOR_CHILD; 97 | 98 | // common function definitions 99 | void printerr(const char*, ...); 100 | void printerrno(const char *format, ...); 101 | void printdebug(const char*, ...); 102 | void printinfo(const char*, ...); 103 | void textcolor(FILE*, int, int); 104 | 105 | void parsefile(char*, void (*f)(char*), bool); 106 | void parsestream(FILE*, char*, void (*f)(char*)); 107 | 108 | int string_cmp(const void*, const void*); 109 | bool is_sorted(void*, size_t, size_t, int (*compar)(const void *, const void *)); 110 | char *gethome(); 111 | char *strclone(const char*); 112 | char* concat(int, ...); 113 | // TODO malloc wrapper -- gracious 114 | 115 | #endif //JSH_COMMON_H_INCLUDED 116 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog for `jsh` 2 | 3 | This page lists all changes made to the `jsh` source code since [the latest release](https://github.com/jovanbulck/jsh/releases/latest). On commiting changes to the `master` branch, this page should be updated. 4 | 5 | ## Changes to be included in the next release (now in `master`) 6 | 7 | work towards a new release: 8 | 9 | #### prompt customizing (issue #3 ): 10 | prompt expansion options are fully documented in the `man` page. Short summary below: 11 | 12 | - coloring options for prompt: 13 | - %B turns on bold; %n restores normal 14 | - %f{color_name} enables foreground text coloring 15 | - %F{color_name} enables bold foreground text coloring 16 | - %b{color_name} enables background coloring 17 | - various new prompt expansion options : 18 | - %U colors user name red and bold iff sudo activated 19 | - %$ includes a '$' char or a '#' char iff sudo access is activated 20 | - %S includes the return value of the last executed shell command, colored red and bold iff non-zero 21 | - directory expansion %d enhancements: 22 | - truncate the directory to the first char *after* the first '/' within the cwd (else it looks like the root) 23 | - replace the current user's home directory with '~' in %d prompt expansion 24 | 25 | #### git support in prompt: 26 | - %g includes the git branch name iff the current working directory is a git repository 27 | - %c includes a bold and red '*' char iff the current working directory is a git repository and git indicates files have changed since the last commit 28 | 29 | #### technical things: 30 | - preprocessing of the prompt color options for max efficiency 31 | - fixed a bug to allow alias expansion when 'sourcing' files 32 | 33 | ## Changes for release 1.2.1 34 | 35 | jsh 1.2.1 fixes two minor bugs in the v1.2.0 release below: 36 | 37 | - Makefile fix for Mac OS X (defined empty variable) 38 | - `source` built_in bugfix allowing parsing of a file with `jsh` alias expansion 39 | 40 | ## Changes for release 1.2.0 41 | 42 | `jsh` 1.2.0 introduces some awesome new features on the user interface side: ;-) 43 | 44 | * Major new feature: context-sensitive custom GNU **readline completion**: 45 | - built_ins, aliases and a number of predefined UNIX commands 46 | - some custom completion for some specific UNIX commands: `git, apt-get, make, jsh, ...` 47 | * wrote a `dialog` based sh **installer shell script**, as discussed in issue #55 48 | * added a **jsh_logout file**, containing shell commands to be executed at logout of an interactive session 49 | * a new `source` built_in to interpret a given file line per line 50 | * fixed the ugly EOF (^D) exiting by outputting an extra newline iff EOF 51 | 52 | This release also includes some work on the more technical side: 53 | 54 | * **Makefile** enhancements: 55 | - now automatically builds a version string, containing info of the machine 56 | - auto-generate a man page with the filled in version number and data (using `sed`) 57 | - added a `make release` target for making releases with a release version string 58 | - various compile flags used by the installer 59 | * `alias` bugfix allowing redefinition of an alias 60 | * partially started the source code re-organizing into cohesive modules, as discussed in issue #46 61 | 62 | ## Changes for release 1.1.1 63 | 64 | * Format string vulnerability patch for the v1.1.0 release. 65 | 66 | Details: applied a format string vulnerability patch to the parsestream functions; passing `printf` may introduce format string vulnerabilities; one should pass the helper function `printf_verbatim` instead 67 | 68 | ## Changes for release 1.1.0 69 | 70 | * A minor improvement to the first stable jsh release: added a `--version` option to query the current version number. 71 | 72 | ## Changes for release 1.0.0 73 | 74 | The first stable `jsh` release! An overview of the major features: 75 | 76 | * `bash`-like shell grammar with support for: 77 | * logical expressions: `&& || ; ( ) # ""` 78 | * stream redirection: `< > >> 2> |` 79 | * commands with space delimited options: lookup using the `PATH` environment variable 80 | * alias substitution 81 | * a number of special shell `built_in` commands: `T F alias cd color debug exit history prompt shcat unalias` 82 | * inputline editing and history using `GNU readline` 83 | * persistent configuration using `~/.jshrc` configuration file 84 | * `jsh` command line options 85 | * compilation and installation of a `man` page using a Makefile 86 | * tested on Linux (Arch, Ubuntu, Tinycore) and Mac OS X 87 | -------------------------------------------------------------------------------- /mini-grep.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define PROGRAM_NAME "mini-grep" // the name of this program 5 | #define MAXLINE 1000 // max number of characters per line 6 | #define COLOR "\033[1;31m" // 0 = normal, 1 = bold (increased intensity) ; 31 red 7 | #define NONE "\033[0m" // to flush the previous color property 8 | 9 | // option global variables 10 | int EXCEPT = 0; 11 | int NUMBER = 0; 12 | 13 | // function definitions 14 | int option(char *s); 15 | int getLine(char s[]); 16 | int strindex(char *s, char *p, char *r[]); 17 | void printmatch(char *s, long no, char *p, char *i[], int n); 18 | 19 | /* 20 | * Print all lines of stdin, matching a specified pattern. 21 | * Return number of matching lines. 22 | */ 23 | int main(int argc, char *argv[]) { 24 | char line[MAXLINE]; 25 | char *index[MAXLINE]; //array of pointers to pattern substrings 26 | char *pattern; //pattern to search for 27 | int i, n, nb_matches = 0; 28 | long lineno = 1; 29 | 30 | // process options 31 | for (i=1; i < argc && *argv[i] == '-'; i++) 32 | if (option(argv[i]+1) < 0) 33 | return 0; 34 | 35 | if (argc-i != 1) 36 | printf("Usage: %s [OPTION]... PATTERN\nTry '%s --help' for more information.\n", PROGRAM_NAME, PROGRAM_NAME); 37 | else { 38 | pattern = argv[i]; 39 | // read all lines on stdin, printing those who match 40 | for(;getLine(line) > 0; lineno++) 41 | if ( ((n = strindex(line, pattern, index)) > 0) != EXCEPT) { 42 | printmatch(line, lineno, pattern, index, n); 43 | nb_matches += n; 44 | } 45 | } 46 | return nb_matches; 47 | } 48 | 49 | /* 50 | * option: process an option string 51 | * Negative return value = terminate program (i.e. don't start pattern search) 52 | */ 53 | int option(char *str) { 54 | int optionfull(char *s); // option helper function 55 | 56 | char *begin = str; 57 | while (*str != '\0') 58 | switch(*str++) { 59 | case '-': 60 | if (str-1 == begin) 61 | return optionfull(str); 62 | break; // else: ignore 63 | case 'h': 64 | printf("Usage: %s [OPTION]... PATTERN\n", PROGRAM_NAME); 65 | printf("Print all standard input lines containing PATTERN\n\n"); 66 | printf("Recognized options:\n"); 67 | printf("-h, --help\t\tdisplay this help message\n"); 68 | printf("-n, --line-number\tprint line number with output lines\n"); 69 | printf("-x, --except\t\tprint all lines except those matching PATTERN\n"); 70 | return -1; 71 | case 'n': 72 | NUMBER = 1; 73 | break; 74 | case 'x': 75 | EXCEPT = 1; 76 | break; 77 | default: 78 | printf("Unrecognized option '-%c'\n", *(str-1)); 79 | printf("Try '%s --help' for a list of regognized options\n", PROGRAM_NAME); 80 | return -1; 81 | } 82 | return 0; 83 | } 84 | 85 | /* 86 | * optionfull: process an option string, in full (--OPTION) notation 87 | * Negative retun value = terminate program (i.e. don't start pattern search) 88 | */ 89 | int optionfull(char *str) { 90 | if (strcmp(str,"help") == 0) 91 | return option("h"); 92 | else if (strcmp(str, "line-number") ==0) 93 | return option("n"); 94 | else if (strcmp(str, "except") == 0) 95 | return option("x"); 96 | else { 97 | printf("Unrecoginized option '--%s'\n", str); 98 | printf("Try '%s --help' for a list of regognized options\n", PROGRAM_NAME); 99 | return -1; 100 | } 101 | } 102 | 103 | /* 104 | * getLine: read line on stdin into line array, return length. 105 | * Note: (in case inputline length > MAXLINE - 1, only the first (MAXLINE-1) characters 106 | * are read into the line array. The following characters of that line are read on the next function invocation.) 107 | */ 108 | int getLine(char line[]) { 109 | int c, i = 0; 110 | 111 | // read stdin into line array, until max or newline or EOF 112 | while( i < MAXLINE && (c=getchar()) != '\n' && c != EOF ) 113 | line[i++] = c; 114 | if ( c == '\n') 115 | line[i++] = c; 116 | line[i] = '\0'; // 0 terminate the string 117 | return i; 118 | } 119 | 120 | /* 121 | * strindex: store in r pointers to all occurences of p in s 122 | * return number of matches 123 | */ 124 | int strindex(char *s, char *p, char *r[]) { 125 | int j, n = 0; 126 | for (; *s != '\0'; s++) { 127 | for(j = 0; *(p+j) != '\0' && *(s+j) == *(p+j); j++) 128 | ; 129 | if (j > 0 && *(p+j) == '\0') { // we have a full match 130 | r[n++] = s; 131 | s += j-1; 132 | } 133 | } 134 | return n; 135 | } 136 | 137 | /* 138 | * printmatch: print (in color) a null-terminated string s with line number no, 139 | * containing n pattern matches, specified by the index array. 140 | */ 141 | void printmatch(char *s, long no, char *pattern, char *index[], int n) { 142 | if (NUMBER) 143 | printf("%ld: ", no); 144 | 145 | for(; *s != '\0'; s++) 146 | if( s == *index && n > 0) { // we have a pattern match 147 | if (isatty(fileno(stdout))) 148 | printf("%s%s%s", COLOR, pattern , NONE); 149 | else 150 | printf("%s", pattern); 151 | index++; 152 | s += strlen(pattern) - 1; 153 | n--; 154 | } 155 | else 156 | printf("%c", *s); 157 | } 158 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | **note:** a major restructuring of the `jsh` project is on the way (see [issue#71](https://github.com/jovanbulck/jsh/issues/71)). The current `master` branch will be discontinued: no new functionality is accepted. 4 | 5 | *Developers, developers, developers*: here are some ways to help the `jsh` project: 6 | 7 | ## Bug reporting and feature requests 8 | 9 | Reporting bugs is a great way to help the `jsh` project too, report your issues 10 | [here](https://github.com/jovanbulck/jsh/issues). Please include the output of jsh --version in all bug reports. 11 | 12 | Having a great idea to improve `jsh`? Shout [here](https://github.com/jovanbulck/jsh/issues)! 13 | 14 | ## Testing 15 | 16 | If you tested jsh on a new or existing platform and have some extra instructions, add them 17 | [here](https://github.com/jovanbulck/jsh/wiki/Compiling-and-running) 18 | 19 | ## Uploading binary Builds 20 | 21 | When a new [release](https://github.com/jovanbulck/jsh/releases) comes out, it's great to add new binaries 22 | for various platforms. As we've had troubles with Github-releases binary builds becoming unavailable, 23 | I think it's best to open a pull request for the 24 | [`gh-pages` branch](https://github.com/jovanbulck/jsh/tree/gh-pages/releases) containing a back-up of all 25 | the releases binaries. I'll then add them to the github release page. 26 | 27 | ## Coding 28 | 29 | Feel free to improve existing or implement new features. If you need some inspiration, see the open [issue](https://github.com/jovanbulck/jsh/issues) list. Issues marked with the [`get-to-know-jsh`](https://github.com/jovanbulck/jsh/labels/get-to-know-jsh) label should be fairly easy. 30 | 31 | If you're working on an existing issue, claim it. 32 | If you're working on a major new feature, you'll best open and claim a new issue for it. 33 | One address for all your pull requests: https://github.com/jovanbulck/jsh/pulls 34 | 35 | ### Commit messages 36 | 37 | - Write informative short commit messages describing the changes. 38 | - Refer to issue and pull request `#numbers` where needed 39 | - Consider starting the commit message with an applicable emoji: 40 | * :bug: `:bug:` when fixing a bug 41 | * :star: `:star:` when implemented a new feauture request 42 | * :hammer: `:hammer:` when fixing the Makefile 43 | * :penguin: `:penguin:` when fixing something for Linux 44 | * :apple: `:apple:` when fixing something for Mac 45 | * :memo: `:memo:` when writing docs 46 | * :lipstick: `:lipstick:` when cleaning up code 47 | * :racehorse: `:racehorse:` when improving performance 48 | * :lock: `:lock:` when dealing with security 49 | * :green_heart: `:green_heart:` when fixing the TravisCI build 50 | * :fire: `:fire:` when removing code or files 51 | * :ghost: `:ghost:` for non-finished proof-of-concept commits ;-) 52 | * :books: `:books:` when working on GNU `readline` 53 | * :bangbang: `:bangbang:` when working on `readline` history support 54 | * :shell: `:shell:` when working on the shell's core structure 55 | * :package: `:package:` for package / binary build related commits 56 | * :checkered_flag: `:checkered_flag:` for version number change commits 57 | 58 | ### Coding guidelines 59 | 60 | *work in progress* This section lists some coding guidelines to keep the `jsh` code readable, uniform and clean. Note not all of `jsh`'s current code base confirms to these guidelines. In future, this should be the case however. Therefore all code in pull requests should confirm to these guidelines. 61 | 62 | #### General layout guidelines 63 | * Don't use tabs, use 4 spaces instead (set your texteditor to insert spaces instead of tabs) 64 | * Line length shouldn't exceed column 90 - 95 (e.g. `gedit` can be configured to show a right margin) 65 | * all code files should start with the GPL copyright notice, see e.g. `jsh.c` 66 | 67 | #### C coding guidelines 68 | * All code should be ANSI C compatible and compile without warnings with `gcc` 69 | * The use of `libc` functions should be as much as possible POSIX compatible. 70 | * Pay great attention to software security: buffer overflows, overreads, format string vulnerabilies, malloc leaks, ... 71 | * Function defintions are formated as follows: `return_type function_name(arg_type1, arg_type2, ...);` 72 | * 'Public' function defintions go into C header files. 73 | * 'Private' helper function defintions are listed at the start of the C file. 74 | * Put generic helper function definitions that can be re-used accross the code base, in `jsh-common.h` 75 | * All functions should have doc. Write something as: 76 | ```c 77 | /* 78 | * function_name: short description, potentially mentioning @param(arg_name) 79 | * @arg arg_name : info on the first argument 80 | * @arg longer_arg_name : info on the second argument 81 | * @return: info on the returned value, if any 82 | * @note: additional info, if any 83 | */ 84 | return_type function_name(arg_type1 arg_name, arg_type2 longer_arg_name) 85 | ``` 86 | * `if then else` and related syntax is formatted as follows: 87 | ```c 88 | if (condition) 89 | single_line_cmd; 90 | 91 | if (condition) { 92 | if_branch_cmds; 93 | on_multiple_lines; 94 | } else { 95 | else_cmds; 96 | multi_line; 97 | } 98 | ``` 99 | * Function calls are formatted as follows: `int a = call_a_function(some_param);` 100 | * Choose wisely between `for` and `while` loops: keep readability, elegance and compactness in mind. 101 | * Whenever possible, choose the `bool` datatype defined in `stdbool.h` over integers 102 | * Don't use magic numbers; use `#define KEY value` instead. 103 | * Multiline macro's should always go into a `do { .. } while(false)` loop: see e.g. [this rationale](http://stackoverflow.com/questions/154136/do-while-and-if-else-statements-in-c-c-macros) 104 | -------------------------------------------------------------------------------- /jsh-man.1: -------------------------------------------------------------------------------- 1 | .\" @BEGIN_COMMENT Manpage for jsh: Makefile processes this file to include the version number (@VERSION) 2 | .\" and date (@DATE) and writes it to ./jsh.1 @END_COMMENT 3 | .\" 4 | .TH JSH 1 "@DATE" "jsh @VERSION" "jsh man page" 5 | .SH NAME 6 | jsh \- A basic UNIX shell implementation in C 7 | .SH SYNOPSIS 8 | \fBjsh\fP [options] 9 | .SH DESCRIPTION 10 | \fBjsh\fP is a UNIX command interpreter (shell) that executes commands read from the standard input or from a file. \fBjsh\fP implements a subset of the \fBsh\fP language grammar and is intended to be POSIX-conformant. 11 | 12 | \fBjsh\fP is written 'just for fun' and is not intented to be a full competitor to advanced UNIX shells such as \fBbash\fP and \fBzsh\fP. \fBjsh\fP is free software and you are welcome to collaborate on the github page (https://github.com/jovanbulck/jsh) or to redistribute \fBjsh\fP under the conditions of the GNU General Public License. 13 | .SH OPTIONS 14 | \fBjsh\fP supports any combination of the following options: 15 | .TP 16 | \fB\-h, \--help\fP 17 | display an informative help message and exit 18 | .TP 19 | \fB\-d, \--debug\fP 20 | turn printing of debug messages on 21 | .TP 22 | \fB\-n, \--nodebug\fP 23 | turn printing of debug messages off 24 | .TP 25 | \fB\-c, \--color\fP 26 | turn coloring of jsh output messages on 27 | .TP 28 | \fB\-o, \--nocolor\fP 29 | turn coloring of jsh output messages off 30 | .TP 31 | \fB\-d, \--norc\fP 32 | disable autoloading of the ~/.jshrc file 33 | .TP 34 | \fB\-l, \--license\fP 35 | display licence information and exit 36 | .TP 37 | \fB\-v, \--version\fP 38 | display version information and exit 39 | .SH CONFIG FILES 40 | .TP 41 | \fI~/.jshrc\fP 42 | file containing commands to be executed at login (note using the \fBsource\fP builtin, one can include any other file to be processed at startup) 43 | .TP 44 | \fI~/.jsh_login\fP 45 | file containing a text message verbatim printed at login of an interactive session 46 | .TP 47 | \fI~/.jsh_logout\fP 48 | file containing commands to be executed at logout of an interactive session 49 | .TP 50 | \fI~/.jsh_history\fP 51 | file containing the command history auto loaded and saved at login/logout 52 | .SH PROMPT CUSTOMIZING 53 | You can define a custom \fBjsh\fP prompt using the \fBprompt\fP builtin command: \fBprompt\fP "prompt_string" [max_cwd_length]. The first argument defines the new prompt string. The second optional argument defines the maximum length for the current working directory, included with '%d'. One can include the following prompt expansion options preceded by a '%' char in the prompt string: 54 | .TP 55 | \fB%u\fP 56 | includes the current username 57 | .TP 58 | \fB%U\fP 59 | includes the current username, colored red and bold iff \fBsudo\fP access is activated 60 | .TP 61 | \fB%h\fP 62 | includes the current hostname 63 | .TP 64 | \fB%s\fP 65 | includes the return value of the last executed shell command 66 | .TP 67 | \fB%S\fP 68 | includes the return value of the last executed shell command, colored red and bold iff non-zero 69 | .TP 70 | \fB%d\fP 71 | includes the current working directory. When this directory path is longer then the value specified by the optional \fBmax_cwd_length\fP second argument (default is 25), the directory path is 'smart' truncated to include the maximum number of individual trailing directories of the path. If the path contains the current user's home directory, it is replaced with a '~' char. 72 | .TP 73 | \fB%g\fP 74 | includes the \fBgit\fP branch name iff the current working directory is a \fBgit\fP repository 75 | .TP 76 | \fB%c\fP 77 | includes a bold and red '*' char iff the current working directory is a \fBgit\fP repository and \fBgit\fP indicates files have changed since the last commit 78 | .TP 79 | \fB%$\fP 80 | includes a '$' char or a '#' char iff \fBsudo\fP access is activated (usefull for the prompt ending) 81 | .TP 82 | \fB%%\fP 83 | includes the verbatim '%' character 84 | .TP 85 | \fB%B\fP 86 | turns on bold/bright text coloring 87 | .TP 88 | \fB%n\fP 89 | restores normal coloring: turns off bold/bright text coloring 90 | .TP 91 | \fB%f{color_name}\fP 92 | Enables the specified foreground non-bold text color. Recognized colors are \fB{black, red, green, yellow, blue, magenta, cyan, white}\fP. The special colors \fB{reset, resetall}\fP can be used to respectively reset the foreground color to the default or reset all color properties to default. 93 | .TP 94 | \fB%F{color_name}\fP 95 | Enables the specified foreground bold/bright text color. Recognized colors are the same as with \fB%f\fP above. The special colors \fB{reset, resetall}\fP can be used to respectively disable bold style and reset the foreground color to the default or reset all color properties to default. 96 | .TP 97 | \fB%b{color_name}\fP 98 | Enables the specified background text color. Recognized colors are the same as with \fB%f\fP above. The special colors \fB{reset, resetall}\fP can be used to respectively reset the background color to the default or reset all color properties to default. 99 | .SH THE JSH WIKI 100 | \fBjsh\fP has a wiki (https://github.com/jovanbulck/jsh/wiki) where you can find up-to-date information and installation instructions for various platforms. 101 | .SH BUGS REPORTS 102 | If you find a bug or vulnerability in \fBjsh\fP, you should report it on the github page (https://github.com/jovanbulck/jsh/issues). Please include the output of \fBjsh --version\fP in all bug reports. 103 | .SH KNOWN BUGS 104 | \fBjsh\fP only supports a small subset of the \fBsh\fP language grammar and its interpretation can sometimes be ambiguous. You're welcome to propose better interpretations on the github page, linked above. 105 | 106 | Single quotes (') and backticks (`) are not (yet) interpreted by the \fBjsh\fP shell. 107 | 108 | Environment variables are not yet implemented. This will be added in future releases. 109 | 110 | Job control is not yet implemented; pressing ^Z will suspend the \fBjsh\fP shell. Background jobs will be implemented in future releases. 111 | .SH DISCLAIMER 112 | \fBjsh\fP is not a master thesis. 113 | 114 | \fBjsh\fP can be time-consuming and school-distracting. 115 | 116 | Any resemblance of \fBjsh\fP to actual persons is purely coincidental. 117 | .SH AUTHOR 118 | \fBjsh\fP was orginally written by Jo Van Bulck . For additional contributors, use \fBgit shortlog -sn\fP on the jsh.git repository. 119 | .SH LICENSE 120 | \fBjsh\fP is free software, licensed under the GNU General Public License (https://gnu.org/licenses/gpl.html). Try \fBjsh --license\fP for more information. 121 | .SH SEE ALSO 122 | \fIsh(1)\fR, \fIbash(1)\fR, \fIreadline(1)\fR. 123 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # ============================================================= 2 | # This file is part of jsh. 3 | # 4 | # jsh: A basic UNIX shell implementation in C 5 | # Copyright (C) 2014 Jo Van Bulck 6 | # 7 | # jsh is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # jsh is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with jsh. If not, see . 19 | # ============================================================ 20 | 21 | JSH_INSTALL_DIR = /usr/local/bin 22 | MANPAGE_INSTALL_DIR = /usr/local/share/man/man1 23 | JSH_RELEASE_DIR = ./JSH_$(RELEASE_NB)_RELEASE 24 | 25 | DATE = $(shell date +%d\ %b\ %Y) 26 | HOUR = $(shell date +%Hh%M) 27 | MACHINE_BUILT = $(shell uname -srm) 28 | MACHINE_RELEASE = $(shell uname -sm) 29 | RELEASE_NB = 1.2.1 30 | RELEASE_VERSION_STR = "jsh $(RELEASE_NB) on $(MACHINE_RELEASE) (official release $(DATE))" 31 | DEV_BUILT_VERSION_STR = "jsh post $(RELEASE_NB) on $(MACHINE_BUILT) \n(developer built $(DATE) : $(HOUR))" 32 | VERSION_STR = $(DEV_BUILT_VERSION_STR) 33 | # 'make release' will override the above line to RELEASE_VERSION_STR 34 | 35 | ifndef CC # allow the compiler to be changed with 'export CC=the_compiler' 36 | CC = gcc 37 | endif 38 | CFLAGS = -g -DVERSION='$(VERSION_STR)' $(EXTRA_CFLAGS) 39 | # EXTRA_CFLAGS is empty on default; 'make install' will add the INSTALL_CFLAGS 40 | ifndef INSTALL_CFLAGS 41 | INSTALL_CFLAGS = -DNODEBUG 42 | endif 43 | LIBS = -lreadline 44 | LN = $(CC) $(CFLAGS) jsh-common.o jsh.o alias.o jsh-parse.o jsh-completion.o -o jsh $(LIBS) 45 | 46 | ECHO_LIBS = echo "Linking jsh with the following libraries: $(LIBS) " 47 | UNAME_S = $(shell uname -s) 48 | 49 | ifeq ($(UNAME_S), Darwin) 50 | IS_BSD 51 | else ifeq ($(UNAME_S), FreeBSD) 52 | IS_BSD 53 | endif 54 | 55 | ifeq ($(UNAME_S), Darwin) 56 | # link explicitely with readline library folder for Mac OS X (installed with homebrew) 57 | LINK = $(LN) -L/usr/local/lib/ 58 | else 59 | # try to link jsh with the readline library (and curses or termcap if needed) 60 | LINK = @(($(ECHO_LIBS)); ($(LN)) || (($(ECHO_LIBS) "lncurses"); $(LN) -lncurses) || \ 61 | (($(ECHO_LIBS) "termcap"); $(LN) -termcap) || (echo "Failed linking jsh: all known fallback libraries were tried")) 62 | endif 63 | 64 | all: print_start_info jsh-common alias parse completion jsh link man 65 | @echo "-------- Compiling all done --------" 66 | 67 | jsh-common: jsh-common.c jsh-common.h 68 | $(CC) $(CFLAGS) -c jsh-common.c -o jsh-common.o 69 | alias: alias.c alias.h jsh-common.h 70 | $(CC) $(CFLAGS) -c alias.c -o alias.o 71 | parse: jsh-parse.c jsh-parse.h jsh-common.h 72 | $(CC) $(CFLAGS) -c jsh-parse.c -o jsh-parse.o 73 | completion: jsh-completion.h jsh-completion.c jsh-common.h 74 | $(CC) $(CFLAGS) -c jsh-completion.c -o jsh-completion.o 75 | jsh: jsh.c jsh-common.h 76 | $(CC) $(CFLAGS) -c jsh.c -o jsh.o 77 | link: jsh-common.o jsh.o alias.o jsh-parse.o jsh-completion.o 78 | $(LINK) 79 | 80 | man: jsh-man.1 81 | ifndef NO_MAKE_MAN # don't make the man page when NO_MAKE_MAN has a non-empty value 82 | @echo "making man page: adding version number and date to jsh.1" 83 | ifdef IS_BSD # BSD sed version has another syntax 84 | @sed -e 's/@VERSION/$(RELEASE_NB)/' -e 's/@DATE/$(DATE)/' \ 85 | -e '/@BEGIN_COMMENT/,/END_COMMENT/c\ '$$'\n''.\\" jsh manpage auto generated by jsh Makefile' \ 86 | < jsh-man.1 > jsh.1 87 | else # GNU sed version syntax 88 | @sed -e 's/@VERSION/$(RELEASE_NB)/' -e 's/@DATE/$(DATE)/' \ 89 | -e '/@BEGIN_COMMENT/,/END_COMMENT/c\.\\" jsh manpage auto generated by jsh Makefile' \ 90 | < jsh-man.1 > jsh.1 91 | endif 92 | endif 93 | 94 | .PHONY: print_start_info 95 | print_start_info: 96 | @echo "-------- making jsh version" $(VERSION_STR) "-------- " 97 | 98 | ## this helper target is a hack for TravisCI; since it seems it can't use the clang 99 | ## compiler when making with 'sudo' 100 | .PHONY: make_for_install 101 | make_for_install: 102 | ifndef INSTALL_ONLY 103 | @echo "-------- installing jsh --------" 104 | @echo "making jsh with additional $(INSTALL_CFLAGS) flags" 105 | $(MAKE) --always-make EXTRA_CFLAGS='$(INSTALL_CFLAGS)' NO_MAKE_MAN='$(NO_MAKE_MAN)' 106 | endif 107 | 108 | .PHONY: install 109 | install: make_for_install 110 | @echo "installing jsh executable in directory $(JSH_INSTALL_DIR)..." 111 | @test -d $(JSH_INSTALL_DIR) || (mkdir -p $(JSH_INSTALL_DIR) && echo "created directory $(JSH_INSTALL_DIR)") 112 | @install -m 0755 jsh $(JSH_INSTALL_DIR); 113 | 114 | ifndef NO_MAKE_MAN 115 | @echo "installing the manpage in directory $(MANPAGE_INSTALL_DIR)..." 116 | @test -d $(MANPAGE_INSTALL_DIR) || (mkdir -p $(MANPAGE_INSTALL_DIR) && echo "created directory $(MANPAGE_INSTALL_DIR)") 117 | @install -m 0644 jsh.1 $(MANPAGE_INSTALL_DIR); 118 | ifndef IS_BSD # Man-DB update is not necessary on BSD based systems 119 | @echo "updating man-db..." 120 | @mandb --quiet 121 | endif 122 | endif 123 | @echo "-------- Installation all done --------" 124 | 125 | .PHONY: uninstall 126 | uninstall: 127 | @echo "-------- Uninstalling jsh from directories $(JSH_INSTALL_DIR) and $(MANPAGE_INSTALL_DIR) --------" 128 | rm -f $(JSH_INSTALL_DIR)/jsh $(MANPAGE_INSTALL_DIR)/jsh.1 129 | @echo "-------- Uninstallation all done --------" 130 | 131 | .PHONY: release 132 | release: 133 | @echo "-------- making jsh $(RELEASE_NB) release built --------" 134 | $(MAKE) --always-make EXTRA_CFLAGS='$(INSTALL_CFLAGS)' VERSION_STR='$(RELEASE_VERSION_STR)' 135 | @echo "copying jsh executable in directory $(JSH_RELEASE_DIR)/ ..." 136 | @test -d $(JSH_RELEASE_DIR) || (mkdir -p $(JSH_RELEASE_DIR) && echo "created directory $(JSH_RELEASE_DIR)") 137 | cp jsh $(JSH_RELEASE_DIR) && chmod a+rx $(JSH_RELEASE_DIR)/jsh; 138 | 139 | @echo "copying the manpage in directory $(JSH_RELEASE_DIR)..." 140 | cp jsh.1 $(JSH_RELEASE_DIR) && chmod a+r $(JSH_RELEASE_DIR)/jsh.1; 141 | @echo "-------- Release built all done --------" 142 | 143 | .PHONY: clean 144 | clean: 145 | rm -f jsh-common.o alias.o jsh.o jsh jsh.1 146 | (test -d $(JSH_RELEASE_DIR) && rm -rfI $(JSH_RELEASE_DIR)) || true 147 | 148 | .PHONY: help 149 | help: 150 | @echo "The following are valid targets for this Makefile:" 151 | @echo "... all -- (the default if no target is provided); compiles the shell to the 'jsh' binary in the current directory" 152 | @echo "... clean -- removes all object files generated by the build process; also removes the $(JSH_RELEASE_DIR)/ directory and its content, if any" 153 | @echo "... install -- installs the jsh binary with $(INSTALL_CFLAGS) options to $(JSH_INSTALL_DIR)/ and the jsh man page to $(MANPAGE_INSTALL_DIR)/ Make sure you have the necessary rights, use 'sudo make install' if necessary." 154 | @echo "... uninstall -- removes the jsh binary from $(JSH_INSTALL_DIR)/ and the jsh man page from $(MANPAGE_INSTALL_DIR)/ Make sure you have the necessary rights, use 'sudo make uninstall' if necessary." 155 | @echo "... man -- makes a UNIX man page 'jsh.1' with filled in date and version number in the current directory" 156 | @echo "... release -- makes a jsh release built in $(JSH_RELEASE_DIR)/ in the current directory" 157 | 158 | -------------------------------------------------------------------------------- /jsh-common.c: -------------------------------------------------------------------------------- 1 | /* This file is part of jsh. 2 | * 3 | * jsh: A basic UNIX shell implementation in C 4 | * Copyright (C) 2014 Jo Van Bulck 5 | * 6 | * jsh is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * jsh is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with jsh. If not, see . 18 | */ 19 | 20 | #include "jsh-common.h" 21 | 22 | #define SET_ERR_COLOR \ 23 | if (IS_INTERACTIVE && COLOR) \ 24 | textcolor(stderr, BRIGHT, RED); 25 | 26 | void printerr(const char *format, ...) { 27 | SET_ERR_COLOR; 28 | va_list args; 29 | fprintf(stderr, "jsh: "); 30 | va_start(args, format); 31 | vfprintf(stderr, format, args); 32 | va_end(args); 33 | RESTORE_COLOR(stderr); 34 | } 35 | 36 | void printerrno(const char *format, ...) { 37 | SET_ERR_COLOR; 38 | va_list args; 39 | fprintf(stderr, "jsh: "); 40 | va_start(args, format); 41 | vfprintf(stderr, format, args); 42 | va_end(args ); 43 | fprintf(stderr, ": %s", strerror(errno)); 44 | RESTORE_COLOR(stderr); 45 | } 46 | 47 | // TODO mss int debuglevel / priority 48 | void printdebug(const char *format, ...) { 49 | if (DEBUG) { 50 | if (IS_INTERACTIVE && COLOR) 51 | textcolor(stdout, RESET, YELLOW); 52 | 53 | va_list args; 54 | fprintf(stdout, "[DEBUG: "); 55 | va_start(args, format); 56 | vfprintf(stdout, format, args); 57 | va_end(args); 58 | fprintf(stdout, "]"); 59 | RESTORE_COLOR(stdout); 60 | fflush(stdout); // force the debug info to be instantly written 61 | } 62 | } 63 | 64 | void printinfo(const char *format, ...) { 65 | va_list args; 66 | fprintf(stdout, "jsh: "); 67 | va_start(args, format); 68 | vfprintf(stdout, format, args); 69 | va_end(args ); 70 | fprintf(stdout, "\n"); 71 | } 72 | 73 | /* 74 | * only set the style and fg (to prevent problems with translucency...) 75 | * use RESTORE_COLOR macro to reset the color afterwards 76 | */ 77 | void textcolor(FILE *stream, int style, int fg) { 78 | char colorcode[13]; 79 | sprintf(colorcode, "%c[%d;%dm", 0x1B, style, fg + 30); 80 | fprintf(stream, "%s", colorcode); 81 | } 82 | 83 | /* 84 | * returns getenv("HOME") if not null; else "." 85 | */ 86 | char *gethome() { 87 | char *curdir = "."; 88 | char *rv = getenv("HOME"); 89 | return (rv != NULL)? rv: curdir; 90 | } 91 | 92 | /* 93 | * @note: inline function implementation should be in header. Moreover one extern 94 | * declaration should be used, to tell the compiler where to put the non-inlined function, 95 | * if needed. See (http://stackoverflow.com/questions/26503235/c-inline-funtion-and-gcc). 96 | */ 97 | extern inline int puts_verbatim(const char *s); 98 | 99 | /* 100 | * parsefile: wrapper for parsestream(), opening and closing the file at the provided path. 101 | * @arg errmsg: true = print an error message if opening the file failed 102 | * false = exit silently if opening the file failed 103 | * @NOTE: if you pass a pointer to 'printf()' here, this may introduce format-string- 104 | * vulnerabilities as the lines are passed verbatim to the function. If you want to use 105 | * this function to print the content of a file line per line, pass a pointer to 106 | * 'puts_verbatim()' (defined in jsh-common.h) instead. 107 | */ 108 | void parsefile(char *path, void (*fct)(char*), bool errmsg) { 109 | FILE *file = fopen(path, "r"); 110 | if (file == NULL) { 111 | if (errmsg) printerrno("opening of file '%s' failed", path); 112 | return; 113 | } 114 | parsestream(file, path, fct); 115 | fclose(file); 116 | } 117 | 118 | /* 119 | * parsestream: reads the provided stream strm line per line, passing each line, 120 | * including '\n' to the provided function fct. 121 | * @NOTE: if you pass a pointer to 'printf()' here, this may introduce format-string- 122 | * vulnerabilities as the lines are passed verbatim to the function. If you want to use 123 | * this function to print the content of a file line per line, pass a pointer to 124 | * 'puts_verbatim()' (defined in jsh-common.h) instead. 125 | */ 126 | void parsestream(FILE *strm, char* name, void (*fct)(char*)) { 127 | printdebug("-------- now parsing stream '%s' --------", name); 128 | 129 | char line[MAX_FILE_LINE_LENGTH+1]; 130 | int c, i = 0, j = 1; // i = index in line; j = line nb 131 | 132 | while ((c = fgetc(strm)) != EOF) 133 | if (c == '\n') { 134 | line[i] = '\0'; 135 | printdebug("%s: now parsing line %d: '%s'", name, j, line); 136 | fct(line); 137 | fct("\n"); 138 | i = 0; 139 | j++; 140 | } 141 | else if (i < MAX_FILE_LINE_LENGTH) 142 | line[i++] = c; 143 | else { 144 | printerr("%s: ignoring line %d exeeding the max line length: %d", name, j, MAX_FILE_LINE_LENGTH); 145 | while ((c=fgetc(strm)) != '\n'); 146 | i = 0; 147 | j++; 148 | } 149 | printdebug("-------- end of stream '%s' --------", name); 150 | } 151 | 152 | /* 153 | * string_cmp: wrapper function for strcmp(); to be passed to bsearch() or qsort() in order to compare 154 | * two pointers to a string (char**) 155 | */ 156 | int string_cmp(const void *a, const void *b) { 157 | const char **ia = (const char **) a; 158 | const char **ib = (const char **) b; 159 | return strcmp(*ia, *ib); 160 | } 161 | 162 | 163 | /* 164 | * is_sorted: returns false iff the provided array a isn't sorted according to the provided comparison function, 165 | * else returns true; time complexity O(n) 166 | */ 167 | bool is_sorted(void *a, size_t n, size_t el_size, int (*compar)(const void *, const void *)) { 168 | int i; 169 | for (i = 0; i < (n - 1)*el_size; i += el_size) { 170 | int rv = compar((a + i), (a + i + el_size)); 171 | if (rv >= 0) 172 | return false; 173 | } 174 | return true; 175 | } 176 | 177 | /* 178 | * strclone: returns a pointer to a malloc block with a copy of the provided string. 179 | */ 180 | char *strclone(const char* str) { 181 | char *ret = malloc(strlen(str)+1); 182 | strcpy(ret, str); 183 | return ret; 184 | } 185 | 186 | /* 187 | * concat: concatenates count nb of strings and returns a pointer to the malloc()ed result. 188 | * the caller should free() the result afterwards 189 | * credits: http://stackoverflow.com/a/11394336 190 | */ 191 | char* concat(int count, ...) { 192 | va_list ap; 193 | int i; 194 | 195 | // Find required length to store merged string 196 | int len = 1; // room for NULL 197 | va_start(ap, count); 198 | for(i=0 ; i 5 | * 6 | * jsh is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * jsh is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with jsh. If not, see . 18 | */ 19 | 20 | #include "alias.h" 21 | 22 | #define MAX_ALIAS_VAL_LENGTH 200 // the maximum allowed number of chars per alias value 23 | #define MAX_ALIAS_KEY_LENGTH 50 // the maximum allowed number of chars per alias key 24 | 25 | struct alias { 26 | char *key; 27 | char *value; 28 | struct alias *next; 29 | }; 30 | //typedef struct alias ALIAS; 31 | //#define CREATE_ALIAS(k,v) (struct alias) {k, v} 32 | 33 | struct alias *head = NULL; 34 | struct alias *tail = NULL; 35 | 36 | int total_alias_val_length = 0; 37 | int nb_aliases = 0; 38 | 39 | bool alias_key_changed = false; 40 | 41 | /* 42 | * alias: create a mapping between a key and value pair that can be resolved with resolvealiases(). 43 | * returns EXIT_SUCCESS or EXIT_FAILURE if something went wrong (e.g. malloc) 44 | * (note that provided strings that are too long are silently truncated) 45 | */ 46 | int alias(char *k, char *v) { 47 | // allow recursive alias definitions 48 | char *val = resolvealiases(v); 49 | 50 | int vallength = strnlen(val, MAX_ALIAS_VAL_LENGTH); 51 | int keylength = strnlen(k, MAX_ALIAS_KEY_LENGTH); 52 | 53 | // alloc memory for the new alias struct and its key 54 | // note: *val has already been alloced by the resolvealiases() call 55 | struct alias *new = malloc(sizeof(struct alias)); //TODO chkerr 56 | new->next = NULL; 57 | new->key = malloc(sizeof (char) * keylength+1); 58 | 59 | // copy the provided strings into the allocated memory 60 | strncpy(new->key, k, keylength+1); 61 | new->value = val; 62 | 63 | if(alias_exists(k)) { 64 | unalias(k); 65 | } 66 | total_alias_val_length += vallength; 67 | 68 | if (head == NULL) { 69 | head = new; 70 | tail = head; 71 | } 72 | else { 73 | tail->next = new; 74 | tail = new; 75 | } 76 | nb_aliases++; 77 | alias_key_changed = true; 78 | return EXIT_SUCCESS; 79 | } 80 | 81 | /* 82 | * unalias: unaliases a specified key 83 | * returns EXIT_SUCCESS if the specified key was found; else prints an error message and returns EXIT_FAILURE 84 | */ 85 | int unalias(char *key) { 86 | struct alias *cur = head; 87 | struct alias *prev = NULL; 88 | while (cur != NULL) { 89 | if (strncmp(cur->key, key, MAX_ALIAS_KEY_LENGTH) == 0) { 90 | // re-organize the linked list 91 | if (prev) 92 | prev->next = cur->next; 93 | else 94 | head = cur->next; 95 | if (cur == tail) 96 | tail = prev; 97 | // free the unalised alias and return 98 | total_alias_val_length -= strnlen(cur->value, MAX_ALIAS_VAL_LENGTH); 99 | free(cur); 100 | nb_aliases--; 101 | alias_key_changed = true; 102 | return EXIT_SUCCESS;; 103 | } 104 | prev = cur; 105 | cur = cur->next; 106 | } 107 | printerr("unalias: no such alias key: %s", key); 108 | return EXIT_FAILURE; 109 | } 110 | 111 | /* 112 | * printaliases: print a list of all currently set aliases on stdout 113 | * returns EXIT_SUCCESS 114 | */ 115 | int printaliases() { 116 | struct alias *cur = head; 117 | while(cur != NULL) { 118 | printf("alias %s = '%s'\n", cur->key, cur->value); 119 | cur = cur->next; 120 | } 121 | return EXIT_SUCCESS; 122 | } 123 | 124 | /* 125 | * get_all_alias_keys: returns a newly malloced array of pointers to newly malloced strings 126 | * containing a copy of the alias keys. 127 | * @param nb_keys : if non-NULL; will contain the length of the result array; 128 | * nb_keys will be untouched if NULL is returned 129 | * @param only_on_change : if true, the result will only be non-NULL if one of the alias 130 | * keys changed since the last time this method was called. 131 | * @return: an array with all alias key strings, or NULL iff @param(only_on_change) and 132 | * there have been no alias key changes since the last time this method was called. 133 | * @note: the caller is responisble for freeing the array as well as the array elements 134 | */ 135 | char **get_all_alias_keys(unsigned int *nb_keys, bool only_on_change) { 136 | if (only_on_change && !alias_key_changed) { 137 | return NULL; 138 | } 139 | 140 | char **ret = malloc(sizeof(char*) * nb_aliases); 141 | 142 | int i = 0; 143 | struct alias *cur = head; 144 | while(cur != NULL) { 145 | ret[i] = strclone(cur->key); 146 | cur = cur->next; 147 | i++; 148 | } 149 | if (nb_keys) *nb_keys = nb_aliases; 150 | alias_key_changed = false; 151 | return ret; 152 | } 153 | 154 | 155 | /* 156 | * resolvealiases: substitutes all known aliases in the inputstring. Returns a pointer to the alias-expanded string. 157 | * NOTE: this function returns a pointer to a newly malloced() string. The caller should free() it afterwards, 158 | * as well as also the inputstring *s, if needed 159 | * 160 | * current limitations for aliases: 161 | * TODO - any spaces in the value must be escaped in the input for the 'alias' cmd e.g. alias ls ls\ --color=auto 162 | * alt syntax: alias ls "ls --color=auto" 163 | */ 164 | char *resolvealiases(char *s) { 165 | bool is_valid_alias(char*, char*, int); // helper function def 166 | 167 | // alloc enough space for the return value 168 | int maxsize = strlen(s) + total_alias_val_length; 169 | char *ret = malloc(sizeof (char) * maxsize); 170 | strcpy(ret, s); 171 | 172 | // find all alias key substrings, replacing them if valid in context 173 | struct alias *cur; 174 | char *p, *str; // p is pointer to matched substring; str is pointer to not-yet-checked string 175 | for (cur = head; cur != NULL; cur = cur->next) 176 | for (str = ret; (p = strstr(str, cur->key)) != NULL;) { 177 | if (is_valid_alias(cur->key, ret, p-ret)) { 178 | printdebug("alias: '%s' VALID in context '%s'", cur->key, p); 179 | 180 | char *after = p + strlen(cur->key); 181 | memmove(p + strlen(cur->value), after, strlen(after)+1); // overlapping mem; len+1 : also copy the '\0' 182 | memcpy(p, cur->value, strlen(cur->value)); // non-overlapping mem 183 | str = p+strlen(cur->value); 184 | } 185 | else { 186 | printdebug("alias: '%s' INVALID in context '%s'", cur->key, p); 187 | str = p+strlen(cur->key); 188 | } 189 | } 190 | 191 | printdebug("alias: input resolved to: '%s'", ret); 192 | return ret; 193 | } 194 | 195 | /* 196 | * is_valid_alias: returns whether or not an occurence of an alias key is valid (i.e. must be 197 | * replaced by its value) in a given context string. An alias match is valid iff it occurs 198 | * as a comd in the grammar and it's not '\' escaped. 199 | * 200 | * @param key: the alias key corresponding to the alias that is matched 201 | * @param context: the context string where the alias is matched 202 | * @param i: the index in the context string where the alias is matched: context+i equals alias->key 203 | */ 204 | bool is_valid_alias(char *key, char *context, int i) { 205 | // allow escaping '\' of aliases TODO is this usefull? --> yes for the ~ alias hack 206 | if ( i > 0 && *(context+i-1) == '\\' ) { 207 | printdebug("alias: escaping '%s'", key); 208 | memmove(context+i-1, context+i, strlen(context+i)+1); //TODO this function shouldn't change the given context 209 | return false; 210 | } 211 | 212 | // built_in aliases are valid in any context TODO unless escaped... 213 | if (*key == '~') 214 | return true; 215 | 216 | return is_valid_cmd(key, context, i); 217 | } 218 | 219 | /* 220 | * alias_exists: returns whether or not a specified key is currently aliased. 221 | * @return true if the supplied alias already exists; else false. 222 | */ 223 | bool alias_exists(char* key) { 224 | if (!head) return false; 225 | 226 | struct alias *curAlias; 227 | for (curAlias = head; curAlias != NULL; curAlias = curAlias->next) { 228 | // If the current alias matches the argument, return true. 229 | if (strcmp(curAlias->key, key) == 0) return true; 230 | } 231 | return false; 232 | } 233 | -------------------------------------------------------------------------------- /jsh-completion.c: -------------------------------------------------------------------------------- 1 | /* This file is part of jsh. 2 | * 3 | * jsh: A basic UNIX shell implementation in C 4 | * Copyright (C) 2014 Jo Van Bulck 5 | * 6 | * jsh is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * jsh is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with jsh. If not, see . 18 | */ 19 | 20 | #include "jsh-completion.h" 21 | 22 | // #################### helper generator function definitions #################### 23 | char *jsh_cmd_generator(const char*, int); 24 | char *jsh_built_in_generator(const char*, int); 25 | char *jsh_alias_generator(const char*, int); 26 | char *jsh_external_cmd_generator(const char*, int); 27 | char *git_completion_generator(const char*, int); 28 | char *apt_compl_generator(const char*, int); 29 | char *jsh_options_generator(const char*, int); 30 | char *debug_completion_generator(const char*, int); 31 | char *make_options_generator(const char*, int); 32 | 33 | /* 34 | * The function that is called by readline; returns a list of matches or NULL iff no matches 35 | * found. 36 | * @note: All custom autocompletion generators should be called from withing this function. 37 | */ 38 | char** jsh_command_completion(const char *text, int start, int end) { 39 | char **matches = NULL; 40 | 41 | // true iff user entered 'cmd text' 42 | #define USR_ENTERED(cmd) \ 43 | (start >= strlen(cmd)+1 && (strncmp(rl_line_buffer + start - strlen(cmd) - 1, \ 44 | cmd, strlen(cmd)) == 0)) // +1 for space 45 | 46 | if (is_valid_cmd(text, rl_line_buffer, start)) { 47 | // try custom cmd autocompletion iff this is a valid 'comd' context 48 | matches = rl_completion_matches(text, &jsh_cmd_generator); 49 | } 50 | else { 51 | // else try custom autocompletion for specific commands 52 | if (USR_ENTERED("git")) { 53 | matches = rl_completion_matches(text, &git_completion_generator); 54 | } 55 | else if (USR_ENTERED("jsh")) { 56 | matches = rl_completion_matches(text, &jsh_options_generator); 57 | } 58 | else if (USR_ENTERED("make")) { 59 | matches = rl_completion_matches(text, &make_options_generator); 60 | } 61 | else if (USR_ENTERED("debug")) { 62 | matches = rl_completion_matches(text, &debug_completion_generator); 63 | } 64 | else if (USR_ENTERED("apt")) { 65 | matches = rl_completion_matches(text, &apt_compl_generator); 66 | } 67 | } 68 | 69 | return matches; 70 | } 71 | 72 | // #################### helper generator function implementations #################### 73 | 74 | /* 75 | * RL COMPLETION GENERATOR FUNCTION JSH DEVELOPER INFO : 76 | * 77 | * 1. a GNU readline generator function is a function that is passed a partially entered 78 | * command several times and returns a single possible match each time. The first time 79 | * it is called for a new partially entered command, @param(int state) is zero. The 80 | * generator should then initialize static state and return the matches one by one. 81 | * When no more matches, return NULL. 82 | * 2. a jsh generator function is called from the "jsh_command_completion()" function above, 83 | * using the "rl_completion_matches()" readline helper function 84 | * 3. For a straightforward (static string array) completion generator, one should use the 85 | * COMPLETION_SKELETON macro, see examples below. 86 | * 87 | * In other words (from the readline doc): 88 | * "text is the partial word to be completed. state is zero the first time the function 89 | * is called. The generator function returns (char *) NULL to inform rl_completion_matches() 90 | * that there are no more possibilities left. Usually the generator function computes the 91 | * list of possible completions when state is zero, and returns them one at a time on 92 | * subsequent calls. Each string the generator function returns as a match must be 93 | * allocated with malloc(); Readline frees the strings when it has finished with them." 94 | */ 95 | 96 | /* 97 | * COMPLETION_SKELETON: a sketleton to facilitate the implementation of a custom completion 98 | * generator for GNU readline. 99 | * @arg array : a char* array with possible commands 100 | * @arg nb_elements : the length of @param(array) 101 | */ 102 | #define COMPLETION_SKELETON(array, nb_elements) \ 103 | do { \ 104 | static int len; \ 105 | static int index; \ 106 | \ 107 | if (!state) { \ 108 | index = 0; \ 109 | len = strlen(text); \ 110 | } \ 111 | \ 112 | while (index < nb_elements) \ 113 | if (strncmp(array[index], text, len) == 0) \ 114 | return strclone(array[index++]); \ 115 | else \ 116 | index++; \ 117 | \ 118 | return NULL; \ 119 | } \ 120 | while (0) 121 | 122 | /* 123 | * jsh_cmd_generator: a readline generator that combines several helper generators so that 124 | * results from these generators are combined in a single generator. 125 | */ 126 | char *jsh_cmd_generator(const char *text, int state) { 127 | // a separate state for each helper generator, so that it starts from zero 128 | static int alias_state = 0; 129 | static int built_in_state = 0; 130 | static int unix_state = 0; 131 | 132 | if (!state) { 133 | alias_state = 0; 134 | built_in_state = 0; 135 | unix_state = 0; 136 | } 137 | 138 | char *rv; 139 | // jsh grammar priority: alias > built_in > external_cmd 140 | if (!(rv = jsh_alias_generator(text, alias_state++))) 141 | if (!(rv = jsh_built_in_generator(text, built_in_state++))) 142 | rv = jsh_external_cmd_generator(text, unix_state++); 143 | return rv; 144 | } 145 | 146 | /* 147 | * jsh_alias_generator: a readline generator that returns matches with jsh aliases. 148 | */ 149 | char *jsh_alias_generator(const char *text, int state) { 150 | static char **alias_keys = NULL; 151 | static unsigned int nb_alias_keys; 152 | if (!state) { 153 | char **ret; 154 | if ((ret = get_all_alias_keys(&nb_alias_keys, true))) { 155 | if (alias_keys) { 156 | int i; 157 | for (i = 0; i < nb_alias_keys; i++) 158 | free(alias_keys[i]); 159 | free(alias_keys); 160 | } 161 | alias_keys = ret; 162 | } 163 | } 164 | COMPLETION_SKELETON(alias_keys, nb_alias_keys); 165 | } 166 | 167 | /* 168 | * jsh_built_in_generator: a readline generator that returns matches with jsh built_ins. 169 | */ 170 | char *jsh_built_in_generator(const char *text, int state) { 171 | COMPLETION_SKELETON(built_ins, nb_built_ins); 172 | } 173 | 174 | /* 175 | * jsh_external_cmd_generator: a readline generator that returns matches for non-jsh commands. 176 | * TODO search $PATH at boot-time and save the directory content in an array... 177 | */ 178 | char *jsh_external_cmd_generator(const char *text, int state) { 179 | // hackhackhack: an array with some usefull commands 180 | const char *widely_used_cmds[] = {"git", "cat", "grep", "ls", "exit", "sudo", "kill", \ 181 | "killall", "links", "find", "clear", "chmod", "echo", "make", "poweroff", "reboot", \ 182 | "pacman", "aptitude", "apt-cache", "apt-get", "man", "nano", "vi", "gcc", "jsh", "zsh", \ 183 | "bash"}; 184 | #define nb_widely_used_cmds (sizeof(widely_used_cmds)/sizeof(widely_used_cmds[0])) 185 | 186 | COMPLETION_SKELETON(widely_used_cmds, nb_widely_used_cmds); 187 | } 188 | 189 | /* 190 | * git_completion_generator: a readline completor for git commands 191 | */ 192 | char *git_completion_generator(const char *text, int state) { 193 | static const char *git_cmds[] = {"add", "bisect", "branch", "checkout", "clone", \ 194 | "commit", "diff", "fetch", "grep", "init", "log", "merge", "mv", "pull", "push", \ 195 | "rebase", "reset", "rm", "show", "status", "tag"}; 196 | static const int nb_elements = (sizeof(git_cmds)/sizeof(git_cmds[0])); 197 | 198 | COMPLETION_SKELETON(git_cmds, nb_elements); 199 | } 200 | 201 | /* 202 | * debug_completion_generator: a proof of concept readline completor for "jsh debug on/off" 203 | */ 204 | char *debug_completion_generator(const char *text, int state) { 205 | static const char *options[] = {"on", "off"}; 206 | static const int nb_options = (sizeof(options)/sizeof(options[0])); 207 | 208 | COMPLETION_SKELETON(options, nb_options); 209 | } 210 | 211 | /* 212 | * make_completion_generator: a readline completion generator for GNU make 213 | */ 214 | char *make_options_generator(const char *text, int state) { 215 | static const char *options[] = { "--always-make", "--environment-overrides", \ 216 | "--ignore-errors", "--keep-going", "install", "--no-keep-going", "--stop", "install", \ 217 | "clean", "help"}; 218 | static const int nb_elements = (sizeof(options)/sizeof(options[0])); 219 | 220 | COMPLETION_SKELETON(options, nb_elements); 221 | } 222 | 223 | /* 224 | * jsh_options_generator: a readline completion generator for "jsh --options" 225 | */ 226 | char *jsh_options_generator(const char *text, int state) { 227 | static const char *options[] = {"--nodebug", "--debug", "--color", "--nocolor", \ 228 | "--norc", "--license", "--version", "--help"}; //TODO dont hardcode here --> put enum in jsh.c? 229 | static const int nb_options = (sizeof(options)/sizeof(options[0])); 230 | 231 | COMPLETION_SKELETON(options, nb_options); 232 | } 233 | 234 | /* 235 | * apt_compl_generator: a readline completion generator for "apt-get" 236 | */ 237 | char *apt_compl_generator(const char *text, int state) { 238 | static const char *options[] = { "list", "search", "show", "install", "remove", \ 239 | "edit-sources", "update", "upgrade", "full-upgrade"}; 240 | static const int nb_elements = (sizeof(options)/sizeof(options[0])); 241 | 242 | COMPLETION_SKELETON(options, nb_elements); 243 | } 244 | -------------------------------------------------------------------------------- /installer.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ============================================================= 3 | # This file is part of jsh. 4 | # 5 | # jsh: A basic shell implementation 6 | # Copyright (C) 2014 Jo Van Bulck 7 | # 8 | # jsh is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # jsh is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with jsh. If not, see . 20 | # ============================================================ 21 | 22 | ############################## STARTUP THINGS ############################# 23 | 24 | if [ ! command -v dialog >/dev/null 2>&1 ]; then 25 | echo "Seems like the 'dialog' program isn't installed on you system." 26 | echo "The installer will exit. Try installing jsh yourself with the 'make' utility." 27 | echo "See https://github.com/jovanbulck/jsh/wiki/Compiling-and-running for more info." 28 | exit 1 29 | fi 30 | 31 | if [ `uname -s` = "FreeBSD" ]; then 32 | MAKE=gmake 33 | MAN_PATH="/usr/local/man/man1" 34 | if ! [ command -v gmake >/dev/null 2>&1 ]; then 35 | echo "BSD system detected. It seems GNU make ('gmake') isn't installed though." 36 | echo "The installer will exit. Try installing jsh yourself with the 'gmake' utility." 37 | echo "See https://github.com/jovanbulck/jsh/wiki/Compiling-and-running for more info." 38 | exit 1 39 | fi 40 | else 41 | MAKE=make 42 | MAN_PATH="/usr/local/share/man/man1" 43 | fi 44 | 45 | # default values, overridable by user via dialogs 46 | INSTALL_PATH="/usr/local/bin" 47 | 48 | MAKE_MAN=true 49 | COLOR_OUTPUT=true 50 | RC_FILE=true 51 | DEBUG=false 52 | 53 | ############################## COMMON THINGS ############################# 54 | 55 | # common options for all dialogs 56 | DIALOG="dialog --stderr --clear" 57 | 58 | # create a tempfile to hold dialogs responses 59 | tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/jsh_installer_tmp$$ 60 | another_temp_file=`tempfile 2>/dev/null` || another_temp_file=/tmp/jsh_installer_other_tmp$$ 61 | 62 | exit_installer() 63 | { 64 | clear 65 | echo "jsh installation aborted" 66 | rm -f $tempfile 67 | rm -f $another_temp_file 68 | exit 1 69 | } 70 | 71 | # cleanup tempfile if any of the signals - SIGHUP SIGINT SIGTERM it received. 72 | trap exit_installer SIGHUP SIGINT SIGTERM 73 | 74 | exit_installer_success() 75 | { 76 | clear 77 | echo "jsh installer exited successfully" 78 | rm -f $tempfile 79 | rm -f $another_temp_file 80 | exit 0 81 | } 82 | 83 | display_info() 84 | { 85 | $DIALOG --backtitle "jsh installer" \ 86 | --title "$1" \ 87 | --msgbox "$2" 10 50 88 | retval=$? 89 | if [ $retval -eq 255 ] 90 | then 91 | exit_installer 92 | fi 93 | } 94 | 95 | # the following sections define some dialog fucntions in order to move forward / back 96 | # between them; exection starts at the "hello dialog" below 97 | 98 | ############################## MAKE OUTPUT DIALOG ############################## 99 | 100 | display_make() 101 | { 102 | MAKE_ARGS="$1" 103 | MAKE_CMD="$MAKE $MAKE_ARGS 2>&1 | \ 104 | $DIALOG --backtitle \"jsh installer\" \ 105 | --title \"making jsh\" \ 106 | --ok-label \"Continue\" \ 107 | --programbox 'make $MAKE_ARGS output' 108 | 100 100" 109 | 110 | # see if we need sudo (have write rights to install directories) 111 | if [ ! -w $INSTALL_PATH ] || ( $MAKE_MAN && [ ! -w $MAN_PATH ]) 112 | then 113 | clear 114 | echo "The installer will now execute 'make $MAKE_ARGS'. \ 115 | Since you don't have write rights to these directories, we'll use sudo. Type your sudo \ 116 | password below:" 117 | # run the whole pipeline as sudo to avoid having sudo prompting and messing up the 118 | # stdout of the dialog 119 | echo $MAKE_CMD | sudo sh 120 | else 121 | echo $MAKE_CMD | sh 122 | fi 123 | 124 | #TODO this isn't the return value of make... 125 | retval=$? 126 | echo $retval 127 | echo $another_temp_file 128 | if [ ! $retval -eq 0 ] 129 | then 130 | display_info "make jsh" "make exited with an error (return value = $retval) \ 131 | The installer will now exit.\n\nSee (https://github.com/jovanbulck/jsh/ \ 132 | wiki/Compiling-and-running) for help on compiling jsh for your system." 133 | exit_installer 134 | fi 135 | } 136 | 137 | ############################## INSTALL TARGETS DIALOG ############################# 138 | 139 | query_install_uninstall() 140 | { 141 | $DIALOG --backtitle "jsh installer" \ 142 | --title "Install / uninstall" \ 143 | --ok-label "Continue" \ 144 | --cancel-label "Stop the time" \ 145 | --radiolist "Do you want to install or uninstall jsh?" 9 75 5 \ 146 | "install" "install jsh binary and / or man page" on \ 147 | "uninstall" "remove jsh binary and man page from default locations" off \ 148 | 2> $tempfile 149 | 150 | retval=$? 151 | case $retval in 152 | 0) # OK pressed; parse response 153 | choice=`cat $tempfile` 154 | if [ $choice = "install" ] 155 | then 156 | query_compile_flags # continue to the next dialog 157 | else 158 | display_make "uninstall JSH_INSTALL_DIR="$INSTALL_PATH" MANPAGE_INSTALL_DIR="$MAN_PATH"" 159 | display_info "uninstall jsh" "jsh is successfully uninstalled from $INSTALL_PATH and \ 160 | $MAN_PATH\n\njsh development is an ongoing process. Give it a try any time later ;-)" 161 | exit_installer_success 162 | fi;; 163 | 1) 164 | exit_installer;; # "Stop the time" pressed 165 | 255) 166 | exit_installer;; # ESC pressed 167 | esac 168 | } 169 | 170 | ############################## COMPILE FLAGS DIALOG ############################# 171 | 172 | query_compile_flags() 173 | { 174 | # set saved state 175 | if $MAKE_MAN ; then TOGGLE_MAN=on ; else TOGGLE_MAN=off ; fi 176 | if $COLOR_OUTPUT ; then TOGGLE_COLOR=on ; else TOGGLE_COLOR=off ; fi 177 | if $RC_FILE ; then TOGGLE_RC=on ; else TOGGLE_RC=off ; fi 178 | if $DEBUG ; then TOGGLE_DBG=on ; else TOGGLE_DBG=off ; fi 179 | 180 | $DIALOG --backtitle "jsh installer" \ 181 | --title "Compile flags" \ 182 | --separate-output \ 183 | --ok-label "Continue" \ 184 | --cancel-label "Back" \ 185 | --checklist "Select the compile flags below" 12 90 5 \ 186 | "man" "include a UNIX man page for jsh, available via 'man jsh'" $TOGGLE_MAN \ 187 | "color" "colorize jsh debug and error messages" $TOGGLE_COLOR \ 188 | "rcfile" "auto load the ~/.jshrc file at jsh startup" $TOGGLE_RC \ 189 | "debug" "turn on debug output by default" $TOGGLE_DBG \ 190 | 2> $tempfile 191 | # some more future option ideas: 192 | # "update" "check for new jsh release at jsh startup" off \ 193 | # "fallback" "don't use the GNU readline library for input line editing and history" off \ 194 | 195 | retval=$? 196 | case $retval in 197 | 0) # OK pressed; parse response 198 | #default all flags to false; any flag chosen by the user will be overriden 199 | MAKE_MAN=false 200 | COLOR_OUTPUT=false 201 | RC_FILE=false 202 | DEBUG=false 203 | 204 | while read line 205 | do 206 | case ${line} in 207 | "man") 208 | MAKE_MAN=true;; 209 | "color") 210 | COLOR_OUTPUT=true;; 211 | "rcfile") 212 | RC_FILE=true;; 213 | "debug") 214 | DEBUG=true;; 215 | esac 216 | done < $tempfile 217 | query_install_dir;; # continue to the next dialog 218 | 1) 219 | query_install_uninstall;; # Back pressed 220 | 255) 221 | exit_installer;; # ESC pressed 222 | esac 223 | } 224 | 225 | ############################## SELECT INSTALL DIRECTORY DIALOG ################### 226 | 227 | query_install_dir() 228 | { 229 | 230 | if $MAKE_MAN ; then OK_LABEL="Continue" ; else OK_LABEL="Install now" ; fi 231 | 232 | $DIALOG --backtitle "jsh installer" \ 233 | --title "Choose install directory" \ 234 | --ok-label "$OK_LABEL" \ 235 | --cancel-label "Back" \ 236 | --inputbox "type the jsh installation directory below" \ 237 | 7 50 "$INSTALL_PATH" \ 238 | 2> $tempfile 239 | 240 | retval=$? 241 | case $retval in 242 | 0) # OK pressed; set install path 243 | inputline=`cat $tempfile` 244 | if [ ! -d $inputline ] 245 | then 246 | display_info "Choose install directory" "The install path you choose isn't a valid \ 247 | directory. Too bad, try again..." 248 | query_install_dir 249 | else 250 | INSTALL_PATH=$inputline 251 | query_man_dir # continue to next dialog 252 | fi;; 253 | 1) # "back" button pressed 254 | query_compile_flags;; 255 | 255) 256 | exit_installer;; # ESC pressed 257 | esac 258 | } 259 | 260 | ############################## SELECT MAN INSTALL DIRECTORY DIALOG ################### 261 | 262 | query_man_dir() 263 | { 264 | if $MAKE_MAN 265 | then 266 | $DIALOG --backtitle "jsh installer" \ 267 | --title "Install directory" \ 268 | --ok-label "Install now" \ 269 | --cancel-label "Back" \ 270 | --inputbox "type the jsh manpage installation directory below" \ 271 | 8 50 "/usr/local/share/man/man1" \ 272 | 2> $tempfile 273 | retval=$? 274 | case $retval in 275 | 0) # OK pressed; parse response 276 | inputline=`cat $tempfile` 277 | if [ ! -d $inputline ] 278 | then 279 | display_info "Choose man install directory" "The man install path you \ 280 | choose isn't a valid directory. Too bad, try again..." 281 | query_man_dir 282 | else 283 | MAN_PATH=$inputline 284 | # continue normal execution 285 | fi;; 286 | 1) # "back" button 287 | query_install_dir;; 288 | 255) 289 | exit_installer;; # ESC pressed 290 | esac 291 | else 292 | true # continue normal execution 293 | fi 294 | } 295 | 296 | ############################## HELLO DIALOG ############################# 297 | 298 | $DIALOG --backtitle "jsh installer" --title "Install jsh" \ 299 | --msgbox "Hello $USER, this installer will guide you through \ 300 | the jsh build and install process.\n\nHit enter to continue; ESC any time to abort." 10 41 301 | 302 | retval=$? 303 | if [ $retval -eq 255 ] 304 | then 305 | exit_installer 306 | fi 307 | 308 | # start normal execution of the above dialogs on the next line; continue below thereafter 309 | query_install_uninstall 310 | 311 | ############################## JSH CONFIG FILES ############################## 312 | 313 | show_config_file_dialog() 314 | { 315 | file=$1 316 | $DIALOG --backtitle "jsh installer" \ 317 | --title "Create jsh configuration file" \ 318 | --yesno "The installer hasn't found an existing '$file' config file. \ 319 | Should I create an empty one? You will be provided with the possibility \ 320 | to edit it afterwards." 8 60 321 | retval=$? 322 | case $retval in 323 | 0) # Yes : create a default file and edit 324 | touch $file 325 | echo $2 > $file 326 | if [ $# -eq 3 ] && [ $3 = "add_dummy_conf" ] 327 | then 328 | echo "#" >> $file 329 | echo "# Insert commands here to create your own custom jsh shell! :-)" >> $file 330 | echo "# To get you started, see (https://github.com/jovanbulck/jsh/wiki/Sample-\ 331 | configuration-files)" >> $file 332 | echo "# for more info and example configuration files" >> $file 333 | echo "" >> $file 334 | echo "" >> $file 335 | fi 336 | show_edit_config_file_dialog $file;; 337 | 1) # No : continue normal execution 338 | ;; 339 | 255) # ESC pressed 340 | exit_installer;; 341 | esac 342 | } 343 | 344 | show_edit_config_file_dialog() 345 | { 346 | file=$1 347 | $DIALOG --backtitle "jsh installer" \ 348 | --title "Edit the new jsh configuration file below" \ 349 | --editbox $file 50 100 \ 350 | 2> $tempfile 351 | 352 | retval=$? 353 | case $retval in 354 | 0) # OK : write out the file 355 | cp $tempfile $file;; 356 | 1) # Cancel : continue normal execution; dont write out the file 357 | ;; 358 | 255) # ESC 359 | exit_installer;; 360 | esac 361 | } 362 | 363 | if $RC_FILE && [ ! -e "$HOME/.jshrc" ] 364 | then 365 | show_config_file_dialog "$HOME/.jshrc" "# ~/.jshrc : file containing jsh-shell commands \ 366 | executed by jsh on startup of an interactive session" "add_dummy_conf" 367 | fi 368 | 369 | if [ ! -e "$HOME/.jsh_logout" ] 370 | then 371 | show_config_file_dialog "$HOME/.jsh_logout" "# ~/.jsh_logout: a file containing jsh-shell \ 372 | commands executed by jsh when exiting an interactive sesssion." "add_dummy_conf" 373 | fi 374 | 375 | if [ ! -e "$HOME/.jsh_login" ] 376 | then 377 | show_config_file_dialog "$HOME/.jsh_login" "Hi $USER, welcome back to jsh!" 378 | fi 379 | 380 | ############################## MAKE INSTALL JSH ############################ 381 | 382 | # determine the corresponding compile flags previously toggled by the user via dialogs 383 | INSTALL_CFLAGS="" 384 | 385 | if ! $DEBUG; then INSTALL_CFLAGS="$INSTALL_CFLAGS-DNODEBUG "; fi 386 | if ! $COLOR_OUTPUT; then INSTALL_CFLAGS="$INSTALL_CFLAGS-DNOCOLOR "; fi 387 | if ! $RC_FILE; then INSTALL_CFLAGS="$INSTALL_CFLAGS-DNORC "; fi 388 | 389 | FLAGS="install JSH_INSTALL_DIR=\"$INSTALL_PATH\" MANPAGE_INSTALL_DIR=\"$MAN_PATH\" \ 390 | INSTALL_CFLAGS=\"$INSTALL_CFLAGS\"" 391 | if ! $MAKE_MAN; then FLAGS="$FLAGS NO_MAKE_MAN=\"true\""; fi 392 | 393 | display_make "$FLAGS" 394 | 395 | ############################## DEFAULT SHELL DIALOG ############################ 396 | 397 | $DIALOG --backtitle "jsh installer" \ 398 | --title "jsh as default shell" \ 399 | --no-label "Yes" --yes-label "No" \ 400 | --yesno "Do you want to set jsh as your default UNIX login shell? \ 401 | (currently not recommended)" 6 50 402 | 403 | retval=$? 404 | case $retval in 405 | 0) # No pressed 406 | ;; # continue normal execution 407 | 1) # Yes pressed 408 | clear 409 | echo "changing the default shell to jsh" 410 | OLD_SHELL=$SHELL 411 | # redirect chsh stdout and stderr to screen as well as to a file 412 | # save the return value of chsh (otherwise $? will be the ret value of tee) 413 | { chsh -s /usr/local/bin/jsh 2>&1 ; echo $? > $another_temp_file; } | tee $tempfile 414 | 415 | chsh_retval=`cat $another_temp_file` 416 | if [ $chsh_retval -eq 0 ] 417 | then 418 | display_info "changing shell to jsh" "chsh exited successfully: \njsh is now \ 419 | your default UNIX login shell. Use 'chsh -s $OLD_SHELL' any time to revert the default shell." 420 | else 421 | display_info "changing shell to jsh" "Your default UNIX login shell hasn't \ 422 | changed. Use 'chsh -s $INSTALL_PATH/jsh' after the installation to retry. chsh says\n\n \ 423 | `cat $tempfile`" 424 | fi;; 425 | 255) # ESC pressed 426 | exit_installer;; 427 | esac 428 | 429 | ############################## EXIT SUCCESS DIALOG ############################# 430 | 431 | display_info "jsh installation completed" "jsh is successfully installed on your system. \ 432 | Have fun with your new shell!\n\n`$INSTALL_PATH/jsh --version`" 433 | 434 | exit_installer_success 435 | -------------------------------------------------------------------------------- /jsh-parse.c: -------------------------------------------------------------------------------- 1 | /* This file is part of jsh. 2 | * 3 | * jsh: A basic UNIX shell implementation in C 4 | * Copyright (C) 2014 Jo Van Bulck 5 | * 6 | * jsh is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * jsh is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with jsh. If not, see . 18 | * 19 | * ---------------------------------------------------------------------- 20 | * jsh-parse.c: a file containing functions to parse input according to the following grammar: 21 | * 22 | * input := expr 23 | * 24 | * expr := expr // expr is a logical combination 25 | * expr 26 | * expr #comment 27 | * "expr" 28 | * (expr) 29 | * expr ; expr 30 | * expr && expr 31 | * expr || expr 32 | * cmd 33 | * 34 | * cmd := cmd | cmd // cmd is the unit of truth value evaluation 35 | * cmd >> path // note: pipe redirection get priority over explicit redirection 36 | * cmd 2> path 37 | * cmd > path 38 | * cmd < path 39 | * cmd & *TODO 40 | * comd 41 | * 42 | * comd := comd option // comd is the unit of fork / built_in 43 | * comd "option with spaces" // TODO? e.g. echo "ik ben jo" en git commit -m "dit is een message" 44 | * alias // note priority: alias > built_in > executable 45 | * built_in 46 | * executable_path // relative (using the PATH env var) or absolute 47 | * ---------------------------------------------------------------------- 48 | * 49 | * e.g. : ls / -l >> out.txt && cat < out.txt | grep --color=auto -B 2 usr ; pwd 50 | * (ls -al > outfile && cat outfile | grep jsh | wc -w ) &&(pwd || echo i am not executing);echo final 51 | * (../exit -1&&echo i am not executing ||echo me neither); pwd 52 | * ((../exit -1&& echo i am not executing)|| echo i am);pwd 53 | * ( ( (a && b) || (c) ) && (d) ) 54 | * ls | grep out | print | print | print | cat | print | print | cat | print 55 | * (debug off && (echo cur dir is && pwd) && (history | grep ls | shcat | cat | shcat | ../mini-grep pwd | 56 | * cat | shcat | shcat | ../mini-grep shcat)) #comment 57 | * echo hi # dit ~ is (commentaar) && pwd ; dit (((ook cd && ### echo jo ) 58 | * 59 | * TODO alias replacement between () for truth value? 60 | */ 61 | 62 | #include "jsh-parse.h" 63 | 64 | #define RESOLVE_TRUTH_VAL(rv) ((rv == EXIT_SUCCESS)? 'T' : 'F') // note: 'T' and 'F' are built-ins 65 | 66 | // #################### helper function definitions #################### 67 | comd *createcomd(char**); 68 | void freecomdlist(comd*); 69 | int parsecmd(char**, int); 70 | int execute(comd*, int); 71 | void redirectstreams(comd*, int, int); 72 | int exec_built_in(comd*, int, int); 73 | extern int is_built_in(comd*); 74 | extern int parse_built_in(comd*, int); 75 | 76 | /* 77 | * createcomd: returns a pointer to a newly created comd struct, 78 | * using defaults: {cmd, lengthof(cmd), NULL, NULL, NULL, 0, NULL} 79 | * The caller should free() the returned comd after use, e.g. using the freecomdlist() function. 80 | */ 81 | comd *createcomd(char **cmd) { 82 | comd *ret = malloc(sizeof(comd)); //TODO chkerr 83 | ret->cmd = cmd; 84 | 85 | // calculate cmd length 86 | int i, length = 0; 87 | for (i = 0; cmd[i] != NULL; i++) 88 | length++; 89 | 90 | ret->length = length; 91 | ret->inf = NULL; 92 | ret->outf = NULL; 93 | ret->errf = NULL; 94 | ret->append_out = 0; 95 | ret->next = NULL; 96 | return ret; 97 | } 98 | 99 | /* 100 | * free()s the provided comd chain 101 | */ 102 | void freecomdlist(comd *list) { 103 | comd *cur = list; 104 | while (cur != NULL) { 105 | printdebug("freeing comd struct for '%s'", *cur->cmd); 106 | comd *temp = cur; 107 | cur = cur->next; 108 | free(temp); 109 | } 110 | } 111 | 112 | /** 113 | * TODO also take aliases etc into account 114 | */ 115 | int parse_from_file(char *line) { 116 | char *resolved = resolvealiases(line); 117 | int rv = parseexpr(resolved); 118 | free(resolved); 119 | return rv; 120 | } 121 | 122 | /* 123 | * parseexpr: parses the '\0' terminated expr string recursivly, according to the 'expr' grammar. 124 | * returns exit status (EXIT_SUCCESS || !EXIT_SUCCESS) of executed expression 125 | */ 126 | //int parseexpr(char **expr, int length) { //TODO length arg?? ipv null term string 127 | int parseexpr(char *expr) { 128 | int resolvebrackets(char*, int); //helper functions declarations 129 | int splitexpr(char*, char***); 130 | int length = strlen(expr); 131 | int i, rv; 132 | bool inquotes = false; 133 | 134 | /**** 0. skip all leading spaces tabs and newlines ****/ 135 | int k = strspn(expr, " \t\n"); 136 | expr = expr + k; 137 | if (k) 138 | printdebug("parseexpr: skipped %d leading spaces/tabs", k); 139 | 140 | /**** 1. BRACKETS: resolve, if any ****/ 141 | if ((rv = resolvebrackets(expr, length)) != -1) 142 | return rv; 143 | 144 | /**** 2. OPERATORS: first subexpression (till first logic operator) has no more brackets ****/ 145 | for (i = 0; i < length; i++) { 146 | if (inquotes && (expr[i] != '"' || expr[i-1] == '\\')) 147 | continue; //(unescaped) quotes protect their content from being interpreted 148 | else if (expr[i] == '#') { 149 | expr[i] = '\0'; 150 | return parseexpr(expr); 151 | } 152 | else if (expr[i] == '"' && (i == 0 || expr[i-1] != '\\')) { 153 | inquotes = inquotes?false:true; 154 | } 155 | else if (expr[i] == ';') { 156 | expr[i] = '\0'; 157 | parseexpr(expr); 158 | return parseexpr(expr+i+1); 159 | } 160 | else if (strncmp(expr+i, "&&", 2) == 0) { 161 | expr[i] = '\0'; 162 | if (parseexpr(expr) == EXIT_SUCCESS) 163 | return parseexpr(expr+i+2); 164 | else 165 | return EXIT_FAILURE; 166 | } 167 | else if (strncmp(expr+i, "||", 2) == 0) { 168 | expr[i] = '\0'; 169 | if (parseexpr(expr) != EXIT_SUCCESS) 170 | return parseexpr(expr+i+2); 171 | else 172 | return EXIT_SUCCESS; 173 | } 174 | } 175 | 176 | /**** 3. BASE: expr is a cmd ****/ 177 | char **curcmd; 178 | length = splitexpr(expr, &curcmd); // split the expression, using space as a delimiter 179 | rv = parsecmd(curcmd, length); 180 | printdebug("parseexpr: expr evaluated with return value %d", rv); 181 | return rv; 182 | } 183 | 184 | /* 185 | * resolvebrackets helper function: recursively resolve any subexpression *directly* following an opening '(' left bracket 186 | * returns exit status (EXIT_SUCCESS || !EXIT_SUCCESS) of executed expression or -1 if no brackets where evaluated. 187 | */ 188 | int resolvebrackets(char *expr, int length) { 189 | char *l = strchr(expr,'('); // pointer to first '(' 190 | if (l == NULL || l > expr) // '(' must be at the start of expr 191 | return -1; 192 | 193 | int i, rv, count = 0; 194 | char *r = NULL; 195 | // 1. find pointer *r to matching ')' 196 | for (i = 1; i < length; i++) 197 | if (expr[i] == '(') 198 | count++; 199 | else if (expr[i] == ')') { 200 | if (count == 0) { 201 | r = expr + i; 202 | break; 203 | } 204 | else 205 | count--; 206 | } 207 | 208 | if (r == NULL) { 209 | printerr("parse errror: unbalanced parenthesis when evaluating '%s'", expr); 210 | return EXIT_FAILURE; 211 | } 212 | 213 | // 2. (recursively) parse the expression between brackets 214 | *r = '\0'; 215 | printdebug("resolvebrackets: now evaluating '%s'", l+1); 216 | rv = parseexpr(l+1); 217 | 218 | /* 3. parse the remainder of the expression, replacing the evaluated subexpression with 219 | its built-in truth value (T | F), using memmove for overlapping memory 220 | [--> no buf overflow, since at least 2 chars '(' and ')' are replaced with a single 'T' or 'F' char] 221 | */ 222 | *l = RESOLVE_TRUTH_VAL(rv); 223 | memmove(l + 1, r + 1, strlen(r+1)+1); // len+1 : also copy the '\0' 224 | printdebug("resolvebrackets: input resolved to '%s'", l); 225 | return parseexpr(l); 226 | } 227 | 228 | /* 229 | * splitexpr helper function: splits a '\0' terminated input string *expr, using space as a delimiter. Note spaces can be '\ ' escaped. 230 | * initializes the provided pointer ***ret to point to a NULL terminated array of pointers to *expr space-delimited-substrings 231 | * returns curcmd array length 232 | * TODO DONE NOTE: this funtion expects an expr without redundant spaces (as is converted by resolvealiases() for example) 233 | */ 234 | int splitexpr(char *expr, char ***ret) { 235 | static char **curcmd = NULL; // array of pointers to current cmd and its arguments 236 | static int curcmd_realloc = 0; // total nb of reallocations for curcmd 237 | int j = 0; // index in curcmd[] array 238 | int length = strlen(expr); 239 | 240 | #define CMD_OPT_ALLOC_UNIT 10 // unit of re-allocation for curcmd[] 241 | #define REALLOC_CURCMD \ 242 | if (!(curcmd = realloc(curcmd, sizeof (char*) * CMD_OPT_ALLOC_UNIT * ++curcmd_realloc))) { \ 243 | printf("FAILED"); \ 244 | printerrno("Running out of memory. Exiting"); \ 245 | exit(EXIT_FAILURE); \ 246 | } 247 | 248 | // 0. allocate init space on the heap 249 | if (!curcmd_realloc) 250 | REALLOC_CURCMD; 251 | 252 | // 1. skip all leading spaces 253 | int i = strspn(expr, " "); 254 | char *ch = expr + i; // ch is pointer to the next token to add 255 | 256 | // 2. split using space as a delimiter 257 | for (; i < length; i++) { 258 | // allow escaping (i.e. skipping) the next char 259 | #define CHK_ESCAPING(index) \ 260 | if (expr[index] == '\\' && index < length-1) { \ 261 | printdebug("escaping char '%c' in '%s'", expr[index+1], ch); \ 262 | memmove(expr+index, expr+index+1, strlen(expr+index+1) + 1); \ 263 | length--; \ 264 | index++; \ 265 | } 266 | 267 | CHK_ESCAPING(i) 268 | if (expr[i] == '"') { //TODO TODO doc -> protect content 269 | expr[i] = '\0'; 270 | if (ch < expr + i) 271 | curcmd[j++] = ch; //TODO realloc?? 272 | ch = expr + i + 1; 273 | int k; 274 | bool found = false; 275 | for (k=i+1; k < length && !found; k++) { 276 | CHK_ESCAPING(k) 277 | if (expr[k] == '"') { 278 | expr[k] = '\0'; 279 | curcmd[j++] = ch; //TODO realloc?? 280 | ch = expr + k + 1; 281 | found = true; 282 | } 283 | } 284 | if (!found) 285 | printerr("parse errror: unbalanced quoting -> added end quotes \"%s\"...", ch); 286 | i = k-1; 287 | } 288 | else if (expr[i] == ' ') { 289 | expr[i] = '\0'; 290 | if (ch < expr + i) //TODO TODO doc 291 | curcmd[j++] = ch; 292 | ch = expr + i + 1; 293 | // realloc curcmd[] if needed 294 | if (j >= CMD_OPT_ALLOC_UNIT * curcmd_realloc) 295 | REALLOC_CURCMD; 296 | } 297 | } 298 | 299 | if (j == 0 || *ch) // ignore trailing spaces 300 | curcmd[j++] = ch; // add trailing token 301 | curcmd[j] = NULL; 302 | 303 | *ret = curcmd; // set provided pointer 304 | return j; // return curcmd array length 305 | } 306 | 307 | /* 308 | * parsecmd: parses the space delimited cmd[lenght] array, according to the 'cmd' grammar. 309 | * returns exit status (EXIT_SUCCESS || !EXIT_SUCCESS) of executed cmd 310 | */ 311 | int parsecmd(char **cmd, int length) { 312 | comd *pipeline_head = createcomd(cmd); 313 | comd *pipeline_tail = pipeline_head; 314 | 315 | #define CHK_FILE(op) \ 316 | if (i >= length - 1) { \ 317 | printerr("parse error: no file specified after redirection operator '%s'", op); \ 318 | return EXIT_FAILURE; \ 319 | } 320 | 321 | int i, nbpipes; 322 | for (i = 0, nbpipes = 0; i < length; i++) { 323 | if (*cmd[i] == '|') { 324 | cmd[i] = NULL; 325 | pipeline_tail->length = i; 326 | comd *new = createcomd(cmd+i+1); 327 | pipeline_tail->next = new; 328 | pipeline_tail = new; 329 | nbpipes++; 330 | } 331 | else if (*cmd[i] == '<') { 332 | CHK_FILE("<") 333 | cmd[i++] = NULL; 334 | pipeline_tail->inf = cmd[i]; 335 | } 336 | else if (strncmp(cmd[i], ">>", 2) == 0) { 337 | CHK_FILE(">>") 338 | cmd[i++] = NULL; 339 | pipeline_tail->outf = cmd[i]; 340 | pipeline_tail->append_out = 1; 341 | } 342 | else if (strncmp(cmd[i], "2>", 2) == 0) { 343 | CHK_FILE("2>") 344 | cmd[i++] = NULL; 345 | pipeline_tail->errf = cmd[i]; 346 | } 347 | else if (*cmd[i] == '>') { 348 | CHK_FILE(">") 349 | cmd[i++] = NULL; 350 | pipeline_tail->outf = cmd[i]; 351 | } 352 | } 353 | // base: pipeline of comds 354 | return execute(pipeline_head, nbpipes); 355 | } 356 | 357 | /* 358 | * execute: execute a list of comds as a pipeline, using fork and exec. 359 | * specified number of pipes npipes = (length of pipeline - 1) 360 | * returns the exit status (EXIT_SUCCESS || !EXIT_SUCCESS) of the last process in the pipeline 361 | * 362 | * Note: - pipe redirecting has priority over explicit redirecting: 363 | * e.g. ls > out | less : ls stdout will *only* be directed to less 364 | */ 365 | int execute(comd *pipeline, int npipes) { 366 | int i, pfds[npipes*2]; 367 | // 0. create n pipes and store the file descriptors 368 | for (i = 0; i < npipes; i++) 369 | if (pipe(pfds+i*2) < 0) { 370 | printerrno("Couldn't create pipe"); 371 | exit(EXIT_FAILURE); 372 | } 373 | #define CLOSE_ALL_PIPES \ 374 | for (k = 0; k < npipes*2; k++) \ 375 | if (pfds[k] != -1 && close(pfds[k]) == -1) \ 376 | printerrno("couldn't close pipefd %d", pfds[k]); 377 | #define CLOSE_PREV_PIPE \ 378 | if (stdoutfd != -1 && close(stdoutfd) == -1) \ 379 | printerrno("couldn't close writing end with pipefd %d", pfds[k]); \ 380 | else \ 381 | pfds[j+1] = -1; // to indicate this side is closed 382 | 383 | comd *cur = pipeline; 384 | int j, k, status = 0, nbchildren = 0; 385 | /* 1. fork nbchildren = (npipes + 1 - nbuiltins) child processes and connect them to the pipes 386 | NOTE: each iteration: close the writing end of the prev pipe to indicate the parent process (jsh) 387 | won't use it anymore; otherwise, the next process (built_in) in the pipeline won't receive the EOF...*/ 388 | for (i = 0, j = 0; i <= npipes; i++, j+=2, cur = cur->next) { 389 | /**** pipe stdin iff not first cmd; stdout iff not last cmd ****/ 390 | int stdinfd = (i > 0)? pfds[j-2] : -1; 391 | int stdoutfd = (i < npipes)? pfds[j+1] : -1; 392 | 393 | //TODO TODO 394 | //*cur->cmd = resolvealiases(*cur->cmd); 395 | 396 | /**** try to execute cur as a built_in ****/ 397 | if ((status = exec_built_in(cur, stdinfd, stdoutfd)) != -1) { 398 | printdebug("built-in: executed '%s'", *cur->cmd); 399 | CLOSE_PREV_PIPE 400 | continue; 401 | } 402 | 403 | /**** cur is not a built-in; fork a child process ****/ 404 | nbchildren++; 405 | pid_t pid = fork(); 406 | if (pid == -1) { 407 | printerrno("Creation of child process failed. Exiting"); 408 | exit(EXIT_FAILURE); 409 | } 410 | else if (pid == 0) { 411 | // ######## child process execution: redirect streams, setup pipe and execv ######## 412 | printdebug("fork: now executing '%s'", *cur->cmd); 413 | I_AM_FORK = 1; 414 | 415 | redirectstreams(cur, stdinfd, stdoutfd); 416 | CLOSE_ALL_PIPES; // no longer needed 417 | // TODO use exevp to auto search for the cmd, using the PATH env 418 | if (execvp(*cur->cmd, cur->cmd) < 0) { 419 | printerrno("couldn't execute command '%s'", *cur->cmd); //TODO here no color since !(is_interactive)... 420 | exit(EXIT_FAILURE); 421 | } 422 | } 423 | // ######## parent process execution: continue loop ######## 424 | CLOSE_PREV_PIPE 425 | } 426 | // ######## continued parent process execution: wait for children completion ######## 427 | CLOSE_ALL_PIPES; // close all remaining open pipe fds; no longer needed 428 | 429 | // wait for children completion 430 | WAITING_FOR_CHILD = true; 431 | int statuschild = 0; 432 | for (k = 0; k < nbchildren; k++) { 433 | wait(&statuschild); 434 | printdebug("waiting completed: child %d of %d", k+1, nbchildren); 435 | } 436 | WAITING_FOR_CHILD = false; 437 | 438 | // free() the comd list 439 | freecomdlist(pipeline); 440 | 441 | // return status of last process in the pipeline 442 | status = ((status == -1)? statuschild: status); 443 | return ((WIFEXITED(status)? WEXITSTATUS(status): WTERMSIG(status))); //TODO WIFSTOPPED 444 | 445 | /*int rv; 446 | if ( WIFSIGNALED(status) ) { 447 | rv = WTERMSIG(status); 448 | printdebug("child terminated with value: %d", rv); 449 | } 450 | else if (WIFEXITED(status)) { 451 | rv = WEXITSTATUS(status); 452 | printdebug("child exited with value %d", rv); 453 | } 454 | else { 455 | printdebug("child stopped how???"); 456 | exit(EXIT_FAILURE); 457 | } 458 | return rv; 459 | 460 | if (WIFSTOPPED(status)) 461 | printf("Child received SIGTSTP"); 462 | */ 463 | } 464 | 465 | /* 466 | * exec_built_in: try to execute the provided *comd as a built_in shell command; 467 | * wrapper for parse_built_in(), redirecting and restoring std streams if needed 468 | * the argument stdinfd and stdoutfd are file descriptors for the pipeline if any; else -1 469 | * returns -1 if command not recognized as a built_in; 470 | * else returns exit status (EXIT_FAILURE || EXIT_SUCCESS) of executed built_in 471 | */ 472 | int exec_built_in(comd *comd, int stdinfd, int stdoutfd) { 473 | int i = is_built_in(comd); 474 | if (i == -1) 475 | return -1; 476 | 477 | // redirect std streams, parse built_in and restore std streams 478 | int saved_stdin = dup(STDIN_FILENO); 479 | int saved_stdout = dup(STDOUT_FILENO); 480 | redirectstreams(comd, stdinfd, stdoutfd); 481 | int rv = parse_built_in(comd, i); 482 | REDIRECT_STR(saved_stdin, STDIN_FILENO); 483 | REDIRECT_STR(saved_stdout, STDOUT_FILENO); 484 | close(saved_stdin); 485 | close(saved_stdout); 486 | 487 | return rv; 488 | } 489 | 490 | /* 491 | * redirectstreams: redirect stdin, stdout, stderr as specified in the specified comd struct and 492 | * stdinfd/stdoutfd arguments: specifying the file descriptors for the pipeline if any; else -1 493 | * note: pipe redirection has priority over explicit redirection 494 | * on failure, prints error message and exit(EXIT_FAILURE) 495 | */ 496 | void redirectstreams(comd *cmd, int stdinfd, int stdoutfd) { 497 | if (cmd->inf != NULL) { 498 | printdebug("redirecting stdin to file '%s'", cmd->inf); 499 | int fd = open(cmd->inf, O_RDONLY); 500 | if(fd < 0) { 501 | printerrno("error opening file '%s'", cmd->inf); 502 | exit(EXIT_FAILURE); 503 | } 504 | dup2(fd, STDIN_FILENO); 505 | close(fd); // no longer needed 506 | } 507 | if (cmd->outf != NULL) { 508 | printdebug("redirecting stdout to file '%s'", cmd->outf); 509 | int fd; 510 | if (cmd->append_out) 511 | fd = open(cmd->outf, O_WRONLY | O_CREAT | O_APPEND, 0666); //rw-rw-rw; will be combined with current umask 512 | else 513 | fd = open(cmd->outf, O_WRONLY | O_CREAT | O_TRUNC, 0666); 514 | if(fd < 0) { 515 | printerrno("error opening file '%s'", cmd->outf); 516 | exit(EXIT_FAILURE); 517 | } 518 | dup2(fd, STDOUT_FILENO); 519 | close(fd); 520 | } 521 | if (cmd->errf != NULL) { 522 | printdebug("redirecting stderr to file '%s'", cmd->errf); 523 | int fd = open(cmd->errf, O_WRONLY | O_CREAT | O_TRUNC, 0666); 524 | if(fd < 0) { 525 | printerrno("error opening file '%s'", cmd->errf); 526 | exit(EXIT_FAILURE); 527 | } 528 | dup2(fd, STDERR_FILENO); 529 | close(fd); 530 | } 531 | // piping has priority: override prev redirections if any 532 | if (stdinfd != -1) { 533 | printdebug("redirecting stdin to pipefd %d", stdinfd); 534 | REDIRECT_STR(stdinfd, STDIN_FILENO); 535 | } 536 | if (stdoutfd != -1) { 537 | printdebug("redirecting stdout to pipefd %d", stdoutfd); 538 | REDIRECT_STR(stdoutfd, STDOUT_FILENO); 539 | } 540 | } 541 | 542 | /* 543 | * is_valid_cmd: returns whether or not an occurence of a cmd string is valid in a given 544 | * context string. An cmd is valid iff it occurs as a 'comd' in the grammar. 545 | * 546 | * @param cmd: the command string to be checked 547 | * @param context: the context string where the command occurs 548 | * @param i: the index in the context string where the command occurs: context+i equals cmd 549 | */ 550 | bool is_valid_cmd(const char* cmd, const char* context, int i) { 551 | #if ASSERT 552 | assert(strncmp(context+i, cmd, strlen(cmd)) == 0); 553 | #endif 554 | 555 | // check the context following the cmd occurence 556 | const char *after = context + i + strlen(cmd); 557 | bool after_ok = (*after == ' ' || *after == '\0' || *after == '|' || *after == ';' || *after == ')' || 558 | (strncmp(after, "&&", 2) == 0) || (strncmp(after, "||", 2) == 0)); 559 | 560 | if (!after_ok) 561 | return false; 562 | 563 | // check the context preceding the alias occurence 564 | const char *before = context + i; 565 | int index_before = i; 566 | while (index_before > 0 && (*(before-1) == ' ' || *(before-1) == '(')) { 567 | before--; 568 | index_before--; 569 | } 570 | 571 | bool before_ok = ( index_before == 0 || (*(before-1) == '|' || *(before-1) == ';') || 572 | (index_before >= 2 && (strncmp(before-2, "&&", 2) == 0 || strncmp(before-2, "||", 2) == 0)) 573 | || (index_before >= 4 && strncmp(before-4, "sudo", 4) == 0)); 574 | 575 | return before_ok; 576 | } 577 | -------------------------------------------------------------------------------- /jsh.c: -------------------------------------------------------------------------------- 1 | /* This file is part of jsh. 2 | * 3 | * jsh: A basic UNIX shell implementation in C 4 | * Copyright (C) 2014 Jo Van Bulck 5 | * 6 | * jsh is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * jsh is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with jsh. If not, see . 18 | */ 19 | 20 | #include "jsh-common.h" 21 | #include "jsh-colors.h" 22 | #include "alias.h" 23 | #include "jsh-parse.h" 24 | #include "jsh-completion.h" 25 | #include 26 | #include 27 | #include // GNU readline: http://cnswww.cns.cwru.edu/php/chet/readline/rltop.html 28 | #include 29 | 30 | // ########## macro definitions ########## 31 | #ifndef VERSION 32 | #define VERSION "jsh: unknown built" // makefile normally fills in the version info 33 | #endif 34 | #define RCFILE ".jshrc" 35 | #define HISTFILE ".jsh_history" 36 | #define LOGIN_FILE ".jsh_login" 37 | #define LOGOUT_FILE ".jsh_logout" 38 | #define DEFAULT_PROMPT "%B%u%n@%h[%S]::%f{yellow}%d%f{reset}%$ " // default init prompt string: "user@host[status]:pwd$ " 39 | #define MAX_PROMPT_LENGTH 250 // maximum length of the displayed prompt string 40 | #define MAX_PROMPT_BUF_LENGTH 50 // the max number of msd of a status integer in the prompt string 41 | // ########## function declarations ########## 42 | void option(char*); 43 | void things_todo_at_start(void); 44 | void things_todo_at_exit(void); 45 | char *getprompt(int); 46 | char *readcmd(int status); 47 | int is_built_in(comd*); 48 | int parse_built_in(comd*, int); 49 | void sig_int_handler(int); 50 | void touch_config_files(void); 51 | char *resolve_prompt_colors(char*); 52 | 53 | // ########## global variables ########## 54 | #ifdef NODEBUG 55 | bool DEBUG = false; 56 | #else 57 | bool DEBUG = true; 58 | #endif 59 | 60 | #ifdef NOCOLOR 61 | bool COLOR = false; 62 | #else 63 | bool COLOR = true; 64 | #endif 65 | 66 | #ifdef NORC 67 | bool LOAD_RC = false; 68 | #else 69 | bool LOAD_RC = true; 70 | #endif 71 | 72 | bool WAITING_FOR_CHILD = false; // whether or not the jsh parent process is currently (blocking) waiting for child termination 73 | bool I_AM_FORK = false; 74 | bool IS_INTERACTIVE; // initialized in things_todo_at_start; (compiler's 'constant initializer' complaints) 75 | int nb_hist_entries = 0; // number of saved hist entries in this jsh session 76 | sigjmp_buf ctrlc_buf; // buf used for setjmp/longjmp when SIGINT received 77 | char *user_prompt_string = "$ ";// initialized in things_todo_at_start function 78 | int MAX_DIR_LENGTH = 25; // the maximum length of an expanded pwd substring in the prompt string 79 | 80 | /* 81 | * built_ins[] = array of built_in cmd names; should be sorted with 'qsort(built_ins, nb_built_ins, sizeof(char*), string_cmp);' 82 | * built_in enum = value corresponds to index in built_ins[] 83 | */ 84 | const char *built_ins[] = {"", "F", "T", "alias", "cd", "color", "debug",\ 85 | "exit", "history", "prompt", "shcat", "source", "unalias"}; 86 | const size_t nb_built_ins = sizeof(built_ins)/sizeof(built_ins[0]); 87 | enum built_in {EMPTY, F, T, ALIAS, CD, CLR, DBG, EXIT, HIST, PROMPT, SHCAT, SRC, UNALIAS}; 88 | typedef enum built_in built_in; 89 | 90 | /* 91 | * 92 | * TODO gracious malloc etc 93 | * TODO snprintf ipv printf for format string vulnerabilities... 94 | * TODO gnu readline disable on non interactive input 95 | * TODO read history MAX_HIST_SIZE ofzo?? 96 | */ 97 | int main(int argc, char **argv) { 98 | int i, status; 99 | // process options 100 | for (i = 1; i < argc && *argv[i] == '-'; i++) 101 | option(argv[i]+1); 102 | 103 | things_todo_at_start(); 104 | 105 | signal(SIGINT, sig_int_handler); 106 | // after receiving SIGINT, program is continued on the next line 107 | if (sigsetjmp(ctrlc_buf, 1) == 0) 108 | status = 0; // get here on direct call 109 | else 110 | status = -1; // get here by SIGINT signal 111 | 112 | char *s; 113 | while ((s = readcmd(status)) != NULL) 114 | status = parseexpr(s); 115 | 116 | exit(EXIT_SUCCESS); 117 | } 118 | 119 | /* 120 | * option: process an option [-OPTIONCHARS] string 121 | */ 122 | void option(char *str) { 123 | void optionfull(char *s); // option helper function 124 | 125 | char *begin = str; 126 | while (*str != '\0') 127 | switch(*str++) { 128 | case '-': 129 | if (str-1 == begin) 130 | return optionfull(str); 131 | break; // else: ignore 132 | case 'h': 133 | printf("jsh: A basic UNIX shell implementation in C\n"); 134 | printf("\nRecognized options:\n"); 135 | printf("-h, --help\tdisplay this help message\n"); 136 | printf("-d, --debug\tturn printing of debug messages on\n"); 137 | printf("-n, --nodebug\tturn printing of debug messages on\n"); 138 | printf("-c, --color\tturn coloring of jsh output messages on\n"); 139 | printf("-o, --nocolor\tturn coloring of jsh output messages off\n"); 140 | printf("-f, --norc\tdisable autoloading of the ~/%s file\n", RCFILE); 141 | printf("-l, --license\tdisplay licence information\n"); 142 | printf("-v, --version\tdisplay version information\n"); 143 | printf("\nConfiguration files:\n"); 144 | printf("~/%s\tfile containing commands to be executed at login\n", RCFILE); 145 | printf("~/%s\tfile containing the welcome message auto printed at login of an interactive session\n", LOGIN_FILE); 146 | printf("~/%s\tfile containing commands to be executed at logout of an interactive session\n", LOGOUT_FILE); 147 | printf("~/%s\tfile containing the command history auto loaded and saved at login/logout\n", HISTFILE); 148 | printf("\nReport bugs to: jo.vanbulck@student.kuleuven.be\n"); 149 | printf("jsh homepage: \n"); 150 | printf("This program is free software, and you are welcome to redistribute it under\n"); 151 | printf("the condititions of the GNU General Public License. Try 'jsh --license' for more info.\n"); 152 | exit(EXIT_SUCCESS); 153 | case 'v': 154 | printf("%s\n", VERSION); 155 | exit(EXIT_SUCCESS); 156 | break; 157 | case 'd': 158 | DEBUG = true; 159 | break; 160 | case 'n': 161 | DEBUG = false; 162 | break; 163 | case 'c': 164 | COLOR = true; 165 | break; 166 | case 'o': 167 | COLOR = false; 168 | break; 169 | case 'f': 170 | LOAD_RC = false; 171 | break; 172 | case 'l': 173 | printf("jsh: A basic UNIX shell implementation in C\n"); 174 | printf("Copyright (C) 2014 Jo Van Bulck \n"); 175 | printf("\nThis program is free software: you can redistribute it and/or modify\n"); 176 | printf("it under the terms of the GNU General Public License as published by\n"); 177 | printf("the Free Software Foundation, either version 3 of the License, or\n"); 178 | printf("(at your option) any later version.\n"); 179 | 180 | printf("\nThis program is distributed in the hope that it will be useful,\n"); 181 | printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); 182 | printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); 183 | printf("GNU General Public License for more details.\n"); 184 | 185 | printf("\nYou should have received a copy of the GNU General Public License\n"); 186 | printf("along with this program. If not, see .\n"); 187 | exit(EXIT_SUCCESS); 188 | break; 189 | default: 190 | printerr("Unrecognized option '-%c'", *(str-1)); 191 | printerr("Try 'jsh --help' for a list of regognized options"); 192 | exit(EXIT_FAILURE); 193 | } 194 | } 195 | 196 | /* 197 | * optionfull: helper function to process an option string, in full [--OPTION] notation 198 | */ 199 | void optionfull(char *str) { 200 | if (strcmp(str,"nodebug") == 0) 201 | option("n"); 202 | else if (strcmp(str,"debug") == 0) 203 | option("d"); 204 | else if (strcmp(str,"nocolor") == 0) 205 | option("o"); 206 | else if (strcmp(str,"color") == 0) //TODO mss color=auto ... enum 207 | option("c"); 208 | else if (strcmp(str,"help") == 0) 209 | option("h"); 210 | else if (strcmp(str,"version") == 0) 211 | option("v"); 212 | else if (strcmp(str,"norc") == 0) 213 | option("f"); 214 | else if (strcmp(str,"license") == 0) 215 | option("l"); 216 | else { 217 | printerr("Unrecoginized option '--%s'\n", str); 218 | printerr("Try 'jsh --help' for a list of regognized options\n"); 219 | exit(EXIT_FAILURE); 220 | } 221 | } 222 | 223 | /* 224 | * things_todo_at_exit: do stuff that needs to be done at jsh login 225 | */ 226 | void things_todo_at_start(void) { 227 | // assert the built_ins array is properly sorted 228 | #if ASSERT 229 | assert(is_sorted(built_ins, nb_built_ins, sizeof(char*), string_cmp)); 230 | printdebug("built_ins array is_sorted() assertion passed :-)"); 231 | #endif 232 | 233 | // evaluate once at startup; to maintain for forked children in a pipeline 234 | IS_INTERACTIVE = (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)); 235 | 236 | touch_config_files(); 237 | 238 | // load history file if any 239 | char * path = concat(3, gethome(), "/", HISTFILE); 240 | if (read_history(path) == 0) 241 | printdebug("reading history from %s succeeded", path); 242 | else 243 | printdebug("reading history from %s failed", path); 244 | free(path); 245 | 246 | // register the things_todo_at_exit function atexit 247 | atexit(things_todo_at_exit); 248 | 249 | // enable custom rl_autocompletion 250 | rl_attempted_completion_function = jsh_command_completion; 251 | 252 | // built-in aliases 253 | alias("~", gethome()); 254 | 255 | // default prompt 256 | user_prompt_string = resolve_prompt_colors(DEFAULT_PROMPT); 257 | 258 | // read ~/.jshrc if any 259 | if (LOAD_RC) { 260 | path = concat(3, gethome(), "/", RCFILE); 261 | parsefile(path, (void (*)(char*)) parse_from_file, false); 262 | free(path); 263 | } 264 | 265 | // print welcome message (without debugging output) 266 | if (IS_INTERACTIVE) { 267 | bool temp = DEBUG; 268 | DEBUG = false; 269 | char * path = concat(3, gethome(), "/", LOGIN_FILE); 270 | parsefile(path, (void (*)(char*)) puts_verbatim, false); 271 | free(path); 272 | DEBUG = temp; 273 | printdebug("debugging is on. Turn it off with 'debug off'."); 274 | } 275 | } 276 | 277 | /* 278 | * create_config_files: looks for the jsh config files; 279 | * if not found creates new empty ones (rw-rw-rw; will be combined with current umask) 280 | */ 281 | void touch_config_files(void) { 282 | #define CREATE_F(name) \ 283 | path = concat(3, gethome(), "/", name); \ 284 | fd = open(path, O_RDWR | O_CREAT, 0666); \ 285 | if (fd >= 0) { \ 286 | printdebug("opened file %s", name); \ 287 | close(fd); \ 288 | } \ 289 | else \ 290 | printdebug("couldn't open/create file '%s': %s", name, strerror(errno)); \ 291 | free(path); 292 | 293 | char* path; 294 | int fd; 295 | CREATE_F(HISTFILE); 296 | CREATE_F(RCFILE); 297 | CREATE_F(LOGIN_FILE); 298 | CREATE_F(LOGOUT_FILE); 299 | } 300 | 301 | /* 302 | * things_todo_at_exit: do stuff that needs to be done at jsh logout (i.e. iff I_AM_FORK == 0) 303 | */ 304 | void things_todo_at_exit(void) { 305 | if (I_AM_FORK) 306 | return; //ignore exiting of child processes (e.g. failed fork execv) 307 | 308 | // execute commands in logout file (silently) 309 | if (IS_INTERACTIVE) { 310 | printdebug("now executing '%s'", LOGOUT_FILE); 311 | bool dbg = DEBUG; 312 | DEBUG = false; 313 | char *path = concat(3, gethome(), "/", LOGOUT_FILE); 314 | parsefile(path, (void (*)(char*)) parse_from_file, false); 315 | free(path); 316 | DEBUG = dbg; 317 | printdebug("'%s' executed", LOGOUT_FILE); 318 | } 319 | 320 | char * path = concat(3, gethome(), "/", HISTFILE); //TODO check this uses malloc??? fail return status? 321 | if (append_history(nb_hist_entries, path) == 0) 322 | printdebug("appending %d history entries to %s succeeded", nb_hist_entries, path); 323 | else 324 | printdebug("appending %d history entries to %s failed", nb_hist_entries, path); 325 | free(path); 326 | } 327 | 328 | /* 329 | * getprompt: return a string representing the command prompt (as defined by the user_prompt_string) 330 | * iff IS_INTERACTIVE, else the empty string is returned. The returned string is guaranteed to be less then 331 | * MAX_PROMPT_LENGTH; when a directory is expanded in the prompt string, it is 'smart' truncated to MAX_DIR_LENGTH. 332 | * When a status integer or git branch is included in the prompt string, the strings length is truncated to MAX_PROMPT_BUF_LENGTH. 333 | */ 334 | char* getprompt(int status) { 335 | // static string to hold the current prompt (return value) between function calls 336 | static char prompt[MAX_PROMPT_LENGTH] = ""; 337 | static char buf[MAX_PROMPT_BUF_LENGTH] = ""; // used for char / int to string conversion 338 | 339 | if (!IS_INTERACTIVE) 340 | return ""; 341 | 342 | prompt[0] = '\0'; // clear the prev prompt 343 | char *next; // points to the next substring to add to the prompt 344 | int i; 345 | for (i = 0; i < strlen(user_prompt_string); i++) { 346 | /*** check for '%' prompt expansion options ***/ 347 | if (user_prompt_string[i] == '%') { 348 | i++; // potentially overread the '\0' char (harmless) 349 | switch (user_prompt_string[i]) { 350 | case 'u': 351 | next = getenv("USER"); 352 | break; 353 | case 'U': 354 | { 355 | char *username = getenv("USER"); 356 | // make the username red and bold when sudo access is activated 357 | // see e.g. http://stackoverflow.com/questions/122276/quickly-check-whether-sudo-permissions-are-available 358 | char *cur_user_has_sudo = strclone("sudo -n true > /dev/null 2> /dev/null"); 359 | if (parseexpr(cur_user_has_sudo) == EXIT_SUCCESS) { 360 | snprintf(buf, MAX_PROMPT_BUF_LENGTH, "%s%s%s", COLOR_BOLD RED_FG, \ 361 | username, COLOR_RESET_BOLD RESET_FG); 362 | next = buf; 363 | } 364 | else 365 | next = username; 366 | 367 | free(cur_user_has_sudo); 368 | break; 369 | } 370 | case '$': 371 | { 372 | char *cur_user_has_sudo = strclone("sudo -n true > /dev/null 2> /dev/null"); 373 | if (parseexpr(cur_user_has_sudo) == EXIT_SUCCESS) 374 | next = "#"; 375 | else 376 | next = "$"; 377 | 378 | free(cur_user_has_sudo); 379 | break; 380 | } 381 | case 'h': 382 | { 383 | int hostlen = sysconf(_SC_HOST_NAME_MAX)+1; // Plus one for null terminate 384 | char hostname[hostlen]; 385 | gethostname(hostname, hostlen); 386 | hostname[hostlen-1] = '\0'; // Always null-terminate 387 | next = hostname; 388 | break; 389 | } 390 | case 's': 391 | snprintf(buf, MAX_PROMPT_BUF_LENGTH, "%d", status); 392 | next = buf; 393 | break; 394 | case 'S': 395 | if (!status) 396 | snprintf(buf, MAX_PROMPT_BUF_LENGTH, "%d", status); 397 | else 398 | snprintf(buf, MAX_PROMPT_BUF_LENGTH, "%s%d%s", COLOR_BOLD RED_FG, \ 399 | status, COLOR_RESET_BOLD RESET_FG); 400 | next = buf; 401 | break; 402 | case 'd': 403 | { 404 | // get the directory 405 | char *cwd = getcwd(NULL, 0); //TODO portability: this is GNU libc specific... + errchk 406 | 407 | // replace the home dir with '~' if any 408 | char *home = gethome(); 409 | if (strstr(cwd, home)) { 410 | cwd = cwd + strlen(home)-1; 411 | cwd[0] = '~'; 412 | } 413 | 414 | int cwdlen = strlen(cwd); 415 | char *ptr = NULL; 416 | // get a ptr to the first '/' + 1 within the truncated directory string 417 | if (cwdlen > MAX_DIR_LENGTH) { 418 | ptr = strchr(cwd + cwdlen - MAX_DIR_LENGTH, '/'); 419 | ptr = (ptr && ptr < cwd+cwdlen-1)? ptr+1 : ptr; 420 | } 421 | next = ptr? ptr : cwd + ((MAX_DIR_LENGTH < cwdlen) ? cwdlen - MAX_DIR_LENGTH : 0); 422 | break; 423 | } 424 | case 'g': 425 | { 426 | char *pwd_is_git = strclone("git rev-parse --git-dir > /dev/null 2> /dev/null"); 427 | if (parseexpr(pwd_is_git) == EXIT_SUCCESS) { 428 | FILE *fp = popen("git symbolic-ref --short -q HEAD", "r"); 429 | buf[0] = ' '; 430 | buf[1] = '['; 431 | buf[MAX_PROMPT_BUF_LENGTH-2] = ']'; 432 | buf[MAX_PROMPT_BUF_LENGTH-1] = '\0'; 433 | int j; 434 | for (j = 2; j < MAX_PROMPT_BUF_LENGTH-2; j++) { 435 | int cur = getc(fp); 436 | if (cur == EOF || cur == '\n') { 437 | buf[j++] = ']'; 438 | buf[j] = '\0'; 439 | break; 440 | } 441 | else 442 | buf[j] = cur; 443 | } 444 | next = buf; 445 | pclose(fp); 446 | } 447 | else 448 | next = ""; 449 | free(pwd_is_git); 450 | break; 451 | } 452 | case 'c': 453 | { 454 | char *pwd_is_git = strclone("git rev-parse --git-dir > /dev/null 2> /dev/null"); 455 | char *files_have_changed = strclone("git diff --exit-code > /dev/null 2> /dev/null"); 456 | if ( (parseexpr(pwd_is_git) == EXIT_SUCCESS) && (parseexpr(files_have_changed) != EXIT_SUCCESS) ) { 457 | snprintf(buf, MAX_PROMPT_BUF_LENGTH, "%s%c%s", COLOR_BOLD RED_FG, \ 458 | '*', COLOR_RESET_BOLD RESET_FG); 459 | next = buf; 460 | } 461 | else 462 | next = ""; 463 | free(pwd_is_git); 464 | free(files_have_changed); 465 | break; 466 | } 467 | case '%': 468 | next = "%"; 469 | break; 470 | default: 471 | printerr("skipping unrecognized prompt option '%%%c'", user_prompt_string[i]); 472 | next = ""; 473 | break; 474 | } 475 | } 476 | /*** no prompt expansion; copy the char verbatim ***/ 477 | else { 478 | sprintf(buf, "%c", user_prompt_string[i]); 479 | next = buf; 480 | } 481 | 482 | /*** check length of string to concat; abort to avoid an overflow ***/ 483 | if ((strlen(prompt) + strlen(next)) >= MAX_PROMPT_LENGTH) { 484 | printerr("Prompt expansion too long: not concatting '%s'. Now returning...", next); 485 | return prompt; 486 | } 487 | strcat(prompt, next); 488 | } 489 | return prompt; 490 | } 491 | 492 | /** 493 | * resolve_prompt_colors: return a newly malloced prompt string with the 494 | * symbolic color expansion codes replaced with the corresponding ANSI escape codes. 495 | * This function can be called once on new promp initialisation to save time on 496 | * subsequent prompt re-evaluations. 497 | * NOTE: the return value is a malloced str with length MAX_PROMPT_LENGTH; when the 498 | * expansion is longer, it is truncated and an error message is written to stdout 499 | */ 500 | char *resolve_prompt_colors(char *prompt) { 501 | char *rv = malloc(MAX_PROMPT_LENGTH); 502 | rv[0] = '\0'; 503 | char buf[3]; // to hold the next char and '%' temporarily to append to rv 504 | 505 | // macro to insert a given ANSI escape color value str iff a given name str matches 506 | #define CHK_COLOR(cname, cvalue) \ 507 | if (!strncmp(prompt+i+1, "{" cname "}", strlen("{" cname "}"))) { \ 508 | next = cvalue; \ 509 | i += strlen("{" cname "}"); \ 510 | break; \ 511 | } 512 | 513 | char *next; 514 | int i; 515 | for (i = 0; i < strlen(prompt); i++) { 516 | if (prompt[i] == '%') { 517 | i++; // potentially overread the '\0' char (harmless) 518 | switch (prompt[i]) { 519 | case 'f': 520 | // fg color, normal 521 | CHK_COLOR("black", BLACK_FG) 522 | CHK_COLOR("red", RED_FG) 523 | CHK_COLOR("green", GREEN_FG) 524 | CHK_COLOR("yellow", YELLOW_FG) 525 | CHK_COLOR("blue", BLUE_FG) 526 | CHK_COLOR("magenta", MAGENTA_FG) 527 | CHK_COLOR("cyan", CYAN_FG) 528 | CHK_COLOR("white", WHITE_FG) 529 | CHK_COLOR("reset", RESET_FG) 530 | CHK_COLOR("resetall", COLOR_RESET_ALL) 531 | 532 | printerr("resolve_prompt_colors: skipping empty color prompt option: specify non-bold fg color with '%%f{color_name}'"); 533 | next = ""; 534 | break; 535 | case 'F': 536 | // fg color, bold 537 | CHK_COLOR("black", COLOR_BOLD BLACK_FG) 538 | CHK_COLOR("red", COLOR_BOLD RED_FG) 539 | CHK_COLOR("green", COLOR_BOLD GREEN_FG) 540 | CHK_COLOR("yellow", COLOR_BOLD YELLOW_FG) 541 | CHK_COLOR("blue", COLOR_BOLD BLUE_FG) 542 | CHK_COLOR("magenta", COLOR_BOLD MAGENTA_FG) 543 | CHK_COLOR("cyan", COLOR_BOLD CYAN_FG) 544 | CHK_COLOR("white", COLOR_BOLD WHITE_FG) 545 | CHK_COLOR("reset", COLOR_RESET_BOLD RESET_FG) 546 | CHK_COLOR("resetall", COLOR_RESET_ALL) 547 | 548 | printerr("resolve_prompt_colors: skipping empty color prompt option: specify bold fg color with '%%f{color_name}'"); 549 | next = ""; 550 | break; 551 | case 'B': 552 | next = COLOR_BOLD; 553 | break; 554 | case 'n': 555 | next = COLOR_RESET_BOLD; 556 | break; 557 | case 'b': 558 | // bg color, normal 559 | CHK_COLOR("black", BLACK_BG) 560 | CHK_COLOR("red", RED_BG) 561 | CHK_COLOR("green", GREEN_BG) 562 | CHK_COLOR("yellow", YELLOW_BG) 563 | CHK_COLOR("blue", BLUE_BG) 564 | CHK_COLOR("magenta", MAGENTA_BG) 565 | CHK_COLOR("cyan", CYAN_BG) 566 | CHK_COLOR("white", WHITE_BG) 567 | CHK_COLOR("reset", RESET_BG) 568 | CHK_COLOR("resetall", COLOR_RESET_ALL) 569 | 570 | printerr("resolve_prompt_colors: skipping empty color prompt option: specify bg color with '%%b{color_name}'"); 571 | next = ""; 572 | break; 573 | default: 574 | sprintf(buf, "%%%c", prompt[i]); 575 | next = buf; 576 | break; 577 | } 578 | } 579 | /*** no prompt expansion; copy the char verbatim ***/ 580 | else { 581 | sprintf(buf, "%c", prompt[i]); 582 | next = buf; 583 | } 584 | 585 | /*** check length of string to concat; abort to avoid an overflow ***/ 586 | if ((strlen(rv) + strlen(next)) >= MAX_PROMPT_LENGTH) { 587 | printerr("Prompt expansion too long: not concatting '%s'. Now returning...", next); 588 | return rv; 589 | } 590 | strcat(rv, next); 591 | } 592 | return rv; 593 | } 594 | 595 | /* 596 | * readcmd: read the next inputline from stdin, add it to the history and resolve all aliases. 597 | * returns the resolved inputline or NULL if EOF on a blank line 598 | * TODO remove status arg? 599 | */ 600 | char *readcmd(int status) { 601 | /** static variables that remain between function calls **/ 602 | static char *buf = (char*) NULL; // inputbuffer for readline() 603 | 604 | // display prompt and read full line in buf 605 | if (buf) { 606 | printdebug("readcmd: freeing memory for: '%s'", buf); 607 | free(buf); // If the buffer has already been allocated, return the memory to the free pool. 608 | buf = NULL; 609 | } 610 | buf = readline(getprompt(status)); //TODO fall back to getline() when non-interactive... 611 | 612 | // If the line has any text in it: expand history, save it to history and resolve aliases 613 | // (readline returns NULL iff EOF on a blank line) 614 | if (buf && *buf) { 615 | printdebug("You entered: '%s'", buf); 616 | // do history expansion 617 | char *expansion = ""; 618 | int hist_rv; 619 | if ((hist_rv = history_expand(buf, &expansion)) != -1) { 620 | if (hist_rv == 1) 621 | printf("%s\n", expansion); // bash-style print the expanded command string iff changed 622 | free(buf); // free unexpanded version 623 | buf = expansion; // point to expanded cmd 624 | } 625 | else { 626 | printerr("readcmd: history expansion failed for '%s': '%s'", buf, expansion); 627 | free(expansion); 628 | } 629 | add_history(buf); 630 | nb_hist_entries++; 631 | char *ret = resolvealiases(buf); 632 | free(buf); // free unresolved version 633 | buf = ret; // point to resolved cmd 634 | } 635 | else if (!buf) { 636 | printf("\n"); 637 | printdebug("You entered EOF"); 638 | } 639 | return buf; 640 | } 641 | 642 | /* 643 | * is_built_in: returns -1 iff the provided comd isn't recognized as a built_in shell command, 644 | * else returns the (positive) index in the built_in[] array. 645 | */ 646 | int is_built_in(comd* comd) { 647 | const char **rv = bsearch(comd->cmd, built_ins, nb_built_ins, sizeof(char*), string_cmp); //TODO strncmp?? buf overflow 648 | return ((rv == NULL)? -1: rv - built_ins); 649 | } 650 | 651 | /* 652 | * parse_built_in: parses the provided *comd as a built_in shell command iff is_built_in(comd) != -1 653 | * the provided int is an index in the built_in[] array, as provided by is_built_in(comd) 654 | * returns exit status (EXIT_FAILURE || EXIT_SUCCESS) of executed built_in 655 | */ 656 | int parse_built_in(comd *comd, int index) { 657 | #if ASSERT 658 | assert(strcmp(*comd->cmd, built_ins[index]) == 0); 659 | #endif 660 | 661 | //######## common macro definitions ########### 662 | #define CHK_ARGC(cmd, argc) \ 663 | if (comd->length != argc+1) { \ 664 | printerr("%s: wrong number of arguments\t(expected = %d)", cmd, argc); \ 665 | return EXIT_FAILURE; \ 666 | } 667 | #define TOGGLE_VAR(name, var, arg) \ 668 | CHK_ARGC(name, 1); \ 669 | if (strcmp(arg, "on") == 0) { \ 670 | printinfo("%s mode on", name); \ 671 | var = 1; \ 672 | return EXIT_SUCCESS; \ 673 | } \ 674 | else if (strcmp(arg, "off") == 0) { \ 675 | printinfo("%s mode off", name); \ 676 | var = 0; \ 677 | return EXIT_SUCCESS; \ 678 | } \ 679 | else { \ 680 | printerr("%s: expects argument 'on' || 'off'", name); \ 681 | return EXIT_FAILURE; \ 682 | } 683 | //######## built-in cmds switch ########### 684 | built_in b = (built_in) index; 685 | switch(b) { 686 | case EMPTY: 687 | printdebug("built-in: ignoring empty input"); 688 | return EXIT_SUCCESS; 689 | break; 690 | case F: 691 | return EXIT_FAILURE; // FALSE 692 | break; 693 | case T: 694 | return EXIT_SUCCESS; // TRUE 695 | break; 696 | case ALIAS: 697 | if (comd->length == 1) { 698 | printaliases(); 699 | return EXIT_SUCCESS; 700 | } 701 | else { 702 | CHK_ARGC("alias", 2); 703 | return alias(comd->cmd[1], comd->cmd[2]); 704 | } 705 | break; 706 | case CD: 707 | { // to allow declarions inside a switch) 708 | char *dir; 709 | if (comd->length == 1) 710 | dir = getenv("HOME"); 711 | else { 712 | CHK_ARGC("cd",1); 713 | dir = comd->cmd[1]; 714 | } 715 | CHK_ERR(chdir(dir), "cd"); 716 | setenv("PWD", dir, 1); 717 | return EXIT_SUCCESS; 718 | break; 719 | } 720 | case CLR: 721 | TOGGLE_VAR("color", COLOR, comd->cmd[1]); //TODO global var 722 | break; 723 | case DBG: 724 | TOGGLE_VAR("debug", DEBUG, comd->cmd[1]); 725 | break; 726 | case EXIT: 727 | exit(EXIT_SUCCESS); 728 | break; 729 | case HIST: 730 | // check for the optional argument 731 | // nb-entries: print the number of hist entries in the current session 732 | if (comd->length == 2 && strcmp(comd->cmd[1], "--nb-entries") == 0) { 733 | printf("%d\n", nb_hist_entries); 734 | return EXIT_SUCCESS; 735 | break; 736 | } 737 | else 738 | CHK_ARGC("history", 0); 739 | 740 | HIST_ENTRY **hlist = history_list(); 741 | int i; 742 | if (hlist) 743 | for (i = 0; hlist[i]; i++) 744 | printf ("%s\n", hlist[i]->line); 745 | return EXIT_SUCCESS; 746 | break; 747 | case PROMPT: 748 | { 749 | // check for the optional dir length argument 750 | if (comd->length == 3) { 751 | MAX_DIR_LENGTH = abs(atoi(comd->cmd[2])); // will return 0 on non-integer 752 | printdebug("setting MAX_DIR_LENGTH to %d", MAX_DIR_LENGTH); 753 | } 754 | else 755 | CHK_ARGC("prompt", 1); 756 | 757 | free(user_prompt_string); 758 | char *newprompt = resolve_prompt_colors(comd->cmd[1]); 759 | printdebug("setting user_prompt_string to '%s'", newprompt); 760 | user_prompt_string = newprompt; 761 | return EXIT_SUCCESS; 762 | break; 763 | } 764 | case SHCAT: 765 | parsestream(stdin, "stdin", (void (*)(char*)) puts_verbatim); // built_in cat; mainly for testing purposes (redirecting stdin) 766 | return EXIT_SUCCESS; 767 | break; 768 | case UNALIAS: 769 | CHK_ARGC("unalias", 1); 770 | return unalias(comd->cmd[1]); 771 | break; 772 | case SRC: 773 | CHK_ARGC("source", 1); 774 | parsefile(comd->cmd[1], (void (*)(char*)) parse_from_file, true); // errormsg if file not found 775 | return EXIT_SUCCESS; 776 | break; 777 | default: 778 | printerr("parse_built_in: unrecognized built_in command: '%s' with index %d", *comd->cmd, index); 779 | exit(EXIT_FAILURE); 780 | } 781 | } 782 | 783 | /* 784 | * sig_int_handler: this function is called when the user enters ^C and 785 | * tells GNU readline to diplay a prompt on a newline 786 | */ 787 | void sig_int_handler(int signo) { 788 | // if ^C entered in child process --> also sent to parent (jsh) process 789 | // --> only clear the prompt when not waiting for an executing child (allow the waitpid to return) 790 | if (!WAITING_FOR_CHILD) { 791 | rl_crlf(); // set cursor to newline 792 | siglongjmp(ctrlc_buf, 1); // jump back to main loop 793 | } 794 | } 795 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | --------------------------------------------------------------------------------