├── test ├── examples │ ├── includes │ │ ├── one.conf │ │ ├── two.conf │ │ ├── five.conf │ │ ├── four.conf │ │ └── more │ │ │ └── three.conf │ ├── nginx-linter.config.json │ ├── simple.conf │ ├── location-order-with-includes.conf │ ├── newlines.conf │ ├── single-quotes.conf │ ├── location-order-includes │ │ ├── server-regex.conf │ │ └── server-equal.conf │ ├── nested-includes.conf │ ├── location-order.conf │ ├── strings.conf │ ├── headers.conf │ ├── strict-location.conf │ ├── lua.conf │ ├── if.conf │ ├── location-order-complicated.conf │ └── if-is-evil.conf ├── rules │ ├── rule-strict-location.spec.js │ ├── rule-trailing-whitespace.spec.js │ ├── rule-line-ending.spec.js │ ├── rule-indentation.spec.js │ ├── rule-if-is-evil.spec.js │ └── rule-location-order.spec.js ├── cli │ ├── options.spec.js │ └── commands.spec.js └── parser.spec.js ├── .gitignore ├── lib ├── index.js ├── rules │ ├── index.js │ ├── rule-trailing-whitespace.js │ ├── rule-line-ending.js │ ├── rule-strict-location.js │ ├── rule-if-is-evil.js │ ├── rule-location-order.js │ └── rule-indentation.js ├── parser │ ├── include-visitor.js │ ├── index.js │ └── parser.js ├── walker.js └── validator.js ├── bin ├── _cli │ ├── index.js │ ├── options.js │ └── commands.js └── nginx-linter.js ├── Dockerfile ├── etc ├── nginx-with-config.sh └── openresty-with-config.sh ├── package.json ├── .github └── workflows │ └── main.yml ├── .eslintrc.yml ├── README.md └── LICENSE /test/examples/includes/one.conf: -------------------------------------------------------------------------------- 1 | set $something 1; 2 | -------------------------------------------------------------------------------- /test/examples/includes/two.conf: -------------------------------------------------------------------------------- 1 | set $something 2; 2 | -------------------------------------------------------------------------------- /test/examples/includes/five.conf: -------------------------------------------------------------------------------- 1 | set $something 5; 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | .nyc_output/ 3 | coverage/ 4 | -------------------------------------------------------------------------------- /test/examples/includes/four.conf: -------------------------------------------------------------------------------- 1 | include more/three.conf; 2 | set $something 4; 3 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | let parser = require('./parser'); 2 | 3 | module.exports = { 4 | parser, 5 | }; 6 | -------------------------------------------------------------------------------- /bin/_cli/index.js: -------------------------------------------------------------------------------- 1 | let {main} = require('./commands'); 2 | 3 | module.exports = { 4 | main, 5 | }; 6 | -------------------------------------------------------------------------------- /test/examples/nginx-linter.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "severity": { 3 | "if-is-evil": "warn" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:12 2 | 3 | WORKDIR /usr/src/app 4 | 5 | COPY . /usr/src/app 6 | 7 | RUN npm install -g /usr/src/app 8 | 9 | CMD ["nginx-linter"] 10 | -------------------------------------------------------------------------------- /bin/nginx-linter.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | let cli = require('./_cli'); 4 | 5 | /*jshint noconsole:off */ 6 | process.exitCode = cli.main(process.argv.slice(2), console); 7 | -------------------------------------------------------------------------------- /test/examples/simple.conf: -------------------------------------------------------------------------------- 1 | events { 2 | } 3 | http { 4 | server { 5 | listen 80; 6 | location = /ok { 7 | return 200; 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /test/examples/location-order-with-includes.conf: -------------------------------------------------------------------------------- 1 | events { 2 | } 3 | http { 4 | include location-order-includes/server-regex.conf; 5 | include location-order-includes/server-equal.conf; 6 | } 7 | -------------------------------------------------------------------------------- /test/examples/newlines.conf: -------------------------------------------------------------------------------- 1 | events { 2 | } 3 | http { 4 | server { 5 | listen 80; 6 | location = /ok { 7 | return 200; 8 | } 9 | } 10 | } 11 | 12 | -------------------------------------------------------------------------------- /test/examples/single-quotes.conf: -------------------------------------------------------------------------------- 1 | events { 2 | } 3 | http { 4 | server { 5 | listen 80; 6 | location = '/o\'k' { 7 | return 200; 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /etc/nginx-with-config.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | docker run \ 4 | --name nginx-linter-test-container \ 5 | -v "`pwd`/$1:/etc/nginx/nginx.conf:ro" \ 6 | -p 8080:80 \ 7 | --rm \ 8 | nginx 9 | -------------------------------------------------------------------------------- /test/examples/location-order-includes/server-regex.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 80; 3 | add_header X-Header-2 ServerBlock; 4 | location ^~ /ordered/a/ca/a { 5 | return 201; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /test/examples/includes/more/three.conf: -------------------------------------------------------------------------------- 1 | set $something 3; 2 | 3 | if ($something) { 4 | # fastcgi_pass here 5 | proxy_pass http://127.0.0.1:8080/; 6 | } 7 | 8 | if ($something) { 9 | # no handler here 10 | } 11 | -------------------------------------------------------------------------------- /test/examples/nested-includes.conf: -------------------------------------------------------------------------------- 1 | events { 2 | } 3 | http { 4 | server { 5 | listen 80; 6 | location = /ok { 7 | include includes/*.conf; 8 | return 200; 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /etc/openresty-with-config.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | docker run \ 4 | --name nginx-linter-test-container \ 5 | -v "`pwd`/$1:/usr/local/openresty/nginx/conf/nginx.conf:ro" \ 6 | -p 8080:80 \ 7 | --rm \ 8 | openresty/openresty:stretch 9 | -------------------------------------------------------------------------------- /test/examples/location-order.conf: -------------------------------------------------------------------------------- 1 | events { 2 | } 3 | http { 4 | server { 5 | listen 80; 6 | location /ok { 7 | return 200; 8 | } 9 | location = /ok/blah { 10 | return 200; 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /test/examples/location-order-includes/server-equal.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 80; 3 | add_header X-Header-2 ServerBlock; 4 | location = /ok2 { 5 | add_header X-Header-1 LocationBlock; 6 | return 200; 7 | } 8 | location = /ok { 9 | return 200; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /test/examples/strings.conf: -------------------------------------------------------------------------------- 1 | http { 2 | map $request_uri $mapped_response_code { 3 | example.* 400; 4 | "{a}" 429; 5 | default 200; 6 | } 7 | 8 | server { 9 | listen 80; 10 | location = / { 11 | return $mapped_response_code; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /lib/rules/index.js: -------------------------------------------------------------------------------- 1 | let builtins = [ 2 | require('./rule-if-is-evil'), 3 | require('./rule-indentation'), 4 | require('./rule-line-ending'), 5 | require('./rule-location-order'), 6 | require('./rule-strict-location'), 7 | require('./rule-trailing-whitespace'), 8 | ]; 9 | 10 | module.exports = { 11 | builtins, 12 | }; 13 | -------------------------------------------------------------------------------- /test/examples/headers.conf: -------------------------------------------------------------------------------- 1 | events { 2 | } 3 | http { 4 | add_header X-Header-1 HttpBlock; 5 | server { 6 | listen 80; 7 | add_header X-Header-2 ServerBlock; 8 | location = /ok { 9 | return 200; 10 | } 11 | location = /ok2 { 12 | add_header X-Header-1 LocationBlock; 13 | return 200; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /test/examples/strict-location.conf: -------------------------------------------------------------------------------- 1 | events { 2 | } 3 | http { 4 | server { 5 | listen 80; 6 | # BAD! prefix location but specified regex 7 | location ^/books/([^/]+)/chapters$ { 8 | return 200; 9 | } 10 | # BAD! exact location but specified regex 11 | location = ^/books/([^/]+)$ { 12 | return 200; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /test/examples/lua.conf: -------------------------------------------------------------------------------- 1 | events { 2 | } 3 | http { 4 | server { 5 | listen 80; 6 | location = /ok { 7 | content_by_lua_block { 8 | local _M = {} 9 | function _M.go() 10 | -- } 11 | if ngx.req.get_body_data() then 12 | ngx.say("Got data") 13 | else 14 | ngx.say("No data") 15 | end 16 | end 17 | _M.go() 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /test/examples/if.conf: -------------------------------------------------------------------------------- 1 | http { 2 | server { 3 | listen 80; 4 | location = /ok { 5 | if ($http_user_agent ~ MSIE) { 6 | rewrite ^(.*)$ /msie/$1 break; 7 | } 8 | 9 | if ($http_cookie ~* "id=([^;]+)(?:;|$)") { 10 | set $id $1; 11 | } 12 | 13 | if ($request_method = POST) { 14 | return 405; 15 | } 16 | 17 | if ($slow) { 18 | limit_rate 10k; 19 | } 20 | 21 | if ($invalid_referer) { 22 | return 403; 23 | } 24 | 25 | return 200; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /lib/rules/rule-trailing-whitespace.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | name: 'trailing-whitespace', 3 | default: true, 4 | invoke: function(node, errors, ignored, state) { 5 | state = state || { whitespace: '' }; 6 | switch (node.type) { 7 | case 'newline': 8 | if (state.whitespace) { 9 | errors.push('Trailing whitespace found'); 10 | } 11 | break; 12 | case 'whitespace': 13 | state.whitespace = node.text; 14 | break; 15 | default: 16 | state.whitespace = ''; 17 | break; 18 | } 19 | return state; 20 | }, 21 | }; 22 | -------------------------------------------------------------------------------- /lib/rules/rule-line-ending.js: -------------------------------------------------------------------------------- 1 | function lineEnding(text) { 2 | switch (text) { 3 | case '\n': 4 | return 'lf'; 5 | case '\r\n': 6 | return 'crlf'; 7 | default: 8 | throw `Unknown line ending ${JSON.stringify(text)}`; 9 | } 10 | } 11 | 12 | module.exports = { 13 | name: 'line-ending', 14 | default: 'lf', 15 | invoke: function(node, errors, expectedType) { 16 | if (node.type === 'newline') { 17 | let actualType = lineEnding(node.text); 18 | if (expectedType !== actualType) { 19 | errors.push(`Expected ${expectedType}, found ${actualType}`); 20 | } 21 | } 22 | }, 23 | }; 24 | -------------------------------------------------------------------------------- /lib/parser/include-visitor.js: -------------------------------------------------------------------------------- 1 | let {walk} = require('../walker'); 2 | 3 | function visitIncludes(node, callback) { 4 | walk(node, (node, state) => { 5 | if (node.type === 'directive' && node.name === 'include') { 6 | state = {node: node, includeGlob: null}; 7 | } else if (node.type === 'parameter' && state && state.includeGlob == null) { 8 | state.includeGlob = node.text; 9 | } else if (node.type !== 'whitespace' && node.type !== 'comment') { 10 | if (node.type === 'punctuation' && node.text === ';' && state && state.includeGlob != null) { 11 | callback(state.node, state.includeGlob); 12 | } 13 | state = null; 14 | } 15 | return state; 16 | }, null); 17 | } 18 | 19 | module.exports = { 20 | visitIncludes, 21 | }; 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nginx-linter", 3 | "version": "0.7.0", 4 | "description": "A linter and formatter for Nginx configuration files", 5 | "bin": { 6 | "nginx-linter": "bin/nginx-linter.js" 7 | }, 8 | "main": "lib/index.js", 9 | "scripts": { 10 | "test": "npm-run-all test:*", 11 | "test:lint": "eslint bin lib test", 12 | "eslint:fix": "eslint --fix bin lib test", 13 | "test:unit": "nyc --reporter=html --reporter=text --reporter=lcov mocha test/*.spec.js test/**/*.spec.js" 14 | }, 15 | "keywords": [ 16 | "nginx", 17 | "linter" 18 | ], 19 | "author": "Jason Hinch", 20 | "license": "GPL-3.0-or-later", 21 | "repository": { 22 | "type": "git", 23 | "url": "https://github.com/jhinch/nginx-linter.git" 24 | }, 25 | "dependencies": { 26 | "chalk": "^2.4.1", 27 | "glob": "^7.1.3", 28 | "pegjs": "^0.10.0", 29 | "table": "^6.8.2" 30 | }, 31 | "devDependencies": { 32 | "coveralls": "^3.1.1", 33 | "eslint": "^8.1.0", 34 | "mocha": "^10.2.0", 35 | "npm-run-all": "^4.1.5", 36 | "nyc": "^15.1.0" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Build & Test 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | name: Build & Test using Node ${{ matrix.node-version }} on ${{ matrix.os }} 12 | runs-on: ${{ matrix.os }} 13 | 14 | strategy: 15 | matrix: 16 | os: [ubuntu-latest] 17 | node-version: [18.x, 20.x] 18 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 19 | 20 | steps: 21 | - uses: actions/checkout@v2 22 | - name: Use Node.js ${{ matrix.node-version }} 23 | uses: actions/setup-node@v2 24 | with: 25 | node-version: ${{ matrix.node-version }} 26 | - run: npm ci 27 | - run: npm test 28 | - name: Coveralls 29 | uses: coverallsapp/github-action@master 30 | with: 31 | github-token: ${{ secrets.GITHUB_TOKEN }} 32 | flag-name: ${{matrix.os}}-node-${{ matrix.node }} 33 | parallel: true 34 | finish: 35 | needs: build 36 | runs-on: ubuntu-latest 37 | steps: 38 | - name: Coveralls Finished 39 | uses: coverallsapp/github-action@master 40 | with: 41 | github-token: ${{ secrets.GITHUB_TOKEN }} 42 | parallel-finished: true 43 | -------------------------------------------------------------------------------- /lib/rules/rule-strict-location.js: -------------------------------------------------------------------------------- 1 | const REGEX_CHARS = '|()[]{^?*+\\'.split(''); 2 | 3 | function checkLocation(mode, locationMatch, errors) { 4 | switch (mode) { 5 | case '=': 6 | // falls through 7 | case '': 8 | if (REGEX_CHARS.filter(c => locationMatch.indexOf(c) !== -1).length) { 9 | errors.push(`Expected string when using${mode.length ? ' \'' + mode + '\' modifier in' : ''} 'location', got regular expression`); 10 | } 11 | break; 12 | } 13 | } 14 | 15 | module.exports = { 16 | name: 'strict-location', 17 | default: true, 18 | invoke: function(node, errors, ignored, state) { 19 | state = state || {}; 20 | if (node.type === 'directive' && node.name === 'location') { 21 | state.location = true; 22 | } else if (node.type === 'parameter') { 23 | if (state.location) { 24 | if (state.mode) { 25 | checkLocation(state.mode, node.text, errors); 26 | state = {}; 27 | } else { 28 | state.mode = node.text; 29 | } 30 | } 31 | } else if (node.type === 'punctuation' && node.text === '{') { 32 | if (state.location) { 33 | checkLocation('', state.mode, errors); 34 | state = {}; 35 | } 36 | } 37 | return state; 38 | }, 39 | }; 40 | -------------------------------------------------------------------------------- /.eslintrc.yml: -------------------------------------------------------------------------------- 1 | env: 2 | es6: true 3 | node: true 4 | extends: 'eslint:recommended' 5 | parserOptions: 6 | ecmaVersion: 2015 7 | rules: 8 | array-bracket-newline: 9 | - error 10 | - consistent 11 | array-bracket-spacing: 12 | - error 13 | array-callback-return: 14 | - error 15 | array-element-newline: 16 | - error 17 | - consistent 18 | brace-style: 19 | - error 20 | comma-dangle: 21 | - error 22 | - always-multiline 23 | comma-spacing: 24 | - error 25 | comma-style: 26 | - error 27 | complexity: 28 | - error 29 | consistent-return: 30 | - error 31 | curly: 32 | - error 33 | - multi-line 34 | - consistent 35 | dot-location: 36 | - error 37 | - property 38 | eqeqeq: 39 | - error 40 | - always 41 | - 'null': never 42 | func-call-spacing: 43 | - error 44 | indent: 45 | - error 46 | - 4 47 | - SwitchCase: 1 48 | keyword-spacing: 49 | - error 50 | linebreak-style: 51 | - error 52 | - unix 53 | no-path-concat: 54 | - error 55 | no-trailing-spaces: 56 | - error 57 | quotes: 58 | - error 59 | - single 60 | semi: 61 | - error 62 | - always 63 | space-before-blocks: 64 | - error 65 | space-before-function-paren: 66 | - error 67 | - never 68 | space-in-parens: 69 | - error 70 | space-infix-ops: 71 | - error 72 | yoda: 73 | - error 74 | overrides: 75 | - files: 76 | - test/*.js 77 | - test/**/*.js 78 | env: 79 | mocha: true 80 | -------------------------------------------------------------------------------- /lib/walker.js: -------------------------------------------------------------------------------- 1 | const defaults = { 2 | onNode: function(node, state) { 3 | return state; 4 | }, 5 | onFileStart: function(node, state) { 6 | return state; 7 | }, 8 | onFileEnd: function(node, state) { 9 | return state; 10 | }, 11 | }; 12 | 13 | function walk(node, callbacks, state) { 14 | if (typeof callbacks === 'function') { 15 | callbacks = {onNode: callbacks}; 16 | } 17 | callbacks = Object.assign({}, defaults, callbacks); 18 | return walkNode(node, callbacks, state); 19 | } 20 | 21 | function walkNode(node, callbacks, state) { 22 | if (Array.isArray(node)) { 23 | state = node.reduce((state, node) => walkNode(node, callbacks, state), state); 24 | } else if (node.type === 'file') { 25 | state = callbacks.onFileStart(node, state); 26 | state = walkNode(node.root, callbacks, state); 27 | state = callbacks.onFileEnd(node, state); 28 | } else { 29 | state = callbacks.onNode(node, state); 30 | if (node.type === 'directive') { 31 | state = walkNode(node.parameters, callbacks, state); 32 | state = walkNode(node.body, callbacks, state); 33 | if (node.includedFiles) { 34 | state = walkNode(node.includedFiles, callbacks, state); 35 | } 36 | } else if (node.type === 'lua:block') { 37 | state = walkNode(node.body, callbacks, state); 38 | } 39 | } 40 | return state; 41 | } 42 | 43 | module.exports = { 44 | walk, 45 | }; 46 | -------------------------------------------------------------------------------- /test/examples/location-order-complicated.conf: -------------------------------------------------------------------------------- 1 | events { 2 | } 3 | http { 4 | server { 5 | listen 80; 6 | location = /ordered/a/b { 7 | return 200; 8 | } 9 | location ^~ /ordered/a/ca/a { 10 | return 201; 11 | } 12 | location ^~ /ordered/a/ca { 13 | return 202; 14 | } 15 | location ^~ /ordered/a/d { 16 | return 203; 17 | } 18 | location ~ ^/ordered/a/c[a-z/]+$ { 19 | return 204; 20 | } 21 | location ~* ^/ordered/a/c[a-y/]+$ { 22 | return 205; 23 | } 24 | location /ordered/a/c { 25 | return 206; 26 | } 27 | location /ordered/a { 28 | return 207; 29 | } 30 | #nginxlinter location-order:off 31 | location /unordered/a { 32 | return 207; 33 | } 34 | location /unordered/a/c { 35 | return 206; 36 | } 37 | location ~* ^/unordered/a/c[a-y/]+$ { 38 | return 205; 39 | } 40 | location ~ ^/unordered/a/c[a-z/]+$ { 41 | return 204; 42 | } 43 | location ^~ /unordered/a/d { 44 | return 203; 45 | } 46 | location ^~ /unordered/a/ca { 47 | return 202; 48 | } 49 | location ^~ /unordered/a/ca/a { 50 | return 201; 51 | } 52 | location = /unordered/a/b { 53 | return 200; 54 | } 55 | #nginxlinter location-order:on 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /test/examples/if-is-evil.conf: -------------------------------------------------------------------------------- 1 | # https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/ 2 | 3 | events { 4 | } 5 | 6 | http { 7 | server { 8 | listen 80; 9 | 10 | location = /ok { 11 | if ($request_method = POST) { 12 | return 405; 13 | } 14 | return 200; 15 | } 16 | 17 | location = /p/ok-but-bad { 18 | #nginxlinter if-is-evil:always 19 | if ($request_method = POST) { 20 | return 405; 21 | } 22 | return 200; 23 | } 24 | 25 | location = /rewrite-from { 26 | if ($request_method = POST) { 27 | rewrite ^ /rewrite-to last; 28 | } 29 | return 200; 30 | } 31 | 32 | location = /rewrite-to { 33 | return 200; 34 | } 35 | 36 | location = /y/rewrite-bad-but-ok { 37 | if ($request_method = POST) { 38 | #nginxlinter if-is-evil:off 39 | rewrite ^ /rewrite-to break; 40 | } 41 | return 200; 42 | } 43 | 44 | location = /z/rewrite-bad { 45 | if ($request_method = POST) { 46 | rewrite ^ /rewrite-to break; 47 | } 48 | return 200; 49 | } 50 | 51 | location /crash { 52 | set $true 1; 53 | 54 | if ($true) { 55 | # fastcgi_pass here 56 | proxy_pass http://127.0.0.1:8080/; 57 | } 58 | 59 | if ($true) { 60 | # no handler here 61 | } 62 | } 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /lib/parser/index.js: -------------------------------------------------------------------------------- 1 | let parser = require('./parser'); 2 | let {visitIncludes} = require('./include-visitor'); 3 | let fs = require('fs'); 4 | let glob = require('glob'); 5 | let path = require('path'); 6 | 7 | function parse(contents) { 8 | return parser.parse(contents); 9 | } 10 | 11 | function parseFile(name) { 12 | let contents = fs.readFileSync(name, 'utf8'); 13 | try { 14 | let root = parse(contents); 15 | let node = { 16 | type: 'file', 17 | name, 18 | root, 19 | }; 20 | return node; 21 | } catch (e) { 22 | throw new Error(`Failed to parse: ${name}\nCaused by:\n${e}`); 23 | } 24 | } 25 | 26 | function parseFiles({includes, excludes, maxDepth}) { 27 | includes = includes || []; 28 | excludes = excludes || []; 29 | maxDepth = maxDepth || 0; 30 | let files = findFiles(includes, excludes); 31 | let nodes = files.map(parseFile); 32 | if (maxDepth > 0) { 33 | nodes.forEach(node => { 34 | let file = node.name; 35 | let effects = []; 36 | visitIncludes(node, (node, includeGlob) => { 37 | includeGlob = path.resolve(path.dirname(file), includeGlob); 38 | effects.push(() => { 39 | node.includedFiles = parseFiles({ 40 | includes: [includeGlob], 41 | excludes: excludes, 42 | maxDepth: maxDepth - 1, 43 | }); 44 | }); 45 | }); 46 | effects.forEach(effect => effect()); 47 | }); 48 | } 49 | return nodes; 50 | } 51 | 52 | function findFiles(includes, excludes) { 53 | let includedFiles = findMatchingFiles(includes); 54 | let excludedFiles = findMatchingFiles(excludes); 55 | return includedFiles.filter(f => excludedFiles.indexOf(f) === -1); 56 | } 57 | 58 | function findMatchingFiles(globs) { 59 | let files = []; 60 | globs.forEach(globString => glob.sync(globString).forEach(file => files.push(file))); 61 | return files; 62 | } 63 | 64 | module.exports = { 65 | parse, 66 | parseFile, 67 | parseFiles, 68 | }; 69 | -------------------------------------------------------------------------------- /bin/_cli/options.js: -------------------------------------------------------------------------------- 1 | const defaults = { 2 | command: 'validate', 3 | config: '~/.nginx-linter.json', 4 | includes: ['/etc/nginx/*.conf', '/etc/nginx/**/*.conf'], 5 | followIncludes: true, 6 | maxIncludeDepth: 5, 7 | excludes: [], 8 | }; 9 | 10 | function parse(args) { 11 | let options = JSON.parse(JSON.stringify(defaults)); 12 | let argsRemaining = args.slice(0); 13 | let customizedIncludes = false; 14 | let customizedExcludes = false; 15 | while (argsRemaining.length) { 16 | let headArg = argsRemaining.shift(); 17 | switch (headArg) { 18 | case '--config': 19 | if (!argsRemaining.length) { 20 | return 'Expected argument after --config'; 21 | } 22 | options.config = argsRemaining.shift(); 23 | break; 24 | case '--include': 25 | if (!argsRemaining.length) { 26 | return 'Expected argument after --include'; 27 | } 28 | if (customizedIncludes) { 29 | options.includes.push(argsRemaining.shift()); 30 | } else { 31 | options.includes = [argsRemaining.shift()]; 32 | customizedIncludes = true; 33 | } 34 | break; 35 | case '--exclude': 36 | if (!argsRemaining.length) { 37 | return 'Expected argument after --exclude'; 38 | } 39 | if (customizedExcludes) { 40 | options.excludes.push(argsRemaining.shift()); 41 | } else { 42 | options.excludes = [argsRemaining.shift()]; 43 | customizedExcludes = true; 44 | } 45 | break; 46 | case '--no-follow-includes': 47 | options.followIncludes = false; 48 | break; 49 | case '--help': 50 | options.command = 'help'; 51 | break; 52 | default: 53 | return `Unknown option: ${headArg}`; 54 | } 55 | } 56 | return options; 57 | } 58 | 59 | module.exports = { 60 | defaults, 61 | parse, 62 | }; 63 | -------------------------------------------------------------------------------- /test/rules/rule-strict-location.spec.js: -------------------------------------------------------------------------------- 1 | let assert = require('assert'); 2 | let fs = require('fs'); 3 | let path = require('path'); 4 | let parser = require('../../lib/parser'); 5 | let {runRules} = require('../../lib/validator'); 6 | let strictLocationRule = require('../../lib/rules/rule-strict-location'); 7 | 8 | function testConfig(name, contents, expectedErrors) { 9 | return { name, contents, expectedErrors }; 10 | } 11 | 12 | const TEST_CONFIGS = [ 13 | testConfig('prefix location', ` 14 | location / { 15 | return 204; 16 | } 17 | `, []), 18 | testConfig('prefix location with off', ` 19 | #nginxlinter off 20 | location /books/([^/]+) { 21 | return 204; 22 | } 23 | `, []), 24 | testConfig('prefix location with true', ` 25 | #nginxlinter strict-location:true 26 | location / { 27 | return 204; 28 | } 29 | `, []), 30 | testConfig('strict-location.conf', fs.readFileSync(path.resolve(__dirname, '..', 'examples', 'strict-location.conf'), 'utf8'), [ 31 | { 32 | rule: 'strict-location', 33 | type: 'error', 34 | text: 'Expected string when using \'location\', got regular expression', 35 | pos: { 36 | start: { column: 44, line: 7, offset: 144 }, 37 | end: { column: 45, line: 7, offset: 145 }, 38 | }, 39 | }, 40 | { 41 | rule: 'strict-location', 42 | type: 'error', 43 | text: 'Expected string when using \'=\' modifier in \'location\', got regular expression', 44 | pos: { 45 | start: { column: 20, line: 11, offset: 249 }, 46 | end: { column: 36, line: 11, offset: 265 }, 47 | }, 48 | }, 49 | ]), 50 | ]; 51 | 52 | describe('rules/if-is-evil', () => { 53 | describe('#invoke()', () => { 54 | TEST_CONFIGS.forEach(({name, contents, expectedErrors}) => { 55 | it(`should have ${expectedErrors.length ? 'errors' : 'no errors'} with ${name}`, () => { 56 | let parseTree = parser.parse(contents); 57 | let actualErrors = runRules(parseTree, [strictLocationRule]); 58 | assert.deepStrictEqual(actualErrors, expectedErrors); 59 | }); 60 | }); 61 | }); 62 | }); 63 | -------------------------------------------------------------------------------- /test/rules/rule-trailing-whitespace.spec.js: -------------------------------------------------------------------------------- 1 | let assert = require('assert'); 2 | let fs = require('fs'); 3 | let path = require('path'); 4 | let parser = require('../../lib/parser'); 5 | let {runRules} = require('../../lib/validator'); 6 | let trailingWhitespaceRule = require('../../lib/rules/rule-trailing-whitespace'); 7 | 8 | function testConfig(name, contents, expectedErrors) { 9 | return { name, contents, expectedErrors }; 10 | } 11 | 12 | const TEST_CONFIGS = [ 13 | testConfig('no trailing space', 'location / {\n # OK\n return 200;\n}', []), 14 | testConfig('trailing space', ' \nlocation / {\n # OK \n return 200; \n}', [ 15 | { 16 | rule: 'trailing-whitespace', 17 | text: 'Trailing whitespace found', 18 | type: 'error', 19 | pos: { 20 | start: { column: 3, line: 1, offset: 2 }, 21 | end: { column: 1, line: 2, offset: 3 }, 22 | }, 23 | }, 24 | { 25 | rule: 'trailing-whitespace', 26 | text: 'Trailing whitespace found', 27 | type: 'error', 28 | pos: { 29 | start: { column: 9, line: 3, offset: 24 }, 30 | end: { column: 1, line: 4, offset: 25 }, 31 | }, 32 | }, 33 | { 34 | rule: 'trailing-whitespace', 35 | text: 'Trailing whitespace found', 36 | type: 'error', 37 | pos: { 38 | start: { column: 15, line: 4, offset: 39 }, 39 | end: { column: 1, line: 5, offset: 40 }, 40 | }, 41 | }, 42 | ]), 43 | testConfig('simple.conf', fs.readFileSync(path.resolve(__dirname, '..', 'examples', 'simple.conf'), 'utf8'), []), 44 | testConfig('lua.conf', fs.readFileSync(path.resolve(__dirname, '..', 'examples', 'lua.conf'), 'utf8'), []), 45 | ]; 46 | 47 | describe('rules/trailing-whitespace', () => { 48 | describe('#invoke()', () => { 49 | TEST_CONFIGS.forEach(({name, contents, expectedErrors}) => { 50 | it(`should have ${expectedErrors.length ? 'errors' : 'no errors'} with ${name}`, () => { 51 | let parseTree = parser.parse(contents); 52 | let actualErrors = runRules(parseTree, [trailingWhitespaceRule], {}); 53 | assert.deepStrictEqual(actualErrors, expectedErrors); 54 | }); 55 | }); 56 | }); 57 | }); 58 | -------------------------------------------------------------------------------- /lib/rules/rule-if-is-evil.js: -------------------------------------------------------------------------------- 1 | 2 | function invoke(node, errors, mode, state) { 3 | switch (mode) { 4 | case 'always': 5 | return invokeWhenAlways(node, errors); 6 | case 'mostly': 7 | return invokeWhenMostly(node, errors, state); 8 | default: 9 | throw `Unknown if-is-evil mode ${mode}`; 10 | } 11 | } 12 | 13 | function invokeWhenAlways(node, errors) { 14 | if (node.type === 'directive' && node.name === 'if') { 15 | errors.push('if is evil and not allowed'); 16 | } 17 | } 18 | 19 | function invokeWhenMostly(node, errors, stack) { 20 | stack = stack || []; 21 | switch (node.type) { 22 | case 'directive': 23 | if (stack.length) { 24 | stack[0] = checkDirective(node, errors, stack[0]); 25 | } 26 | if (node.name === 'if') { 27 | stack.unshift({ directiveCount: 0 }); 28 | } 29 | break; 30 | case 'parameter': 31 | if (stack.length) { 32 | stack[0] = checkParameter(node, errors, stack[0]); 33 | } 34 | break; 35 | case 'punctuation': 36 | if (stack.length) { 37 | if (node.text === '}') { 38 | stack.shift(); 39 | } else if (node.text === ';') { 40 | if (stack[0].inRewrite) { 41 | stack[0].inRewrite = false; 42 | stack[0].rewriteParameterCount = 0; 43 | } 44 | } 45 | } 46 | break; 47 | } 48 | return stack; 49 | } 50 | 51 | function checkDirective(directiveNode, errors, state) { 52 | state.directiveCount++; 53 | if (state.directiveCount > 1) { 54 | errors.push('\'if\' must only contain a single directive'); 55 | } 56 | if (directiveNode.name === 'rewrite') { 57 | state.inRewrite = true; 58 | state.rewriteParameterCount = 0; 59 | } else if (directiveNode.name !== 'return') { 60 | errors.push(`Only a 'rewrite' or 'return' is allowed within an 'if', found '${directiveNode.name}'`); 61 | } 62 | return state; 63 | } 64 | 65 | function checkParameter(parameterNode, errors, state) { 66 | if (state.inRewrite) { 67 | state.rewriteParameterCount++; 68 | if (state.rewriteParameterCount === 3) { 69 | if (parameterNode.text !== 'last') { 70 | errors.push(`A 'rewrite' within an 'if' must use the 'last' flag, found '${parameterNode.text}'`); 71 | } 72 | } 73 | } 74 | return state; 75 | } 76 | 77 | module.exports = { 78 | name: 'if-is-evil', 79 | default: 'mostly', 80 | invoke, 81 | }; 82 | -------------------------------------------------------------------------------- /test/cli/options.spec.js: -------------------------------------------------------------------------------- 1 | let assert = require('assert'); 2 | let options = require('../../bin/_cli/options'); 3 | 4 | function optionsWithFields(overrides) { 5 | return Object.assign({}, options.defaults, overrides); 6 | } 7 | 8 | describe('cli/options', () => { 9 | describe('#parse()', () => { 10 | it('no arguments', () => { 11 | assert.deepStrictEqual(options.parse([]), options.defaults); 12 | }); 13 | it('bad argument', () => { 14 | assert.deepStrictEqual(options.parse(['--badarg']), 'Unknown option: --badarg'); 15 | }); 16 | it('--config without argument', () => { 17 | assert.deepStrictEqual(options.parse(['--config']), 'Expected argument after --config'); 18 | }); 19 | it('--config with argument', () => { 20 | let defaultConfig = options.defaults.config; 21 | assert.deepStrictEqual(options.parse(['--config', 'custom-config.json']), optionsWithFields({ config: 'custom-config.json' })); 22 | assert.deepStrictEqual(options.defaults.config, defaultConfig); 23 | }); 24 | it('--config with multiple arguments', () => { 25 | let defaultConfig = options.defaults.config; 26 | assert.deepStrictEqual(options.parse(['--config', 'custom-config.json', '--config', 'custom-2.json']), optionsWithFields({ config: 'custom-2.json' })); 27 | assert.deepStrictEqual(options.defaults.config, defaultConfig); 28 | }); 29 | it('--include without argument', () => { 30 | assert.deepStrictEqual(options.parse(['--include']), 'Expected argument after --include'); 31 | }); 32 | it('--include with argument', () => { 33 | let defaultIncludes = options.defaults.includes.slice(0); 34 | assert.deepStrictEqual(options.parse(['--include', 'nginx.conf']), optionsWithFields({ includes: ['nginx.conf'] })); 35 | assert.deepStrictEqual(options.defaults.includes, defaultIncludes); 36 | }); 37 | it('--include with multiple arguments', () => { 38 | let defaultIncludes = options.defaults.includes.slice(0); 39 | assert.deepStrictEqual(options.parse(['--include', 'nginx.conf', '--include', 'other.conf']), optionsWithFields({ includes: ['nginx.conf', 'other.conf'] })); 40 | assert.deepStrictEqual(options.defaults.includes, defaultIncludes); 41 | }); 42 | it('--exclude without argument', () => { 43 | assert.deepStrictEqual(options.parse(['--exclude']), 'Expected argument after --exclude'); 44 | }); 45 | it('--exclude with argument', () => { 46 | let defaultExcludes = options.defaults.excludes.slice(0); 47 | assert.deepStrictEqual(options.parse(['--exclude', 'nginx.conf']), optionsWithFields({ excludes: ['nginx.conf'] })); 48 | assert.deepStrictEqual(options.defaults.excludes, defaultExcludes); 49 | }); 50 | it('--exclude with multiple arguments', () => { 51 | let defaultExcludes = options.defaults.excludes.slice(0); 52 | assert.deepStrictEqual(options.parse(['--exclude', 'nginx.conf', '--exclude', 'other.conf']), optionsWithFields({ excludes: ['nginx.conf', 'other.conf'] })); 53 | assert.deepStrictEqual(options.defaults.excludes, defaultExcludes); 54 | }); 55 | }); 56 | }); 57 | -------------------------------------------------------------------------------- /test/rules/rule-line-ending.spec.js: -------------------------------------------------------------------------------- 1 | let assert = require('assert'); 2 | let fs = require('fs'); 3 | let path = require('path'); 4 | let parser = require('../../lib/parser'); 5 | let {runRules} = require('../../lib/validator'); 6 | let lineEndingRule = require('../../lib/rules/rule-line-ending'); 7 | 8 | function testConfig(name, lineEnding, contents, expectedErrors) { 9 | return { name, lineEnding, contents, expectedErrors }; 10 | } 11 | 12 | const TEST_CONFIGS = [ 13 | testConfig('simple lf', 'lf', 'location /no-content {\n return 204;\n}\n', []), 14 | testConfig('simple lf with error', 'lf', 'location /no-content {\r\n return 204;\n}\r\n', [ 15 | { 16 | rule: 'line-ending', 17 | text: 'Expected lf, found crlf', 18 | type: 'error', 19 | pos: { 20 | start: { column: 23, line: 1, offset: 22 }, 21 | end: { column: 1, line: 2, offset: 24 }, 22 | }, 23 | }, 24 | { 25 | rule: 'line-ending', 26 | text: 'Expected lf, found crlf', 27 | type: 'error', 28 | pos: { 29 | start: { column: 2, line: 3, offset: 41 }, 30 | end: { column: 1, line: 4, offset: 43 }, 31 | }, 32 | }, 33 | ]), 34 | testConfig('simple crlf', 'crlf', 'location /no-content {\r\n return 204;\r\n}\r\n', []), 35 | testConfig('simple crlf with error', 'crlf', 'location /no-content {\r\n return 204;\n}\r\n', [ 36 | { 37 | rule: 'line-ending', 38 | text: 'Expected crlf, found lf', 39 | type: 'error', 40 | pos: { 41 | start: { column: 16, line: 2, offset: 39 }, 42 | end: { column: 1, line: 3, offset: 40 }, 43 | }, 44 | }, 45 | ]), 46 | testConfig('newlines.conf', 'lf', fs.readFileSync(path.resolve(__dirname, '..', 'examples', 'newlines.conf'), 'utf8'), [ 47 | { 48 | rule: 'line-ending', 49 | text: 'Expected lf, found crlf', 50 | type: 'error', 51 | pos: { 52 | start: { column: 2, line: 2, offset: 10 }, 53 | end: { column: 1, line: 3, offset: 12 }, 54 | }, 55 | }, 56 | { 57 | rule: 'line-ending', 58 | text: 'Expected lf, found crlf', 59 | type: 'error', 60 | pos: { 61 | start: { column: 13, line: 4, offset: 31 }, 62 | end: { column: 1, line: 5, offset: 33 }, 63 | }, 64 | }, 65 | { 66 | rule: 'line-ending', 67 | text: 'Expected lf, found crlf', 68 | type: 'error', 69 | pos: { 70 | start: { column: 24, line: 7, offset: 100 }, 71 | end: { column: 1, line: 8, offset: 102 }, 72 | }, 73 | }, 74 | ]), 75 | ]; 76 | 77 | describe('rules/line-ending', () => { 78 | describe('#invoke()', () => { 79 | TEST_CONFIGS.forEach(({name, lineEnding, contents, expectedErrors}) => { 80 | it(`should have ${expectedErrors.length ? 'errors' : 'no errors'} with ${name}`, () => { 81 | let parseTree = parser.parse(contents); 82 | let actualErrors = runRules(parseTree, [lineEndingRule], {'line-ending': lineEnding}); 83 | assert.deepStrictEqual(actualErrors, expectedErrors); 84 | }); 85 | }); 86 | }); 87 | }); 88 | -------------------------------------------------------------------------------- /test/rules/rule-indentation.spec.js: -------------------------------------------------------------------------------- 1 | let assert = require('assert'); 2 | let fs = require('fs'); 3 | let path = require('path'); 4 | let parser = require('../../lib/parser'); 5 | let {runRules} = require('../../lib/validator'); 6 | let indentationRule = require('../../lib/rules/rule-indentation'); 7 | 8 | function testConfig(name, setting, contents, expectedErrors) { 9 | return { name, setting, contents, expectedErrors }; 10 | } 11 | 12 | const TEST_CONFIGS = [ 13 | testConfig('simple indentation', 4, ` 14 | location / { 15 | error_page 418 = @other; 16 | recursive_error_pages on; 17 | 18 | # if is normally evil, but I know what I'm doing 19 | if ($something) { 20 | return 418; 21 | } 22 | }`, []), 23 | testConfig('2 spaces', 2, 'location / {\n # OK\n return 200;\n}', []), 24 | testConfig('4 spaces instead of 2', 2, 'location / {\n return 200;\n}', [ 25 | { 26 | rule: 'indentation', 27 | text: 'Expected 2 spaces, found 4 spaces', 28 | type: 'error', 29 | pos: { 30 | start: { column: 5, line: 2, offset: 17 }, 31 | end: { column: 16, line: 2, offset: 28 }, 32 | }, 33 | }, 34 | ]), 35 | testConfig('4 spaces instead of 2 but with override', 2, 'location / {#nginxlinter indentation:4\n return 200;\n}', []), 36 | testConfig('4 spaces', 4, 'location / {\n # OK\n return 200;\n}', []), 37 | testConfig('2 spaces instead of 4', 4, 'location / {\n return 200;\n}', [ 38 | { 39 | rule: 'indentation', 40 | text: 'Expected 4 spaces, found 2 spaces', 41 | type: 'error', 42 | pos: { 43 | start: { column: 3, line: 2, offset: 15 }, 44 | end: { column: 14, line: 2, offset: 26 }, 45 | }, 46 | }, 47 | ]), 48 | testConfig('tabs', 'tab', 'location / {\n\t# OK\n\treturn 200;\n}', []), 49 | testConfig('2 spaces instead of tabs', 'tab', 'location / {\n return 200;\n}', [ 50 | { 51 | rule: 'indentation', 52 | text: 'Expected 1 tab, found 2 spaces', 53 | type: 'error', 54 | pos: { 55 | start: { column: 3, line: 2, offset: 15 }, 56 | end: { column: 14, line: 2, offset: 26 }, 57 | }, 58 | }, 59 | ]), 60 | testConfig('2 spaces instead of tabs', 'tab', 'location / {\n \treturn 200;\n}', [ 61 | { 62 | rule: 'indentation', 63 | text: 'Expected 1 tab, found mixed', 64 | type: 'error', 65 | pos: { 66 | start: { column: 3, line: 2, offset: 15 }, 67 | end: { column: 14, line: 2, offset: 26 }, 68 | }, 69 | }, 70 | ]), 71 | testConfig('simple.conf', 4, fs.readFileSync(path.resolve(__dirname, '..', 'examples', 'simple.conf'), 'utf8'), []), 72 | testConfig('lua.conf', 4, fs.readFileSync(path.resolve(__dirname, '..', 'examples', 'lua.conf'), 'utf8'), []), 73 | ]; 74 | 75 | describe('rules/indentation', () => { 76 | describe('#invoke()', () => { 77 | TEST_CONFIGS.forEach(({name, setting, contents, expectedErrors}) => { 78 | it(`should have ${expectedErrors.length ? 'errors' : 'no errors'} with ${name}`, () => { 79 | let parseTree = parser.parse(contents); 80 | let actualErrors = runRules(parseTree, [indentationRule], {'indentation': setting}); 81 | assert.deepStrictEqual(actualErrors, expectedErrors); 82 | }); 83 | }); 84 | }); 85 | }); 86 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![NPM version][npm-image]][npm-url] 2 | [![build status][github-actions-image]][github-actions-url] 3 | [![Code coverage][coveralls-image]][coveralls-url] 4 | 5 | # nginx-linter 6 | 7 | A command line tool for validating nginx files for style and common pitfalls. 8 | 9 | ## Installation 10 | 11 | ### Requirements 12 | 13 | * Node 18+ 14 | 15 | ### Instructions 16 | 17 | You can install nginx-linter globally using: 18 | 19 | npm install -g nginx-linter 20 | 21 | ## User Guide 22 | 23 | You can run nginx-linter without any configurations like so: 24 | 25 | nginx-linter 26 | 27 | This will by default validate the configuration files under `/etc/nginx/`. 28 | For all the options, you can use the `--help`: 29 | 30 | nginx-linter --help 31 | 32 | ### Built-in rules 33 | 34 | There are a number of built in rules in nginx-linter designed both keep 35 | your nginx configuration style consist but also to find common pitfalls 36 | which may cause bugs in production. 37 | 38 | #### `if-is-evil` 39 | 40 | The `if` directive has a number of [common pitfalls](https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/) due to nginx configuration 41 | being a declarative language not a procedural one and as a result should 42 | either be used sparingly or not at all. There are two modes for this rule 43 | which can be used: 44 | 45 | * **always** - Don't allow any uses of the `if` directive regardless if they are a safe to use 46 | * **mostly** - Only allow uses of the `if` directive which are documented as safe to use 47 | 48 | Default value: **mostly** 49 | 50 | #### `indentation` 51 | 52 | Enforces a consistent indentation for all directive blocks and lua blocks. If the configuration value 53 | is a digit, it indicates the number of spaces to use for each level of indentation. Alternatively, 54 | you can use `tab` as the value to use tabs for indentation. 55 | 56 | Default value: **4** 57 | 58 | #### `line-ending` 59 | 60 | Enforce a consistent line ending within the file. The configuration value can either be `lf` for 61 | Unix/Linux/MacOS style newlines or `crlf` for Windows style newlines. 62 | 63 | Default value: **lf** 64 | 65 | #### `location-order` 66 | 67 | This rules enforces that locations are ordered in the same order in which they will would take 68 | precedence when matching requests. A common pitfall is thinking that Nginx configuration is 69 | matched sequentially which [isn't the case](https://nginx.org/en/docs/http/ngx_http_core_module.html#location). By 70 | enforcing that locations are ordered in precedence order, this will lead to less surprising results in production. 71 | 72 | #### `strict-location` 73 | 74 | `location` directives have a number of modifiers which can be used change the way the location 75 | matches. As these are special symbols it can be difficult for a novice to remember which modes 76 | allow for regular expressions and which ones are regular string comparisons. `strict-location` 77 | checks that prefix and exact matches don't use regular expressions in the location URI. 78 | 79 | #### `trailing-whitespace` 80 | 81 | Enforce that no line ends with whitespace. This rule is largely for cleanliness and style purposes. 82 | 83 | [npm-image]: https://img.shields.io/npm/v/nginx-linter.svg?style=flat-square 84 | [npm-url]: https://www.npmjs.com/package/nginx-linter 85 | [github-actions-image]: https://github.com/jhinch/nginx-linter/actions/workflows/main.yml/badge.svg 86 | [github-actions-url]: https://github.com/jhinch/nginx-linter/actions/workflows/main.yml 87 | [coveralls-image]: https://img.shields.io/coveralls/jhinch/nginx-linter/master.svg?style=flat-square 88 | [coveralls-url]: https://coveralls.io/r/jhinch/nginx-linter?branch=master 89 | -------------------------------------------------------------------------------- /test/rules/rule-if-is-evil.spec.js: -------------------------------------------------------------------------------- 1 | let assert = require('assert'); 2 | let fs = require('fs'); 3 | let path = require('path'); 4 | let parser = require('../../lib/parser'); 5 | let {runRules} = require('../../lib/validator'); 6 | let ifIsEvilRule = require('../../lib/rules/rule-if-is-evil'); 7 | 8 | function testConfig(name, mode, contents, expectedErrors) { 9 | return { name, mode, contents, expectedErrors }; 10 | } 11 | 12 | const TEST_CONFIGS = [ 13 | testConfig('simple if with return', 'mostly', ` 14 | location / { 15 | if ($something) { 16 | return 418; 17 | } 18 | return 200; 19 | }`, []), 20 | testConfig('simple if with return but with always', 'always', ` 21 | location / { 22 | if ($something) { 23 | return 418; 24 | } 25 | return 200; 26 | }`, [ 27 | { 28 | rule: 'if-is-evil', 29 | text: 'if is evil and not allowed', 30 | type: 'error', 31 | pos: { 32 | start: { column: 5, line: 3, offset: 18 }, 33 | end: { column: 6, line: 5, offset: 61 }, 34 | }, 35 | }, 36 | ]), 37 | testConfig('simple if with return with always with comment', 'always', ` 38 | location / { 39 | #nginxlinter if-is-evil:mostly 40 | if ($something) { 41 | return 418; 42 | } 43 | return 200; 44 | }`, []), 45 | testConfig('if with valid directives but more than one', 'mostly', ` 46 | location / { 47 | if ($something) { 48 | rewrite ^ /other last; 49 | return 418; 50 | } 51 | return 200; 52 | }`, [ 53 | { 54 | rule: 'if-is-evil', 55 | text: '\'if\' must only contain a single directive', 56 | type: 'error', 57 | pos: { 58 | start: { column: 9, line: 5, offset: 75 }, 59 | end: { column: 20, line: 5, offset: 86 }, 60 | }, 61 | }, 62 | ]), 63 | testConfig('if-is-evil.conf file', 'mostly', fs.readFileSync(path.resolve(__dirname, '..', 'examples', 'if-is-evil.conf'), 'utf8'), [ 64 | { 65 | rule: 'if-is-evil', 66 | type: 'error', 67 | text: 'if is evil and not allowed', 68 | pos: { 69 | start: { column: 13, line: 19, offset: 355 }, 70 | end: { column: 14, line: 21, offset: 426 }, 71 | }, 72 | }, 73 | { 74 | rule: 'if-is-evil', 75 | type: 'error', 76 | text: 'A \'rewrite\' within an \'if\' must use the \'last\' flag, found \'break\'', 77 | pos: { 78 | start: { column: 39, line: 46, offset: 1039 }, 79 | end: { column: 44, line: 46, offset: 1044 }, 80 | }, 81 | }, 82 | { 83 | rule: 'if-is-evil', 84 | type: 'error', 85 | text: 'Only a \'rewrite\' or \'return\' is allowed within an \'if\', found \'proxy_pass\'', 86 | pos: { 87 | start: { column: 17, line: 56, offset: 1224 }, 88 | end: { column: 51, line: 56, offset: 1258 }, 89 | }, 90 | }, 91 | ]), 92 | ]; 93 | 94 | describe('rules/if-is-evil', () => { 95 | describe('#invoke()', () => { 96 | TEST_CONFIGS.forEach(({name, mode, contents, expectedErrors}) => { 97 | it(`should have ${expectedErrors.length ? 'errors' : 'no errors'} with ${name}`, () => { 98 | let parseTree = parser.parse(contents); 99 | let actualErrors = runRules(parseTree, [ifIsEvilRule], {'if-is-evil': mode}); 100 | assert.deepStrictEqual(actualErrors, expectedErrors); 101 | }); 102 | }); 103 | }); 104 | }); 105 | -------------------------------------------------------------------------------- /lib/rules/rule-location-order.js: -------------------------------------------------------------------------------- 1 | 2 | function checkLocation(currentLocation, previousLocation, errors) { 3 | if (previousLocation) { 4 | switch (currentLocation.mode) { 5 | case '=': 6 | if (previousLocation.mode === '=') { 7 | if (!isLexographicalWithLongestPrefix(previousLocation.uri, currentLocation.uri)) { 8 | errors.push('Expected \'=\' location directives to be in lexicographical order with longest prefix'); 9 | } 10 | } else { 11 | errors.push(`Expected '=' location directives to be ordered before '${previousLocation.mode}'`); 12 | } 13 | break; 14 | case '^~': 15 | if (previousLocation.mode !== '=') { 16 | if (previousLocation.mode === '^~') { 17 | if (!isLexographicalWithLongestPrefix(previousLocation.uri, currentLocation.uri)) { 18 | errors.push('Expected \'^~\' location directives to be in lexicographical order with longest prefix'); 19 | } 20 | } else { 21 | errors.push(`Expected '^~' location directives to be ordered before '${previousLocation.mode}'`); 22 | } 23 | } 24 | break; 25 | case '~': 26 | // fall through 27 | case '~*': 28 | if (previousLocation.mode !== '=' && previousLocation.mode !== '^~') { 29 | if (previousLocation.mode !== '~' && previousLocation.mode !== '~*') { 30 | errors.push(`Expected '${currentLocation.mode}' location directives to be ordered before '${previousLocation.mode}'`); 31 | } 32 | } 33 | break; 34 | case '': 35 | if (previousLocation.mode === '') { 36 | if (!isLexographicalWithLongestPrefix(previousLocation.uri, currentLocation.uri)) { 37 | errors.push('Expected prefix location directives to be in lexicographical order with longest prefix'); 38 | } 39 | } 40 | } 41 | } 42 | } 43 | 44 | function isLexographicalWithLongestPrefix(a, b) { 45 | if (a.startsWith(b)) { 46 | return true; 47 | } else if (b.startsWith(a)) { 48 | return false; 49 | } else { 50 | return a < b; 51 | } 52 | } 53 | 54 | function invoke(node, errors, ignored, stack) { 55 | stack = stack || [{}]; 56 | let state = stack[0]; 57 | switch (node.type) { 58 | case 'directive': 59 | if (node.name === 'location') { 60 | state.previous = state.current; 61 | state.current = {}; 62 | state.location = true; 63 | } 64 | break; 65 | case 'parameter': 66 | if (state.location) { 67 | if (state.current.mode) { 68 | state.current.uri = node.text; 69 | } else { 70 | state.current.mode = node.text; 71 | } 72 | } 73 | break; 74 | case 'punctuation': 75 | if (node.text === '{') { 76 | if (state.location) { 77 | if (state.current.uri == null) { 78 | state.current.uri = state.current.mode; 79 | state.current.mode = ''; 80 | } 81 | state.location = false; 82 | checkLocation(state.current, state.previous, errors); 83 | } 84 | stack.unshift({}); 85 | } else if (node.text === '}') { 86 | stack.shift(); 87 | } 88 | break; 89 | } 90 | return stack; 91 | } 92 | 93 | module.exports = { 94 | name: 'location-order', 95 | default: true, 96 | invoke, 97 | }; 98 | -------------------------------------------------------------------------------- /lib/validator.js: -------------------------------------------------------------------------------- 1 | 2 | let {walk} = require('./walker'); 3 | 4 | function defaults(rules) { 5 | let result = {severity:{}}; 6 | rules.forEach(rule => { 7 | result[rule.name] = rule.default; 8 | result.severity[rule.name] = rule.severity; 9 | }); 10 | return result; 11 | } 12 | 13 | function parseOption(value) { 14 | if (value === 'off' || value === 'false') { 15 | return false; 16 | } else if (value === 'on' || value === 'true') { 17 | return true; 18 | } else if (value.match(/^[a-zA-Z]+$/)) { 19 | return value; 20 | } else { 21 | return JSON.parse(value); 22 | } 23 | } 24 | 25 | function runRules(root, rules, options) { 26 | let defaultOptions = Object.assign({}, defaults(rules), options || {}); 27 | options = Object.assign({}, defaultOptions); 28 | let {resultsStack} = walk(root, { 29 | onFileStart: runRulesOnFileStart, 30 | onNode: runRulesOnNode, 31 | onFileEnd: runRulesOnFileEnd, 32 | }, { 33 | rules, 34 | resultsStack: [[]], 35 | defaultOptions: defaultOptions, 36 | optionsStack: [options], 37 | state: {}, 38 | }); 39 | let results = resultsStack[0]; 40 | if (root.type === 'file' && results.length === 1) { 41 | results = results[0].nested.results; 42 | } 43 | return results; 44 | } 45 | 46 | function runRulesOnFileStart(node, {rules, resultsStack, defaultOptions, optionsStack, state}) { 47 | resultsStack.unshift([]); 48 | optionsStack.unshift(Object.assign({}, defaultOptions)); 49 | rules.forEach(rule => { 50 | if (rule.onFileStart) { 51 | state[rule.name] = rule.onFileStart(state[rule.name]); 52 | } 53 | }); 54 | return {rules, resultsStack, defaultOptions, optionsStack, state}; 55 | } 56 | 57 | function runRulesOnFileEnd(node, {rules, resultsStack, defaultOptions, optionsStack, state}) { 58 | rules.forEach(rule => { 59 | if (rule.onFileStart) { 60 | state[rule.name] = rule.onFileEnd(state[rule.name]); 61 | } 62 | }); 63 | optionsStack.shift(); 64 | let results = resultsStack.shift(); 65 | if (results.length) { 66 | resultsStack[0].push({ 67 | nested: { 68 | fileName: node.name, 69 | results, 70 | }, 71 | }); 72 | } 73 | return {rules, resultsStack, defaultOptions, optionsStack, state}; 74 | } 75 | 76 | function runRulesOnNode(node, {rules, resultsStack, defaultOptions, optionsStack, state}) { 77 | let results = resultsStack[0]; 78 | if (node.type === 'punctuation') { 79 | if (node.text === '{') { 80 | optionsStack.unshift(Object.assign({}, optionsStack[0])); 81 | } else if (node.text === '}') { 82 | optionsStack.shift(); 83 | } 84 | } 85 | let options = optionsStack[0]; 86 | if (node.type === 'comment') { 87 | if (node.text.startsWith('#nginxlinter ')) { 88 | if (node.text === '#nginxlinter off') { 89 | options = null; 90 | } else { 91 | node.text.split(' ').slice(1).forEach(part => { 92 | let [key, value] = part.split(':', 2); 93 | options[key] = parseOption(value); 94 | }); 95 | } 96 | optionsStack[0] = options; 97 | } 98 | } 99 | 100 | if (options) { 101 | rules.forEach(rule => { 102 | if (options[rule.name]) { 103 | let severity = options.severity[rule.name] || 'error'; 104 | let messages = []; 105 | state[rule.name] = rule.invoke( 106 | node, 107 | messages, 108 | options[rule.name], 109 | state[rule.name] 110 | ); 111 | if (messages.length) { 112 | messages.map(message => { 113 | return { 114 | pos: node.pos, 115 | rule: rule.name, 116 | type: severity, 117 | text: message, 118 | }; 119 | }).forEach(result => results.push(result)); 120 | } 121 | } 122 | }); 123 | } 124 | 125 | return {rules, resultsStack, defaultOptions, optionsStack, state}; 126 | } 127 | 128 | module.exports = { 129 | defaults, 130 | runRules, 131 | }; 132 | -------------------------------------------------------------------------------- /test/cli/commands.spec.js: -------------------------------------------------------------------------------- 1 | let assert = require('assert'); 2 | let path = require('path'); 3 | let {main} = require('../../bin/_cli/commands'); 4 | 5 | let stubConsole = new Proxy({}, { 6 | get: (target, prop) => { 7 | if (prop === 'invocations') { 8 | return target; 9 | } else if (Array.isArray(target[prop])) { 10 | // This cannot be an arrow function as 11 | // 'arguments' can not be referenced in them 12 | return function() { 13 | target[prop].push(Array.from(arguments)); 14 | }; 15 | } else { 16 | return undefined; 17 | } 18 | }, 19 | }); 20 | 21 | describe('cli/commands', () => { 22 | beforeEach(() => { 23 | stubConsole.invocations.log = []; 24 | }); 25 | describe('#main()', () => { 26 | it('--help', () => { 27 | let exitCode = main(['--help'], stubConsole); 28 | assert.strictEqual(exitCode, 0); 29 | }); 30 | it('bad argument', () => { 31 | let exitCode = main(['--badarg'], stubConsole); 32 | assert.strictEqual(exitCode, 1); 33 | }); 34 | it('simple.conf', () => { 35 | let exitCode = main(['--include', path.resolve(__dirname, '..', 'examples', 'simple.conf')], stubConsole); 36 | assert.strictEqual(exitCode, 0); 37 | let message = stubConsole.invocations.log[stubConsole.invocations.log.length - 1]; 38 | assert.ok(/Validation succeeded!.*Files: 1, Errors: 0$/.test(message), `Expected success summary, got '${message}'`); 39 | }); 40 | it('if-is-evil.conf', () => { 41 | let exitCode = main(['--include', path.resolve(__dirname, '..', 'examples', 'if-is-evil.conf')], stubConsole); 42 | assert.strictEqual(exitCode, 1); 43 | let message = stubConsole.invocations.log[stubConsole.invocations.log.length - 1]; 44 | assert.ok(/Validation failed!.*Files: 1, Errors: 3$/.test(message), `Expected success summary, got '${message}'`); 45 | }); 46 | it('nested-includes.conf', () => { 47 | let exitCode = main(['--include', path.resolve(__dirname, '..', 'examples', 'nested-includes.conf')], stubConsole); 48 | assert.strictEqual(exitCode, 1); 49 | let message = stubConsole.invocations.log[stubConsole.invocations.log.length - 1]; 50 | assert.ok(/Validation failed!.*Files: 1, Errors: 1$/.test(message), `Expected success summary, got '${message}'`); 51 | }); 52 | it('nested-includes.conf with no follow', () => { 53 | let exitCode = main(['--include', path.resolve(__dirname, '..', 'examples', 'nested-includes.conf'), '--no-follow-includes'], stubConsole); 54 | assert.strictEqual(exitCode, 0); 55 | let message = stubConsole.invocations.log[stubConsole.invocations.log.length - 1]; 56 | assert.ok(/Validation succeeded!.*Files: 1, Errors: 0$/.test(message), `Expected success summary, got '${message}'`); 57 | }); 58 | it('nested-includes.conf with config override', () => { 59 | let exitCode = main([ 60 | '--include', 61 | path.resolve(__dirname, '..', 'examples', 'nested-includes.conf'), 62 | '--config', 63 | path.resolve(__dirname, '..', 'examples', 'nginx-linter.config.json'), 64 | ], stubConsole); 65 | assert.strictEqual(exitCode, 0); 66 | let message = stubConsole.invocations.log[stubConsole.invocations.log.length - 1]; 67 | assert.ok(/Validation succeeded!.*Files: 1, Errors: 0$/.test(message), `Expected success summary, got '${message}'`); 68 | }); 69 | it('location-order-complicated.conf', () => { 70 | let exitCode = main(['--include', path.resolve(__dirname, '..', 'examples', 'location-order-complicated.conf')], stubConsole); 71 | assert.strictEqual(exitCode, 0); 72 | let message = stubConsole.invocations.log[stubConsole.invocations.log.length - 1]; 73 | assert.ok(/Validation succeeded!.*Files: 1, Errors: 0$/.test(message), `Expected success summary, got '${message}'`); 74 | }); 75 | it('location-order-with-includes.conf', () => { 76 | let exitCode = main(['--include', path.resolve(__dirname, '..', 'examples', 'location-order-with-includes.conf')], stubConsole); 77 | assert.strictEqual(exitCode, 0); 78 | let message = stubConsole.invocations.log[stubConsole.invocations.log.length - 1]; 79 | assert.ok(/Validation succeeded!.*Files: 1, Errors: 0$/.test(message), `Expected success summary, got '${message}'`); 80 | }); 81 | }); 82 | }); 83 | -------------------------------------------------------------------------------- /lib/rules/rule-indentation.js: -------------------------------------------------------------------------------- 1 | 2 | function configToDescription(indentation, level) { 3 | if (level === 0) { 4 | return { type: 'nothing', count: 0 }; 5 | } 6 | if (indentation === 'tab') { 7 | return { type: 'tab', count: level }; 8 | } else { 9 | return { type: 'space', count: level * indentation }; 10 | } 11 | } 12 | 13 | function whitespaceToDescription(whitespace) { 14 | if (whitespace.length === 0) { 15 | return { type: 'nothing', count: 0 }; 16 | } else { 17 | let hasSpace = whitespace.indexOf(' ') !== -1; 18 | let hasTab = whitespace.indexOf('\t') !== -1; 19 | let type = hasSpace ? (hasTab ? 'mixed' : 'space') : (hasTab ? 'tab' : 'unknown'); 20 | let count = hasSpace !== hasTab ? whitespace.length : 0; 21 | return { type, count }; 22 | } 23 | } 24 | 25 | function initialState() { 26 | return { whitespace: '', processed: false, level: 0 }; 27 | } 28 | 29 | function increaseLevel(state) { 30 | state.level++; 31 | } 32 | 33 | function decreaseLevel(state) { 34 | state.level--; 35 | } 36 | 37 | function trackIndentation(state, whitespace) { 38 | if (!state.processed) { 39 | state.whitespace += whitespace; 40 | } 41 | } 42 | 43 | function validateIndentation(errors, indentation, state) { 44 | if (!state.processed) { 45 | let expected = configToDescription(indentation, state.level); 46 | let actual = whitespaceToDescription(state.whitespace); 47 | if (expected.type !== actual.type || expected.count !== actual.count) { 48 | let expectedDescription = `${expected.count} ${expected.type}${expected.count > 1 ? 's' : ''}`; 49 | let actualDescription = `${actual.count === 0 ? '' : actual.count + ' '}${actual.type}${actual.count > 1 ? 's' : ''}`; 50 | errors.push(`Expected ${expectedDescription}, found ${actualDescription}`); 51 | } 52 | state.processed = true; 53 | } 54 | state.processed = true; 55 | } 56 | 57 | function resetIndentation(state) { 58 | state.processed = false; 59 | state.whitespace = ''; 60 | } 61 | 62 | function invoke(node, errors, indentation, stack) { 63 | stack = stack || [initialState()]; 64 | let state = stack[0]; 65 | switch (node.type) { 66 | case 'whitespace': 67 | trackIndentation(state, node.text); 68 | break; 69 | case 'newline': 70 | resetIndentation(state); 71 | break; 72 | case 'comment': 73 | // fall through 74 | case 'directive': 75 | validateIndentation(errors, indentation, state); 76 | break; 77 | case 'punctuation': 78 | switch (node.text) { 79 | case '{': 80 | validateIndentation(errors, indentation, state); 81 | increaseLevel(state); 82 | break; 83 | case '}': 84 | decreaseLevel(state); 85 | validateIndentation(errors, indentation, state); 86 | break; 87 | } 88 | break; 89 | case 'lua:code': 90 | switch (node.text) { 91 | case 'function': 92 | // fall through 93 | case 'do': 94 | // fall through 95 | case 'then': 96 | // fall through 97 | case 'repeat': 98 | validateIndentation(errors, indentation, state); 99 | increaseLevel(state); 100 | break; 101 | case 'else': 102 | decreaseLevel(state); 103 | validateIndentation(errors, indentation, state); 104 | increaseLevel(state); 105 | break; 106 | case 'until': 107 | // fall through 108 | case 'end': 109 | // fall through 110 | case 'elseif': 111 | decreaseLevel(state); 112 | validateIndentation(errors, indentation, state); 113 | break; 114 | default: 115 | validateIndentation(errors, indentation, state); 116 | break; 117 | } 118 | break; 119 | } 120 | return stack; 121 | } 122 | 123 | function onFileStart(stack) { 124 | stack = stack || []; 125 | stack.unshift(initialState()); 126 | return stack; 127 | } 128 | 129 | function onFileEnd(stack) { 130 | stack.shift(); 131 | return stack; 132 | } 133 | 134 | module.exports = { 135 | name: 'indentation', 136 | default: 4, 137 | invoke, 138 | onFileStart, 139 | onFileEnd, 140 | }; 141 | -------------------------------------------------------------------------------- /lib/parser/parser.js: -------------------------------------------------------------------------------- 1 | let peg = require('pegjs'); 2 | 3 | module.exports = peg.generate(` 4 | { 5 | function parseNode(type, pos, customizer) { 6 | let node = { type: type, pos: pos }; 7 | customizer(node); 8 | return node; 9 | } 10 | 11 | function textNode(type, pos, text) { 12 | return parseNode(type, pos, node => node.text = text); 13 | } 14 | 15 | function punctuationNode(pos, text) { 16 | return textNode('punctuation', pos, text); 17 | } 18 | } 19 | 20 | start 21 | = Directives 22 | 23 | Directives 24 | = nodes:_ directives:Directive_* { 25 | directives.forEach(d => d.forEach(_ => nodes.push(_))); 26 | return nodes; 27 | } 28 | 29 | Directive_ 30 | = directive:(Directive) nodes:_ { 31 | nodes.unshift(directive); 32 | return nodes; 33 | } 34 | 35 | Directive 36 | = LuaDirective 37 | / StandardDirective 38 | 39 | LuaDirective 40 | = name:$(lua_directive_name) parameters:_ ob:OpenBrace body:LuaBlock cb:CloseBrace { 41 | return parseNode('directive', location(), node => { 42 | node.name = name; 43 | node.parameters = parameters; 44 | node.body = [ob, body, cb]; 45 | }); 46 | } 47 | 48 | LuaBlock 49 | = body:Lua { 50 | return parseNode('lua:block', location(), node => { 51 | node.body = body; 52 | }); 53 | } 54 | 55 | Lua 56 | = outerNodes:((Whitespace / Newline / LuaComment / LuaCode)+ / LuaObject)* { 57 | let nodes = []; 58 | outerNodes.forEach(innerNodes => innerNodes.forEach(node => nodes.push(node))); 59 | return nodes; 60 | } 61 | 62 | LuaObject 63 | = ob:OpenBrace nodes:Lua cb:CloseBrace { 64 | nodes.unshift(ob); 65 | nodes.push(cb); 66 | return nodes; 67 | } 68 | 69 | LuaCode 70 | = (single_quoted_string / double_quoted_string / raw_lua_code) { 71 | return textNode('lua:code', location(), text()); 72 | } 73 | 74 | LuaComment 75 | = '--' (whitespace* !(newline / whitespace) .)* { return textNode('lua:comment', location(), text()); } 76 | 77 | StandardDirective 78 | = name:$(directive_name) parameters:Parameters body:DirectiveBody { 79 | return parseNode('directive', location(), node => { 80 | node.name = name; 81 | node.parameters = parameters; 82 | node.body = body; 83 | }); 84 | } 85 | 86 | Parameters 87 | = parameters:_Parameter* tail:_ { 88 | let nodes = []; 89 | parameters.forEach(p => p.forEach(_ => nodes.push(_))); 90 | tail.forEach(_ => nodes.push(_)); 91 | return nodes; 92 | } 93 | 94 | _Parameter 95 | = nodes:_ parameter:Parameter { 96 | nodes.push(parameter); 97 | return nodes; 98 | } 99 | 100 | Parameter 101 | = (single_quoted_string / double_quoted_string / raw_identifier) 102 | { return textNode('parameter', location(), text()); } 103 | 104 | DirectiveBody 105 | = DirectiveBodyBlock / DirectiveBodyEmpty 106 | 107 | DirectiveBodyEmpty 108 | = semicolon:Semicolon { return [semicolon]; } 109 | 110 | DirectiveBodyBlock 111 | = openBrace:OpenBrace directives:Directives closeBrace:CloseBrace { 112 | directives.unshift(openBrace); 113 | directives.push(closeBrace); 114 | return directives; 115 | } 116 | 117 | Semicolon 118 | = semicolon { return punctuationNode(location(), text()); } 119 | 120 | OpenBrace 121 | = open_brace { return punctuationNode(location(), text()); } 122 | 123 | CloseBrace 124 | = close_brace { return punctuationNode(location(), text()); } 125 | 126 | Newline 127 | = newline { return textNode('newline', location(), text()); } 128 | 129 | Whitespace 130 | = (whitespace)+ { return textNode('whitespace', location(), text()); } 131 | 132 | Comment 133 | = '#' (whitespace* !(newline / whitespace) .)* { return textNode('comment', location(), text()); } 134 | 135 | lua_directive_name 136 | = 'access_by_lua_block' 137 | / 'balancer_by_lua_block' 138 | / 'body_filter_by_lua_block' 139 | / 'content_by_lua_block' 140 | / 'header_filter_by_lua_block' 141 | / 'init_by_lua_block' 142 | / 'init_worker_by_lua_block' 143 | / 'log_by_lua_block' 144 | / 'rewrite_by_lua_block' 145 | / 'set_by_lua_block' 146 | / 'ssl_certificate_by_lua_block' 147 | / 'ssl_session_fetch_by_lua_block' 148 | / 'ssl_session_store_by_lua_block' 149 | 150 | directive_name 151 | = single_quoted_string / double_quoted_string / raw_identifier 152 | 153 | raw_identifier 154 | = (!(whitespace / newline / semicolon / open_brace / close_brace) .) (!(whitespace / newline / semicolon / open_brace) .)* 155 | 156 | raw_lua_code 157 | = (!(whitespace / newline / open_brace / close_brace / "'" / '"') .)+ 158 | 159 | single_quoted_string 160 | = "'" ('\\\\' . / !"'" .)* "'" 161 | 162 | double_quoted_string 163 | = '"' ('\\\\' . / !'"' .)* '"' 164 | 165 | newline 166 | = '\\n' 167 | / '\\r' '\\n' 168 | 169 | whitespace 170 | = ' ' 171 | / '\\t' 172 | 173 | semicolon 174 | = ';' 175 | 176 | open_brace 177 | = '{' 178 | 179 | close_brace 180 | = '}' 181 | 182 | _ 183 | = (Whitespace / Newline / Comment)* 184 | 185 | __ 186 | = (Whitespace / Newline / Comment)+ 187 | 188 | `); 189 | -------------------------------------------------------------------------------- /test/rules/rule-location-order.spec.js: -------------------------------------------------------------------------------- 1 | let assert = require('assert'); 2 | let parser = require('../../lib/parser'); 3 | let {runRules} = require('../../lib/validator'); 4 | let locationOrderRule = require('../../lib/rules/rule-location-order'); 5 | 6 | function testConfig(name, locations, expectedErrorMessages) { 7 | let locationPrefix = 'location '; 8 | let locationSuffix = ' {\n return 200;\n}'; 9 | let contents = locations.map(loc => locationPrefix + loc + locationSuffix).join('\n'); 10 | let expectedErrors = expectedErrorMessages.map(errorMessage => { 11 | return { 12 | rule: 'location-order', 13 | text: errorMessage, 14 | type: 'error', 15 | pos: { 16 | start: { 17 | column: locationPrefix.length + locations[locations.length - 1].length + 2, 18 | line: locations.length * 3 - 2, 19 | offset: contents.length - locationSuffix.length + 1, 20 | }, 21 | end: { 22 | column: locationPrefix.length + locations[locations.length - 1].length + 3, 23 | line: locations.length * 3 - 2, 24 | offset: contents.length - locationSuffix.length + 2, 25 | }, 26 | }, 27 | }; 28 | }); 29 | return { name, contents, expectedErrors }; 30 | } 31 | 32 | const TEST_CONFIGS = [ 33 | testConfig('= lexigraphical', ['= /a', '= /b'], []), 34 | testConfig('= lexigraphical out of order', ['= /b', '= /a'], ['Expected \'=\' location directives to be in lexicographical order with longest prefix']), 35 | testConfig('= lexigraphical with same prefix', ['= /a/b', '= /a'], []), 36 | testConfig('= lexigraphical with same prefix out of order', ['= /a', '= /a/b'], ['Expected \'=\' location directives to be in lexicographical order with longest prefix']), 37 | testConfig('= before ^~', ['= /a', '^~ /b'], []), 38 | testConfig('^~ before =', ['^~ /a', '= /b'], ['Expected \'=\' location directives to be ordered before \'^~\'']), 39 | testConfig('= before ~', ['= /a', '~ /b'], []), 40 | testConfig('~ before =', ['~ /a', '= /b'], ['Expected \'=\' location directives to be ordered before \'~\'']), 41 | testConfig('= before ~*', ['= /a', '~* /b'], []), 42 | testConfig('~* before =', ['~* /a', '= /b'], ['Expected \'=\' location directives to be ordered before \'~*\'']), 43 | testConfig('= before prefix', ['= /a', '/b'], []), 44 | testConfig('prefix before =', ['/a', '= /b'], ['Expected \'=\' location directives to be ordered before \'\'']), 45 | testConfig('^~ lexigraphical', ['^~ /a', '^~ /b'], []), 46 | testConfig('^~ lexigraphical out of order', ['^~ /b', '^~ /a'], ['Expected \'^~\' location directives to be in lexicographical order with longest prefix']), 47 | testConfig('^~ lexigraphical with same prefix', ['^~ /a/b', '^~ /a'], []), 48 | testConfig('^~ lexigraphical with same prefix out of order', ['^~ /a', '^~ /a/b'], ['Expected \'^~\' location directives to be in lexicographical order with longest prefix']), 49 | testConfig('^~ before ~', ['^~ /a', '~ /b'], []), 50 | testConfig('~ before ^~', ['~ /a', '^~ /b'], ['Expected \'^~\' location directives to be ordered before \'~\'']), 51 | testConfig('^~ before ~*', ['^~ /a', '~* /b'], []), 52 | testConfig('~* before ^~', ['~* /a', '^~ /b'], ['Expected \'^~\' location directives to be ordered before \'~*\'']), 53 | testConfig('^~ before prefix', ['^~ /a', '/b'], []), 54 | testConfig('prefix before ^~', ['/a', '^~ /b'], ['Expected \'^~\' location directives to be ordered before \'\'']), 55 | testConfig('~ lexigraphical', ['~ /a', '~ /b'], []), 56 | testConfig('~ lexigraphical out of order', ['~ /b', '~ /a'], []), 57 | testConfig('~ before ~*', ['~ /a', '~* /b'], []), 58 | testConfig('~* before ~', ['~* /a', '~ /b'], []), 59 | testConfig('~ before prefix', ['~ /a', '/b'], []), 60 | testConfig('prefix before ~', ['/a', '~ /b'], ['Expected \'~\' location directives to be ordered before \'\'']), 61 | testConfig('~* lexigraphical', ['~* /a', '~* /b'], []), 62 | testConfig('~* lexigraphical out of order', ['~* /b', '~* /a'], []), 63 | testConfig('~* before prefix', ['~* /a', '/b'], []), 64 | testConfig('prefix before ~*', ['/a', '~* /b'], ['Expected \'~*\' location directives to be ordered before \'\'']), 65 | testConfig('prefix lexigraphical', ['/a', '/b'], []), 66 | testConfig('prefix lexigraphical out of order', ['/b', '/a'], ['Expected prefix location directives to be in lexicographical order with longest prefix']), 67 | testConfig('prefix lexigraphical with same prefix', ['/a/b', '/a'], []), 68 | testConfig('prefix lexigraphical with same prefix out of order', ['/a', '/a/b'], ['Expected prefix location directives to be in lexicographical order with longest prefix']), 69 | ]; 70 | 71 | describe('rules/location-order', () => { 72 | describe('#invoke()', () => { 73 | TEST_CONFIGS.forEach(({name, contents, expectedErrors}) => { 74 | it(`should have ${expectedErrors.length ? 'errors' : 'no errors'} with ${name}`, () => { 75 | let parseTree = parser.parse(contents); 76 | let actualErrors = runRules(parseTree, [locationOrderRule], {}); 77 | assert.deepStrictEqual(actualErrors, expectedErrors); 78 | }); 79 | }); 80 | }); 81 | }); 82 | -------------------------------------------------------------------------------- /bin/_cli/commands.js: -------------------------------------------------------------------------------- 1 | let parser = require('../../lib/parser'); 2 | let {runRules} = require('../../lib/validator'); 3 | let builtinRules = require('../../lib/rules').builtins; 4 | let optionsParser = require('./options'); 5 | let {table, getBorderCharacters} = require('table'); 6 | let chalk = require('chalk'); 7 | let path = require('path'); 8 | let fs = require('fs'); 9 | let os = require('os'); 10 | 11 | const TABLE_CONFIG = { 12 | border: getBorderCharacters('void'), 13 | drawHorizontalLine: () => false, 14 | columns: { 15 | 0: { // Line number 16 | alignment: 'right', 17 | paddingLeft: 2, 18 | paddingRight: 0, 19 | }, 20 | 1: { // : 21 | alignment: 'center', 22 | paddingLeft: 0, 23 | paddingRight: 0, 24 | }, 25 | 2: { // Column number 26 | alignment: 'left', 27 | paddingLeft: 0, 28 | paddingRight: 1, 29 | }, 30 | 3: { // messageType 31 | alignment: 'left', 32 | paddingLeft: 0, 33 | paddingRight: 1, 34 | }, 35 | 4: { // message 36 | alignment: 'left', 37 | paddingLeft: 0, 38 | paddingRight: 1, 39 | }, 40 | 5: { // rule 41 | alignment: 'left', 42 | paddingLeft: 0, 43 | paddingRight: 0, 44 | }, 45 | }, 46 | }; 47 | 48 | function execute(options, output) { 49 | switch (options.command) { 50 | case 'validate': 51 | return validate(options, output); 52 | default: 53 | throw `Unknown command: ${options.command}`; 54 | } 55 | } 56 | 57 | function help(options, output) { 58 | let error = typeof options === 'string' ? options : null; 59 | if (error) { 60 | output.log(error); 61 | } 62 | output.log('Usage: nginx-linter [arguments]'); 63 | output.log(''); 64 | output.log('Arguments:'); 65 | output.log('--help Print this help message and exit'); 66 | output.log(`--config Specify the configuration file to use. Default (${optionsParser.defaults.config})`); 67 | output.log(`--include Include the file or glob in nginx files to validate. Can be specified multiple times. Default (${optionsParser.defaults.includes.join(', ')})`); 68 | output.log('--exclude Exclude a file or glob in the nginx files to validate. Can be specieid multiple times. Excludes take precedence over includes'); 69 | output.log('--no-follow-includes Disable the default behaviour of following include directives found in the nginx configuration'); 70 | return error ? 1 : 0; 71 | } 72 | 73 | function validate(options, output) { 74 | let config = loadConfig(options.config); 75 | let fileNodes = parser.parseFiles({ 76 | includes: options.includes, 77 | excludes: options.excludes, 78 | maxDepth: options.followIncludes ? options.maxIncludeDepth : 0, 79 | }); 80 | let errorCount = fileNodes.map(fileNode => { 81 | let results = runValidationWithBuiltins(fileNode, config); 82 | if (results.length) { 83 | outputResults(fileNode.name, results, output); 84 | } 85 | return countErrors(results); 86 | }).reduce((a, b) => a + b, 0); 87 | outputSummary({ fileCount: fileNodes.length, errorCount }, output); 88 | return errorCount ? 1 : 0; 89 | } 90 | 91 | function countErrors(results) { 92 | return results.reduce((total, result) => { 93 | if (result.type === 'error') { 94 | return total + 1; 95 | } else if (result.nested) { 96 | return total + countErrors(result.nested.results); 97 | } else { 98 | return total; 99 | } 100 | }, 0); 101 | } 102 | 103 | function runValidationWithBuiltins(parseTree, config) { 104 | return runRules(parseTree, builtinRules, config); 105 | } 106 | 107 | function loadConfig(configFile) { 108 | let fileName = configFile; 109 | if (fileName[0] === '~') { 110 | fileName = path.join(os.homedir(), fileName.slice(1)); 111 | } 112 | let contents = null; 113 | try { 114 | contents = fs.readFileSync(fileName, 'utf8'); 115 | } catch (e) { 116 | if (configFile === optionsParser.defaults.config) { 117 | return {}; 118 | } 119 | throw e; 120 | } 121 | return JSON.parse(contents); 122 | } 123 | 124 | function outputResults(fileName, results, output) { 125 | output.log(''); 126 | output.log(chalk.underline(fileName)); 127 | outputInnerResults(' ', fileName, results, output); 128 | } 129 | 130 | function outputInnerResults(indent, fileName, results, output) { 131 | let tableData = []; 132 | let nestedResults = []; 133 | let hiddenResults = {}; 134 | results.forEach(({pos, type, text, nested, rule}) => { 135 | if (nested) { 136 | nestedResults.push(nested); 137 | } else { 138 | hiddenResults[rule] = hiddenResults[rule] || {}; 139 | hiddenResults[rule][type] = hiddenResults[rule][type] || {total: 0, hidden: 0}; 140 | hiddenResults[rule][type].total += 1; 141 | if (hiddenResults[rule][type].total < 1000) { 142 | tableData.push([ 143 | chalk.dim(pos.start.line), 144 | chalk.dim(':'), 145 | chalk.dim(pos.start.column), 146 | type === 'error' ? chalk.red(type) : chalk.yellow(type), 147 | text, 148 | chalk.dim(rule), 149 | ]); 150 | } else { 151 | hiddenResults[rule][type].hidden += 1; 152 | } 153 | } 154 | }); 155 | Object.entries(hiddenResults).forEach(([rule, ruleHiddenResults]) => { 156 | Object.entries(ruleHiddenResults).forEach(([type, ruleTypeHiddenResults]) => { 157 | if (ruleTypeHiddenResults.hidden > 0) { 158 | tableData.push([ 159 | '', 160 | '', 161 | '', 162 | type === 'error' ? chalk.red(type) : chalk.yellow(type), 163 | ruleTypeHiddenResults.hidden + ' more hidden', 164 | chalk.dim(rule), 165 | ]); 166 | } 167 | }); 168 | }); 169 | if (tableData.length) { 170 | output.log(table(tableData, TABLE_CONFIG)); 171 | } 172 | nestedResults.forEach(nested => { 173 | let includeFileName = path.relative(path.dirname(path.resolve(fileName)), nested.fileName); 174 | output.log(chalk.bold(indent + 'within'), chalk.underline(includeFileName)); 175 | outputInnerResults(indent + ' ', nested.fileName, nested.results, output); 176 | }); 177 | } 178 | 179 | function outputSummary({fileCount, errorCount}, output) { 180 | output.log(''); 181 | output.log(`${errorCount ? chalk.red('Validation failed!') : chalk.green('Validation succeeded!')} Files: ${fileCount}, Errors: ${errorCount}`); 182 | } 183 | 184 | function main(args, output) { 185 | try { 186 | let options = optionsParser.parse(args); 187 | if (typeof options === 'string' || options.command === 'help') { 188 | return help(options, output); 189 | } 190 | return execute(options, output); 191 | } catch (e) { 192 | output.error('Unexpected error:', e); 193 | return 1; 194 | } 195 | } 196 | 197 | module.exports = { 198 | main, 199 | }; 200 | -------------------------------------------------------------------------------- /test/parser.spec.js: -------------------------------------------------------------------------------- 1 | let assert = require('assert'); 2 | let fs = require('fs'); 3 | let path = require('path'); 4 | let parser = require('../lib/parser'); 5 | 6 | function punctuation(text) { 7 | return { type: 'punctuation', text }; 8 | } 9 | 10 | function parameter(text) { 11 | return { type: 'parameter', text }; 12 | } 13 | 14 | function directive(name, parameters, body) { 15 | if (body == null) { 16 | body = [punctuation(';')]; 17 | } else { 18 | body.unshift(punctuation('{')); 19 | body.push(punctuation('}')); 20 | } 21 | parameters = parameters || []; 22 | parameters = parameters.map(parameter); 23 | return { 24 | type: 'directive', 25 | name, 26 | parameters, 27 | body, 28 | }; 29 | } 30 | 31 | function luaBlock(body) { 32 | return { 33 | type: 'lua:block', 34 | body, 35 | }; 36 | } 37 | 38 | function lua(text) { 39 | return { 40 | type: 'lua:code', 41 | text, 42 | }; 43 | } 44 | 45 | function sanitizeParseTree(node) { 46 | if (Array.isArray(node)) { 47 | return node.filter(subNode => ['whitespace', 'newline', 'comment', 'lua:comment'].indexOf(subNode.type) === -1).map(sanitizeParseTree); 48 | } else { 49 | let sanitizeNode = Object.assign({}, node); 50 | delete sanitizeNode['pos']; 51 | if (sanitizeNode.type === 'directive') { 52 | sanitizeNode.parameters = sanitizeParseTree(sanitizeNode.parameters); 53 | sanitizeNode.body = sanitizeParseTree(sanitizeNode.body); 54 | } else if (sanitizeNode.type === 'lua:block') { 55 | sanitizeNode.body = sanitizeParseTree(sanitizeNode.body); 56 | } 57 | return sanitizeNode; 58 | } 59 | } 60 | 61 | const TEST_CONFIGS = { 62 | 'simple.conf': [ 63 | directive('events', null, []), 64 | directive('http', null, [ 65 | directive('server', null, [ 66 | directive('listen', ['80']), 67 | directive('location', ['=', '/ok'], [ 68 | directive('return', ['200']), 69 | ]), 70 | ]), 71 | ]), 72 | ], 73 | 'single-quotes.conf': [ 74 | directive('events', null, []), 75 | directive('http', null, [ 76 | directive('server', null, [ 77 | directive('listen', ['80']), 78 | directive('location', ['=', '\'/o\\\'k\''], [ 79 | directive('return', ['200']), 80 | ]), 81 | ]), 82 | ]), 83 | ], 84 | 'if-is-evil.conf': [ 85 | directive('events', null, []), 86 | directive('http', null, [ 87 | directive('server', null, [ 88 | directive('listen', ['80']), 89 | directive('location', ['=', '/ok'], [ 90 | directive('if', ['($request_method', '=', 'POST)'], [ 91 | directive('return', ['405']), 92 | ]), 93 | directive('return', ['200']), 94 | ]), 95 | directive('location', ['=', '/p/ok-but-bad'], [ 96 | directive('if', ['($request_method', '=', 'POST)'], [ 97 | directive('return', ['405']), 98 | ]), 99 | directive('return', ['200']), 100 | ]), 101 | directive('location', ['=', '/rewrite-from'], [ 102 | directive('if', ['($request_method', '=', 'POST)'], [ 103 | directive('rewrite', ['^', '/rewrite-to', 'last']), 104 | ]), 105 | directive('return', ['200']), 106 | ]), 107 | directive('location', ['=', '/rewrite-to'], [ 108 | directive('return', ['200']), 109 | ]), 110 | directive('location', ['=', '/y/rewrite-bad-but-ok'], [ 111 | directive('if', ['($request_method', '=', 'POST)'], [ 112 | directive('rewrite', ['^', '/rewrite-to', 'break']), 113 | ]), 114 | directive('return', ['200']), 115 | ]), 116 | directive('location', ['=', '/z/rewrite-bad'], [ 117 | directive('if', ['($request_method', '=', 'POST)'], [ 118 | directive('rewrite', ['^', '/rewrite-to', 'break']), 119 | ]), 120 | directive('return', ['200']), 121 | ]), 122 | directive('location', ['/crash'], [ 123 | directive('set', ['$true', '1']), 124 | directive('if', ['($true)'], [ 125 | directive('proxy_pass', ['http://127.0.0.1:8080/']), 126 | ]), 127 | directive('if', ['($true)'], []), 128 | ]), 129 | ]), 130 | ]), 131 | ], 132 | 'lua.conf': [ 133 | directive('events', null, []), 134 | directive('http', null, [ 135 | directive('server', null, [ 136 | directive('listen', ['80']), 137 | directive('location', ['=', '/ok'], [ 138 | directive('content_by_lua_block', null, [ 139 | luaBlock([ 140 | lua('local'), 141 | lua('_M'), 142 | lua('='), 143 | punctuation('{'), 144 | punctuation('}'), 145 | lua('function'), 146 | lua('_M.go()'), 147 | lua('if'), 148 | lua('ngx.req.get_body_data()'), 149 | lua('then'), 150 | lua('ngx.say('), 151 | lua('"Got data"'), 152 | lua(')'), 153 | lua('else'), 154 | lua('ngx.say('), 155 | lua('"No data"'), 156 | lua(')'), 157 | lua('end'), 158 | lua('end'), 159 | lua('_M.go()'), 160 | ]), 161 | ]), 162 | ]), 163 | ]), 164 | ]), 165 | ], 166 | 'if.conf': [ 167 | directive('http', null, [ 168 | directive('server', null, [ 169 | directive('listen', ['80']), 170 | directive('location', ['=', '/ok'], [ 171 | directive('if', ['($http_user_agent', '~', 'MSIE)'], [ 172 | directive('rewrite', ['^(.*)$', '/msie/$1', 'break']), 173 | ]), 174 | directive('if', ['($http_cookie', '~*', '"id=([^;]+)(?:;|$)"', ')'], [ 175 | directive('set', ['$id', '$1']), 176 | ]), 177 | directive('if', ['($request_method', '=', 'POST)'], [ 178 | directive('return', ['405']), 179 | ]), 180 | directive('if', ['($slow)'], [ 181 | directive('limit_rate', ['10k']), 182 | ]), 183 | directive('if', ['($invalid_referer)'], [ 184 | directive('return', ['403']), 185 | ]), 186 | directive('return', ['200']), 187 | ]), 188 | ]), 189 | ]), 190 | ], 191 | 'strings.conf': [ 192 | directive('http', [], [ 193 | directive('map', ['$request_uri', '$mapped_response_code'], [ 194 | directive('example.*', ['400']), 195 | directive('"{a}"', ['429']), 196 | directive('default', ['200']), 197 | ]), 198 | directive('server', null, [ 199 | directive('listen', ['80']), 200 | directive('location', ['=', '/'], [ 201 | directive('return', ['$mapped_response_code']), 202 | ]), 203 | ]), 204 | ]), 205 | ], 206 | }; 207 | 208 | describe('parser', () => { 209 | describe('#parse()', () => { 210 | for (let configFileName in TEST_CONFIGS) { 211 | let expectedParseTree = TEST_CONFIGS[configFileName]; 212 | it(`should handle ${configFileName} file`, () => { 213 | let actualParseTree = parser.parse(fs.readFileSync(path.resolve(__dirname, 'examples', configFileName), 'utf8')); 214 | assert.deepStrictEqual(sanitizeParseTree(actualParseTree), expectedParseTree); 215 | }); 216 | } 217 | }); 218 | }); 219 | -------------------------------------------------------------------------------- /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 | 635 | Copyright (C) 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 | Copyright (C) 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 | --------------------------------------------------------------------------------