libnmap 0.4.19 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,110 @@
1
+ 'use strict';
2
+ // Compiles the OpenSSL and nmap sources to static libraries, as position-independent code.
3
+ // Uses the configure and make of each project. No nmap or openssl program is built.
4
+ // Prints the link inputs (libraries) for binding.gyp. All other output goes to stderr.
5
+
6
+ const fs = require('node:fs');
7
+ const os = require('node:os');
8
+ const path = require('node:path');
9
+ const { execFileSync } = require('node:child_process');
10
+
11
+ const root = path.join(__dirname, '..');
12
+ const dir = path.join(root, 'src', 'nmap');
13
+ const stamp = path.join(dir, '.libnmap-build');
14
+ const linkmk = path.join(__dirname, 'link.mk');
15
+ const ssl = path.join(root, 'src', 'openssl');
16
+ const sslPrefix = path.join(ssl, '.libnmap');
17
+ const sslStamp = path.join(sslPrefix, '.libnmap-build');
18
+ const { nmap: pin, openssl: sslPin } = require(path.join(root, 'package.json'));
19
+
20
+ const FLAGS = '-fPIC -O2 -w';
21
+
22
+ // Only nmap. The bundled libraries make the build independent of system packages.
23
+ const CONFIGURE = [
24
+ '--without-zenmap',
25
+ '--without-ndiff',
26
+ '--without-nping',
27
+ '--without-ncat',
28
+ '--with-libpcap=included',
29
+ '--with-libpcre=included',
30
+ '--with-libz=included',
31
+ '--with-liblua=included',
32
+ '--with-libdnet=included',
33
+ '--with-liblinear=included',
34
+ // The OpenSSL that this script compiles, not the system OpenSSL.
35
+ `--with-openssl=${sslPrefix}`,
36
+ '--with-libssh2=included',
37
+ ];
38
+
39
+ // Only the static libraries and the headers.
40
+ const SSL_CONFIGURE = ['no-shared', 'no-tests', 'no-apps', 'no-docs', '-fPIC', '-w',
41
+ `--prefix=${sslPrefix}`, '--libdir=lib'];
42
+
43
+ const sslStampText = JSON.stringify({ commit: sslPin.commit, configure: SSL_CONFIGURE });
44
+
45
+ const stampText = JSON.stringify({ commit: pin.commit, openssl: sslPin.commit, flags: FLAGS,
46
+ configure: CONFIGURE });
47
+
48
+ function run(cmd, args, env = process.env, cwd = dir) {
49
+ // stdout is reserved for the link inputs.
50
+ execFileSync(cmd, args, { cwd, env, stdio: ['ignore', 2, 2] });
51
+ }
52
+
53
+ function buildOpenssl(make, jobs) {
54
+ if (fs.existsSync(sslStamp) && fs.readFileSync(sslStamp, 'utf8') === sslStampText) return;
55
+ if (!fs.existsSync(path.join(ssl, 'Configure'))) {
56
+ throw new Error('src/openssl is empty. Run: node scripts/fetch-sources.js');
57
+ }
58
+
59
+ console.error('libnmap: configuring OpenSSL');
60
+ run('perl', ['Configure', ...SSL_CONFIGURE], process.env, ssl);
61
+ console.error('libnmap: compiling OpenSSL');
62
+ run(make, ['-j', jobs, 'build_libs'], process.env, ssl);
63
+ run(make, ['install_dev'], process.env, ssl);
64
+ fs.writeFileSync(sslStamp, sslStampText);
65
+ }
66
+
67
+ function isBuilt() {
68
+ return fs.existsSync(stamp) && fs.readFileSync(stamp, 'utf8') === stampText
69
+ && fs.existsSync(path.join(dir, 'libnmap.a'));
70
+ }
71
+
72
+ function build() {
73
+ if (!fs.existsSync(path.join(dir, 'configure'))) {
74
+ throw new Error('src/nmap is empty. Run: node scripts/fetch-sources.js');
75
+ }
76
+ const make = process.env.MAKE || 'make';
77
+ const jobs = String(Math.max(1, os.cpus().length));
78
+
79
+ buildOpenssl(make, jobs);
80
+
81
+ console.error('libnmap: configuring nmap');
82
+ run('./configure', CONFIGURE, { ...process.env, CFLAGS: FLAGS, CXXFLAGS: FLAGS });
83
+ console.error('libnmap: compiling nmap');
84
+ run(make, ['-j', jobs, '-f', linkmk, 'libnmap.a']);
85
+ fs.writeFileSync(stamp, stampText);
86
+ }
87
+
88
+ // Makes the Makefile's relative paths absolute, because gyp links from another directory.
89
+ function absolute(token) {
90
+ // The static OpenSSL of this build, and not a system library with the same name.
91
+ if (token === '-lssl' || token === '-lcrypto') return path.join(sslPrefix, 'lib', `lib${token.slice(2)}.a`);
92
+ if (token.startsWith('-L')) return `-L${path.resolve(dir, token.slice(2))}`;
93
+ if (token.startsWith('-')) return token;
94
+ return path.resolve(dir, token);
95
+ }
96
+
97
+ function linkInputs() {
98
+ const make = process.env.MAKE || 'make';
99
+ const out = execFileSync(make, ['-s', '--no-print-directory', '-f', linkmk,
100
+ 'libnmap-link'], { cwd: dir, stdio: ['ignore', 'pipe', 2] }).toString();
101
+ return out.split(/\s+/).filter(Boolean).map(absolute);
102
+ }
103
+
104
+ try {
105
+ if (!isBuilt()) build();
106
+ for (const token of linkInputs()) console.log(token);
107
+ } catch (err) {
108
+ console.error(`libnmap: ${err.message}`);
109
+ process.exit(1);
110
+ }
@@ -0,0 +1,89 @@
1
+ 'use strict';
2
+ // Gets the nmap and OpenSSL sources before the build: existing files, git submodule, or pinned download.
3
+
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const { execFileSync } = require('node:child_process');
8
+
9
+ const root = path.join(__dirname, '..');
10
+ const pkg = require(path.join(root, 'package.json'));
11
+
12
+ // Each source has its pin in package.json and a file that shows that the sources are there.
13
+ const sources = [
14
+ { name: 'nmap', pin: pkg.nmap, marker: 'configure' },
15
+ { name: 'openssl', pin: pkg.openssl, marker: 'Configure' },
16
+ ].map((source) => ({ ...source, dest: path.join(root, 'src', source.name) }));
17
+
18
+ function hasSources(source) {
19
+ return fs.existsSync(path.join(source.dest, source.marker));
20
+ }
21
+
22
+ function git(args, opts = {}) {
23
+ return execFileSync('git', args, { cwd: root, stdio: ['ignore', 'pipe', 'inherit'], ...opts })
24
+ .toString().trim();
25
+ }
26
+
27
+ function isGitCheckout() {
28
+ if (!fs.existsSync(path.join(root, '.git')) || !fs.existsSync(path.join(root, '.gitmodules'))) {
29
+ return false;
30
+ }
31
+ try {
32
+ return git(['rev-parse', '--show-toplevel']) === fs.realpathSync(root);
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ async function download({ name, pin, dest }) {
39
+ const url = `${pin.repository}/archive/${pin.commit}.tar.gz`;
40
+ console.log(`libnmap: downloading ${name} ${pin.version} (${pin.commit.slice(0, 12)})`);
41
+ const res = await fetch(url);
42
+ if (!res.ok) throw new Error(`download of ${url} failed: HTTP ${res.status}`);
43
+
44
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'libnmap-'));
45
+ try {
46
+ const archive = path.join(tmp, `${name}.tar.gz`);
47
+ fs.writeFileSync(archive, Buffer.from(await res.arrayBuffer()));
48
+ fs.mkdirSync(dest, { recursive: true });
49
+ execFileSync('tar', ['-xzf', archive, '-C', dest, '--strip-components=1'], { stdio: 'inherit' });
50
+ } finally {
51
+ fs.rmSync(tmp, { recursive: true, force: true });
52
+ }
53
+ }
54
+
55
+ function check({ name, pin, dest }) {
56
+ const actual = git(['-C', dest, 'rev-parse', 'HEAD']);
57
+ if (actual !== pin.commit) {
58
+ console.error(`libnmap: src/${name} is at ${actual}, but package.json pins ${pin.commit}.`);
59
+ console.error(`Set "${name}.commit" in package.json to the submodule commit.`);
60
+ process.exit(1);
61
+ }
62
+ }
63
+
64
+ async function main() {
65
+ if (process.argv.includes('--check')) {
66
+ sources.forEach(check);
67
+ return;
68
+ }
69
+
70
+ for (const source of sources) {
71
+ if (hasSources(source)) continue;
72
+
73
+ if (isGitCheckout()) {
74
+ console.log(`libnmap: running git submodule update --init src/${source.name}`);
75
+ git(['submodule', 'update', '--init', '--depth', '1', `src/${source.name}`], { stdio: 'inherit' });
76
+ } else {
77
+ await download(source);
78
+ }
79
+
80
+ if (!hasSources(source)) {
81
+ throw new Error(`no ${source.name} sources in ${source.dest}`);
82
+ }
83
+ }
84
+ }
85
+
86
+ main().catch((err) => {
87
+ console.error(`libnmap: ${err.message}`);
88
+ process.exit(1);
89
+ });
@@ -0,0 +1,13 @@
1
+ # Compiles nmap as a static library and not as a program. nmap's own Makefile has the rules.
2
+ # Run from src/nmap: make -f ../../scripts/link.mk libnmap.a
3
+ include Makefile
4
+
5
+ # The same inputs as the nmap program, but without main.o and without the link step.
6
+ libnmap.a: build-netutil build-liblinear build-pcap build-zlib build-pcre build-nsock build-nbase build-dnet build-lua $(if $(strip $(LIBSSH2_LIBS)),build-libssh2) $(OBJS)
7
+ rm -f $@
8
+ $(AR) rcs $@ $(OBJS)
9
+
10
+ # Prints the libraries that the node module links.
11
+ libnmap-link:
12
+ @echo libnmap.a
13
+ @echo $(LDFLAGS) $(LIBS)
package/src/addon.cc ADDED
@@ -0,0 +1,101 @@
1
+ /* N-API binding: run(args) calls nmap_main() one time. Use it only from lib/worker.js.
2
+ *
3
+ * Nmap keeps its state in globals and calls exit() on errors, so a process can
4
+ * run nmap_main() one time only. lib/worker.js gives each scan its own process. */
5
+ #define NAPI_VERSION 8
6
+ #include <node_api.h>
7
+
8
+ #include <locale.h>
9
+ #include <stdio.h>
10
+ #include <stdlib.h>
11
+ #include <string.h>
12
+
13
+ #include "nmap.h"
14
+ #include "NmapOps.h"
15
+
16
+ extern NmapOps o;
17
+ extern void set_program_name(const char *name);
18
+
19
+ static bool nmap_used = false;
20
+
21
+ static napi_value
22
+ Run(napi_env env, napi_callback_info info)
23
+ {
24
+ size_t argc = 1;
25
+ napi_value arg, item, result;
26
+ bool is_array = false;
27
+ uint32_t length = 0, i;
28
+ char **argv;
29
+ int rc;
30
+
31
+ if (napi_get_cb_info(env, info, &argc, &arg, NULL, NULL) != napi_ok
32
+ || argc < 1
33
+ || napi_is_array(env, arg, &is_array) != napi_ok || !is_array
34
+ || napi_get_array_length(env, arg, &length) != napi_ok) {
35
+ napi_throw_type_error(env, NULL, "run(args) needs an array of strings");
36
+ return NULL;
37
+ }
38
+ if (nmap_used) {
39
+ napi_throw_error(env, "ERR_NMAP_USED",
40
+ "nmap_main() can run one time in a process. Start a new worker.");
41
+ return NULL;
42
+ }
43
+
44
+ /* argv[0] is the program name, as on a command line. */
45
+ argv = (char **)calloc((size_t)length + 2, sizeof(char *));
46
+ if (argv == NULL) {
47
+ napi_throw_error(env, NULL, "out of memory");
48
+ return NULL;
49
+ }
50
+ argv[0] = strdup("nmap");
51
+ for (i = 0; i < length; i++) {
52
+ napi_valuetype type;
53
+ size_t size = 0;
54
+
55
+ if (napi_get_element(env, arg, i, &item) != napi_ok
56
+ || napi_typeof(env, item, &type) != napi_ok
57
+ || type != napi_string
58
+ || napi_get_value_string_utf8(env, item, NULL, 0, &size) != napi_ok
59
+ || (argv[i + 1] = (char *)malloc(size + 1)) == NULL) {
60
+ napi_throw_type_error(env, NULL, "every argument must be a string");
61
+ return NULL;
62
+ }
63
+ napi_get_value_string_utf8(env, item, argv[i + 1], size + 1, &size);
64
+ }
65
+
66
+ /* The same steps as main() in upstream main.cc. */
67
+ nmap_used = true;
68
+ #ifdef __APPLE__
69
+ setprogname("nmap"); /* getopt() error messages print this name */
70
+ #endif
71
+ o.locale = strdup(setlocale(LC_CTYPE, NULL));
72
+ set_program_name(argv[0]);
73
+ rc = nmap_main((int)length + 1, argv);
74
+
75
+ fflush(stdout);
76
+ fflush(stderr);
77
+ napi_create_int32(env, rc, &result);
78
+ return result;
79
+ }
80
+
81
+ static napi_value
82
+ Version(napi_env env, napi_callback_info info)
83
+ {
84
+ napi_value result;
85
+ (void)info;
86
+ napi_create_string_utf8(env, NMAP_VERSION, NAPI_AUTO_LENGTH, &result);
87
+ return result;
88
+ }
89
+
90
+ static napi_value
91
+ Init(napi_env env, napi_value exports)
92
+ {
93
+ napi_property_descriptor props[] = {
94
+ { "run", NULL, Run, NULL, NULL, NULL, napi_default, NULL },
95
+ { "version", NULL, Version, NULL, NULL, NULL, napi_default, NULL },
96
+ };
97
+ napi_define_properties(env, exports, sizeof(props) / sizeof(props[0]), props);
98
+ return exports;
99
+ }
100
+
101
+ NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
package/.travis.yml DELETED
@@ -1,21 +0,0 @@
1
- os:
2
- - linux
3
- - osx
4
-
5
- addons:
6
- apt:
7
- packages:
8
- - nmap
9
-
10
- language: node_js
11
- node_js:
12
- - "4"
13
- - "5"
14
- - "6"
15
- - "7"
16
- - "8"
17
- - "9"
18
- - "10"
19
-
20
- before_install:
21
- - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then brew update && brew install nmap; fi